Important
This repository is not a replacement for the k-Wave toolbox. It provides a reproducible simulation framework, configuration system, validation procedures, output organization, and analysis tools built on top of k-Wave 1.4.1.
This repository provides a MATLAB framework for reproducible 2D and 3D elastic shear-wave simulations using the pinned k-Wave 1.4.1 toolbox.
The framework currently includes:
- a validated homogeneous directional 2D reference case;
- 2D circular-inclusion, field-regime, and finite-contact benchmarks;
- configured 3D directional and multi-source simulations;
- multiface finite-contact source banks;
- generated angular source banks, including N8 P2, N32 P8, and N128 P8 cases;
- heterogeneous 3D spheres, finite cylinders, bilayers, and combined geometry;
- full 3D harmonic-field analysis and P/S diagnostics;
- central x-z plane export for external REQ validation;
- timestamped outputs with requested and resolved configurations;
- deterministic, resumable simulation campaigns and Cartesian parameter sweeps;
- campaign-level JSON summaries and CSV run indices;
- structured numerical and physical validation reports.
Historical scripts under archive/ are retained as implementation evidence and
are not used by the current configured workflow.
The complete user guide is available at:
Recommended starting points:
Physics documentation:
- Finite-Contact Sources
- Multiface and Angular Sources
- Heterogeneous Materials
- Harmonic Analysis and P/S Separation
Run all commands from the repository root.
Display the CLI help:
./scripts/kwsim-run --helpValidate a configuration without running k-Wave:
./scripts/kwsim-run \
configs/kwsim/two_d/homogeneous_directional_cli.json \
--dry-runExecute the verified 2D configured reference:
./scripts/kwsim-run \
configs/kwsim/two_d/homogeneous_directional_cli.jsonThe verified reference completed successfully and produced:
truth SWS: 2.0000 m/s
estimated SWS: 2.0043 m/s
relative error: 0.214%
P/S energy: 4.974e-4
steady change: 2.014e-5
overall valid: yes
Runtime depends on hardware and configuration. The verified reference completed in approximately 23 seconds on the development computer.
./scripts/kwsim-run \
configs/kwsim/three_d/homogeneous_directional_req_validation.json \
--dry-run./scripts/kwsim-run \
configs/kwsim/three_d/heterogeneous_sphere_3d.json \
--dry-run./scripts/kwsim-run \
configs/kwsim/three_d/homogeneous_generated_angular_n32_p8_req_validation.json \
--dry-runThese three commands have been verified through the configured dry-run path.
A dry run resolves and validates the configuration without executing the solver or creating outputs.
The campaign system expands one validated base configuration into a deterministic Cartesian parameter sweep. Every expanded configuration is validated before solver execution, and completed runs can be resumed safely without repeating computation.
Campaigns are appropriate for:
- material-property sweeps;
- frequency and seed sweeps;
- source-regime comparisons;
- convergence and sensitivity studies;
- heterogeneous inclusion studies;
- REQ validation and Adaptive REQ dataset generation.
Example campaign files include:
configs/campaigns/kwsim/scientific/homogeneous_directional_2d_sweep.json
configs/campaigns/kwsim/smoke/homogeneous_partial_3d_n8_p2_smoke.json
configs/campaigns/kwsim/smoke/homogeneous_generated_angular_n32_p8_smoke.json
configs/campaigns/kwsim/smoke/heterogeneous_large_sphere_n32_p8_smoke.json
A campaign contains one existing base configuration and an ordered list of parameters to sweep. Multiple sweep parameters are expanded as a deterministic Cartesian product, with the last declared parameter varying fastest.
Standard nested paths are supported:
medium.cs_m_s
source.f0_hz
req_validation.cs_guess_m_s
seed
Indexed paths can address one existing array element:
geometry.objects[1].cs_m_s
geometry.objects[1].radius_m
source.vibrators[5].weight
Indices are one-based and must refer to elements already present in the base configuration.
Expand a campaign without executing simulations:
addpath("src");
> **Campaign API:** New code should use the backend-neutral
> `simcampaigns` package. The older `kwsim.campaigns` namespace is
> retained temporarily for compatibility with existing k-Wave workflows.
[runs, expansion] = simcampaigns.expandCampaign( ...
"configs/campaigns/kwsim/smoke/homogeneous_partial_3d_n8_p2_smoke.json");
disp(expansion.run_count);
disp(string({runs.run_id})');Validate every expanded configuration through the normal configured dry-run path:
[~, validation] = simcampaigns.validateCampaign( ...
"configs/campaigns/kwsim/smoke/homogeneous_partial_3d_n8_p2_smoke.json");
disp(validation.summary);
assert(validation.valid);Campaign validation completes before solver execution begins. If any expanded configuration is invalid, execution is aborted before campaign simulation outputs are created.
Execute or resume a campaign:
report = simcampaigns.runCampaign( ...
"configs/campaigns/kwsim/smoke/homogeneous_partial_3d_n8_p2_smoke.json", ...
Resume=true, ...
ContinueOnError=true);
disp(report.summary);Each expanded run receives a deterministic identifier:
run_000001_<hash>
The identifier contains the expansion ordinal and a SHA-256-derived configuration hash. The hash is computed before campaign-controlled output paths are injected, so relocating a campaign does not change run identity.
With Resume=true, a previously completed run with a matching hash is reported
as:
skipped_completed
and the solver is not executed again. Existing directories without a valid matching completion marker are reported as:
blocked_existing
and are never overwritten automatically.
Campaign outputs are organized as:
outputs/campaigns/<campaign_name>/
├── campaign_summary.json
├── campaign_runs.csv
├── run_000001_<hash>/
├── run_000002_<hash>/
└── ...
Each run directory contains the standard configured-run artifacts enabled by the base configuration, such as:
config/resolved_config.json
data/result.mat
data/summary.mat
data/validation_report.mat
data/validation_summary.txt
data/req_validation_sample.mat
figures/
manifest.txt
campaign_run.json
campaign_summary.json records campaign execution state, including completed,
resumed, failed, blocked, pending, and running counts.
campaign_runs.csv provides one row per expanded simulation. It includes:
- deterministic run identity and execution status;
- scenario, dimension, seed, and frequency;
- background and first-inclusion material properties when available;
- solver runtime and structured validation metrics;
- REQ readiness and source-geometry metrics;
- paths to the resolved configuration, validation report, and REQ sample;
- error identifiers and messages for failed or blocked runs.
When reading the table in MATLAB, specify the comma delimiter explicitly:
T = readtable( ...
"outputs/campaigns/<campaign_name>/campaign_runs.csv", ...
Delimiter=",", ...
TextType="string");For the complete campaign contract, indexed-path rules, material behavior, state model, resume logic, failure recovery, output artifacts, examples, and Adaptive REQ workflow, see:
Reproducible Simulation Campaigns
The lower-level MATLAB interface remains available.
addpath('/absolute/path/to/k-wave_simulations/src');
cfg = kwsim.two_d.defaultConfig();
[result, report] = kwsim.two_d.run(cfg);
disp(report.summary);Save a self-contained result and diagnostic figures:
kwsim.io.saveRun(result, report, 'outputs/my_run');Visualize the measured axial field:
kwsim.viz.plotAxialField(result, report);Compare motion components:
kwsim.viz.plotMotionComponents(result, report);The complete 2D reference example is:
examples/two_d/run_directional_homogeneous_benchmark.m
examples/two_d/run_directional_homogeneous_benchmark.m
The compact cross-run reliability suite is:
examples/two_d/run_directional_homogeneous_validation.m
examples/two_d/run_circular_inclusion_benchmark.m
This benchmark compares a contrast inclusion against homogeneous and zero-contrast cases before saving material and field diagnostics.
examples/two_d/run_field_regimes_benchmark.m
This benchmark runs directional, partial, and broad angular source regimes and evaluates angular diagnostics.
Definitions and source limitations are documented in:
benchmarks/+kwsim_benchmarks/+field_regimes_2d/README.md
examples/two_d/run_finite_contacts_benchmark.m
The benchmark includes validated finite perimeter contacts while retaining point-contact comparisons.
Additional details are documented in:
docs/finite_contacts_2d.md
The current 3D framework supports:
- homogeneous directional single-contact fields;
- same-face and multiface finite-contact source banks;
- generated angular source banks;
- controlled in-plane and out-of-plane contributors;
- independent source phases and transverse polarizations;
- total-drive normalization across source counts;
- N8 P2, N32 P8, and N128 P8 configurations;
- spherical inclusions;
- arbitrarily oriented finite cylinders;
- arbitrarily oriented bilayers;
- combined heterogeneous geometry with defined precedence;
- full-volume harmonic fields;
- 3D P/S diagnostics;
- central x-z acquisition-plane export;
- material and SWS truth maps;
- external REQ-readiness assessment.
The geometry precedence is:
background
-> bilayer
-> cylinders
-> spheres
Later geometry types overwrite earlier assignments where regions overlap.
Source count alone does not establish diffusivity.
Use the following terminology carefully:
directional
multi-source
partial 3D
broad angular
projected 3D
diffuse idealization
N8 P2, N32 P8, and N128 P8 describe source-bank construction:
N = total number of sources
P = configured number of explicitly in-plane contributors
They do not guarantee an ideal isotropic diffuse field.
See:
Public coordinates are:
x = lateral
y = elevational / out-of-plane
z = axial / depth
Public 2D maps use:
[Nz, Nx]
suffix: _zx
Public 3D volumes use:
[Nz, Ny, Nx]
suffix: _zyx
k-Wave solver orientation is handled inside the adapter layer.
Velocity phasors use m/s.
Displacement phasors use m.
The phasor convention is:
signal(t) = real(phasor * exp(1i*2*pi*f0*t)) + dc
The framework uses prescribed boundary particle velocity.
Typical contact models are:
2D: finite_segment
3D: finite_disk
A left-face source with principal propagation in +x and polarization in z is transverse and therefore shear-dominant.
The source is a controlled boundary-motion approximation. It is not a complete model of actuator mass, force, coupling, contact pressure, or electromechanics.
See:
Development configurations commonly use:
cp = reduced_cp_factor * cs
with a typical factor of 10.
This reduces the time-step cost while preserving an admissible elastic model.
It is an explicit computational approximation, not a claim that tissue has a compressional speed near 20 m/s.
Configurations with an inadmissible P/S speed relationship are rejected during validation.
The solver runs in the time domain.
Late-time samples are reduced to complex fields at the source frequency using the configured harmonic-analysis method.
The current 3D baseline uses:
"analysis": {
"harmonic_method": "least_squares",
"temporal_window": "none",
"remove_mean": true
}The resulting complex field contains harmonic amplitude and phase.
Temporal harmonic extraction and spatial wavenumber analysis are separate steps:
time-domain simulation
-> extraction at f0
-> complex spatial field
-> spatial spectrum
-> wavenumber or REQ analysis
See:
Harmonic Analysis and P/S Separation
Configured runs may evaluate:
- configuration and resource preflight;
- grid resolution and points per wavelength;
- source fundamental-frequency fraction;
- finite harmonic fields;
- P/S energy ratio;
- cross-polarization and longitudinal leakage;
- harmonic steady-state change;
- homogeneous SWS agreement;
- source-bank angular properties;
- geometry containment and discretization;
- repeatability;
- REQ readiness.
Validation thresholds are scenario-specific.
A solver completing successfully does not automatically mean that the result is scientifically valid.
Always inspect:
data/validation_summary.txt
config/resolved_config.json
diagnostic figures
truth maps
See:
A configured run is saved under:
outputs/<timestamp>_<run_name>/
Typical structure:
<run_directory>/
├── config/
│ ├── requested_config.mat
│ ├── resolved_config.json
│ └── resolved_config.mat
├── data/
│ ├── result.mat
│ ├── summary.mat
│ ├── validation_report.mat
│ └── validation_summary.txt
├── figures/
└── manifest.txt
Some 3D cases can also save:
data/req_validation_sample.mat
The full time series is disabled by default to prevent accidental multi-gigabyte outputs.
Enable it only when required:
cfg.output.save_time_series = true;New outputs belong under outputs/, which is excluded by .gitignore.
For heterogeneous sliding-window analysis, windows should be classified using the material ID truth map:
background-pure
inclusion-pure
mixed
Mixed windows do not have one unique local ground-truth SWS.
A displayed map can contain visible background and inclusion while still providing no background-pure placements for a selected analysis window.
Do not claim background accuracy or contrast recovery unless the region composition supports those claims.
See:
From MATLAB:
addpath('/absolute/path/to/k-wave_simulations/tests');
results = run_all_tests();Unit tests are designed to run quickly.
Integration tests execute compact k-Wave simulations and take longer.
When using this repository in research, cite both this software and the k-Wave toolbox.
Repository citation metadata are provided in:
This project is distributed under the Apache License 2.0.
Bug reports, validation cases, documentation improvements, and numerical tests are welcome.
See:
This repository builds upon the open-source k-Wave MATLAB Toolbox for time-domain acoustic and elastic-wave simulations.
The k-Wave toolbox is developed and maintained by Bradley E. Treeby and Ben T. Cox.
Please cite the original k-Wave publications when using this repository in research.
Treeby BE, Cox BT.
K-Wave: MATLAB toolbox for the simulation and reconstruction of photoacoustic wave fields.
Journal of Biomedical Optics, 15(2), 021314, 2010.
Treeby BE, Jaros J, Rendell AP, Cox BT.
Modeling nonlinear ultrasound propagation in heterogeneous media with power law absorption using a k-space pseudospectral method.
Journal of the Acoustical Society of America, 131(6), 4324-4336, 2012.
Official website:
https://www.k-wave.org