### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_3D_FFT_planar_sensor/pr_3D_FFT_planar_sensor.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the simulation and reconstruction examples. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_array_as_source/at_array_as_source.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the subsequent examples. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_2D_FFT_line_sensor/pr_2D_FFT_line_sensor.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the examples. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/sd_focussed_detector_3D/sd_focussed_detector_3D.ipynb Installs the k-wave-python library from a GitHub repository using pip. ```bash %pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_focused_bowl_AS/at_focused_bowl_AS.ipynb Installs the k-wave-python library from a GitHub repository using pip. This is the initial step to use the library's functionalities. ```python !pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/us_bmode_phased_array/us_bmode_phased_array.ipynb Installs the k-wave-python library from a GitHub repository using pip. This is the initial setup step for using the library. ```Python %%capture !pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_3D_TR_planar_sensor/pr_3D_TR_planar_sensor.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the subsequent code examples. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_focused_annular_array_3D/at_focused_annular_array_3D.ipynb Installs the k-wave-python library directly from its GitHub repository using pip. ```python !pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_2D_TR_line_sensor/pr_2D_TR_line_sensor.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the subsequent examples. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/na_controlling_the_pml/na_controlling_the_pml.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the example. ```shell %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-Wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/docs/README.md Installs the latest version of the k-Wave-python package from PyPI using pip. This is the primary method for users to get started with the library. ```Bash pip install k-wave-python ``` -------------------------------- ### Run Examples (GPU-enabled) Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst These commands demonstrate how to run the k-Wave-Python examples. By default, they are GPU-enabled. 'make run-examples' is a convenience command, or you can directly run the python script. ```bash make run-examples # or MPLBACKEND=Agg python run_examples.py ``` -------------------------------- ### Run Examples (Force CPU Execution) Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst This command runs the k-Wave-Python examples while forcing CPU execution by setting the 'KWAVE_FORCE_CPU' environment variable. ```bash MPLBACKEND=Agg KWAVE_FORCE_CPU=1 python run_examples.py ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_circular_piston_AS/at_circular_piston_AS.ipynb Installs the k-wave-python library from its GitHub repository using pip. ```bash !pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/sd_focussed_detector_2D/sd_focussed_detector_2D.ipynb Installs the k-wave-python library from a GitHub repository using pip. ```python %pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_linear_array_transducer/at_linear_array_transducer.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the simulations. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-Wave-Python Dependencies Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst This bash command installs the development and testing dependencies for k-Wave-Python using 'uv pip'. The '-e' flag installs the package in editable mode. ```bash uv pip install -e '.[dev,test]' ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_focused_bowl_3D/at_focused_bowl_3D.ipynb Installs the k-wave-python library from a GitHub repository using pip. ```shell %pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/us_beam_patterns/us_beam_patterns.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the simulations. ```python %%capture # !pip install k-wave-python ``` -------------------------------- ### Setup k-wave-python Environment Source: https://github.com/waltsims/k-wave-python/blob/master/examples/sd_focussed_detector_2D/sd_focussed_detector_2D.ipynb Imports necessary libraries and sets up the environment for k-wave-python simulations, including plotting and data handling utilities. ```python %matplotlib inline import os from copy import deepcopy from tempfile import gettempdir import matplotlib.pyplot as plt import numpy as np from kwave.data import Vector from kwave.kgrid import kWaveGrid from kwave.kmedium import kWaveMedium from kwave.ksource import kSource from kwave.kspaceFirstOrder2D import kspaceFirstOrder2DC from kwave.ktransducer import kSensor from kwave.options.simulation_execution_options import SimulationExecutionOptions from kwave.options.simulation_options import SimulationOptions from kwave.utils.data import scale_SI from kwave.utils.mapgen import make_circle, make_disc ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/ivp_photoacoustic_waveforms/ivp_photoacoustic_waveforms.ipynb Installs the k-wave-python library using pip. This is a prerequisite for running the simulations. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_array_as_sensor/at_array_as_sensor.ipynb Installs the k-wave-python library using pip. This is a prerequisite for using the library's functionalities. ```Python %%capture !pip install k-wave-python ``` -------------------------------- ### Configure Pre-commit Hooks Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst This bash command installs the pre-commit git hooks, which are used to automatically format and lint code before commits. ```bash pre-commit install ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_circular_piston_3D/at_circular_piston_3D.ipynb Installs the k-wave-python library from a GitHub repository using pip. This is the initial step to set up the environment for using the library's functionalities. ```bash !pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/sd_directivity_modelling_2D/sd_directivity_modelling_2D.ipynb Installs the k-wave-python library from a GitHub repository using pip. ```Python %pip install git+https://github.com/waltsims/k-wave-python ``` -------------------------------- ### Build k-wave-python Package Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst Builds the k-wave-python package using the Hatch build command. This prepares the package for distribution. ```bash hatch build ``` -------------------------------- ### Install k-wave-python Source: https://github.com/waltsims/k-wave-python/blob/master/examples/us_defining_transducer/us_defining_transducer.ipynb Installs the k-wave-python library using pip. This is a prerequisite for using the library's functionalities. ```python %%capture !pip install k-wave-python ``` -------------------------------- ### 3D Simulation Setup Source: https://github.com/waltsims/k-wave-python/blob/master/examples/ivp_photoacoustic_waveforms/ivp_photoacoustic_waveforms.ipynb Configures the parameters for a 3D photoacoustic simulation. Similar to the 2D setup, but with a 3D grid and source definition (using make_ball). ```python medium3 = kWaveMedium(sound_speed=1500) # create the k-space grid kgrid3 = kWaveGrid([Nx, Nx, Nx], [dx, dx, dx]) # create the time array using an integer number of points per period kgrid3.setTime(int(np.round(t_end / dt)), dt) # create instance of a sensor sensor3 = kSensor() # set sensor mask: the mask says at which points data should be recorded sensor3.mask = np.zeros((Nx, Nx, Nx), dtype=bool) # define a single sensor point sensor3.mask[Nx // 2 + source_sensor_distance, Nx // 2, Nx // 2] = True # set the record type: record the pressure waveform sensor3.record = ['p'] # make a source object source3 = kSource() source3.p0 = make_ball(Vector([Nx, Nx, Nx]), Vector([Nx // 2, Nx // 2, Nx // 2]), source_radius) ``` -------------------------------- ### k-Wave Simulation Setup and Execution Source: https://github.com/waltsims/k-wave-python/blob/master/docs/index.rst This snippet demonstrates how to set up and execute a k-Wave simulation. It covers defining the computational grid, medium properties, sources, sensors, and running the simulation using the k-space pseudospectral method. Dependencies include the k-Wave library itself. ```Python from kWave import * # Define grid k = kWaveGrid([128, 128], dx=0.1) # Define medium m = kWaveMedium(k, sound_speed=1500, density=1000) # Define source s = kWaveSource(k, 'plane', amplitude=1, wave_type='gaussian', f_max=1e6) # Define sensor r = kWaveSensor(k, 'plane', position=[[0, 64]]) # Run simulation kwave_sim = kWaveSimulation(k, m, s, r) kwave_sim.run() # Access results pressure = kwave_sim.get_pressure() ``` -------------------------------- ### Publish k-wave-python to PyPI Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst Publishes the built k-wave-python package to the production PyPI index using the Hatch publish command. Requires authentication with a PyPI token. ```bash hatch publish -u __token__ ``` -------------------------------- ### Clone k-Wave-Python Repository Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst This snippet shows the bash commands to clone the k-Wave-Python repository from GitHub and navigate into the cloned directory. ```bash git clone https://github.com/waltsims/k-wave-python cd k-wave-python ``` -------------------------------- ### Get colormap Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_2D_FFT_line_sensor/pr_2D_FFT_line_sensor.ipynb Retrieves a colormap for visualization purposes. ```python cmap = get_color_map() ``` -------------------------------- ### Get colormap for visualization Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_2D_TR_line_sensor/pr_2D_TR_line_sensor.ipynb Retrieves a colormap to be used for visualizing the simulation results. ```python cmap = get_color_map() ``` -------------------------------- ### Get colormap Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_3D_TR_planar_sensor/pr_3D_TR_planar_sensor.ipynb Retrieves a colormap for visualization purposes. This colormap will be used when plotting the pressure distributions. ```python cmap = get_color_map() ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst These bash commands demonstrate how to create a virtual environment using 'uv' and then activate it. The activation command differs for Linux/macOS and Windows. ```bash uv venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Get Sensor Data Shape Source: https://github.com/waltsims/k-wave-python/blob/master/examples/sd_focussed_detector_2D/sd_focussed_detector_2D.ipynb Retrieves and prints the shape of the pressure data recorded by the sensor from the first simulation run. ```python sensor_data1['p'].shape ``` -------------------------------- ### Initialize and Run 3D Simulation Source: https://github.com/waltsims/k-wave-python/blob/master/examples/us_bmode_linear_transducer/us_bmode_linear_transducer.ipynb This snippet demonstrates the initialization of simulation parameters, including medium properties, input settings, and execution options for a 3D k-wave simulation. It handles both running the simulation on a GPU and downloading pre-existing data if the simulation is not run. ```Python scan_lines = np.zeros((number_scan_lines, kgrid.Nt)) medium_position = 0 for scan_line_index in range(0, number_scan_lines): # load the current section of the medium medium.sound_speed = \ sound_speed_map[:, medium_position:medium_position + grid_size_points.y, :] medium.density = density_map[:, medium_position:medium_position + grid_size_points.y, :] # set the input settings input_filename = f'example_input_{scan_line_index}.h5' # set the input settings simulation_options = SimulationOptions( pml_inside=False, pml_size=pml_size_points, data_cast=DATA_CAST, data_recast=True, save_to_disk=True, input_filename=input_filename, save_to_disk_exit=False ) # run the simulation if RUN_SIMULATION: sensor_data = kspaceFirstOrder3D( medium=medium, kgrid=kgrid, source=not_transducer, sensor=not_transducer, simulation_options=simulation_options, execution_options=SimulationExecutionOptions(is_gpu_simulation=True) ) scan_lines[scan_line_index, :] = not_transducer.scan_line(not_transducer.combine_sensor_data(sensor_data['p'].T)) # update medium position medium_position = medium_position + transducer.element_width if RUN_SIMULATION: simulation_data = scan_lines scipy.io.savemat('sensor_data.mat', {'sensor_data_all_lines': simulation_data}) else: logging.log(logging.INFO, "Downloading data from remote server...") sensor_data_path = 'sensor_data.mat' download_if_does_not_exist(SENSOR_DATA_GDRIVE_ID, sensor_data_path) simulation_data = scipy.io.loadmat(sensor_data_path)['sensor_data_all_lines'] scan_lines = simulation_data ``` -------------------------------- ### Setup k-Wave Grid Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_linear_array_transducer/at_linear_array_transducer.ipynb Calculates grid spacing and dimensions based on the speed of sound, points per wavelength (ppw), and desired simulation time. Initializes the kWaveGrid and sets the simulation time step. ```python # GRID dx = c0 / (ppw * source_f0) Nx = round(grid_size_x / dx) Ny = round(grid_size_y / dx) Nz = round(grid_size_z / dx) kgrid = kWaveGrid([Nx, Ny, Nz], [dx, dx, dx]) kgrid.makeTime(c0, cfl, t_end) ``` -------------------------------- ### Setup Computational Grid and Medium Source: https://github.com/waltsims/k-wave-python/blob/master/examples/na_controlling_the_pml/na_controlling_the_pml.ipynb Initializes the computational grid with specified size and spacing, and defines the acoustic properties of the medium, specifically the sound speed. ```python # create the computational grid and propagation medium grid_size = Vector([128, 128]) # [grid points] grid_spacing = Vector([0.1e-3, 0.1e-3]) # [m] kgrid = kWaveGrid(grid_size, grid_spacing) medium = kWaveMedium(sound_speed=1500) ``` -------------------------------- ### Setup computational grid Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_2D_TR_line_sensor/pr_2D_TR_line_sensor.ipynb Defines the computational grid parameters, including the size of the Perfectly Matched Layer (PML) and the number of grid points and spacing for the simulation domain. ```python # create the computational grid PML_size = 20 # size of the PML in grid points N = Vector([128, 256]) - 2 * PML_size # number of grid points d = Vector([0.1e-3, 0.1e-3]) # grid point spacing [m] kgrid = kWaveGrid(N, d) ``` -------------------------------- ### MATLAB kspaceFirstOrder2D Function Call Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst This MATLAB code snippet shows a typical call to the kspaceFirstOrder2D function within a k-Wave example script. It includes various input arguments for simulation parameters. ```matlab input_args = {'PMLInside', false, 'PMLSize', PML_size, 'PlotPML', false, 'Smooth', false}; sensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:}); ``` -------------------------------- ### Install k-Wave-python Dependencies on MacOS Source: https://github.com/waltsims/k-wave-python/blob/master/docs/README.md Provides instructions for installing necessary dependencies (fftw, hdf5, zlib, libomp) using the brew package manager on MacOS before installing the k-wave-python package. These are required for full functionality on this operating system. ```Bash brew install fftw hdf5 zlib libomp ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/waltsims/k-wave-python/blob/master/docs/development/development_environment.rst This bash command navigates to the k-wave-python directory and executes the 'make test' command, which generates reference files with MATLAB and runs the complete Python test suite. ```bash cd k-wave-python/ make test ``` -------------------------------- ### Configure Sensor and Simulation Options Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_focused_annular_array_3D/at_focused_annular_array_3D.ipynb Sets up the sensor mask and recording parameters, then defines simulation and execution options for a 3D k-Wave simulation, including enabling GPU acceleration and saving data to disk. ```Python # set sensor mask to record central plane, not including the source point sensor.mask = np.zeros((Nx, Ny, Nz), dtype=bool) sensor.mask[(source_x_offset + 1):, :, Nz // 2] = True # record the pressure sensor.record = ['p'] # record only the final few periods when the field is in steady state sensor.record_start_index = kgrid.Nt - (record_periods * ppp) + 1 simulation_options = SimulationOptions(pml_auto=True, data_recast=True, save_to_disk=True, save_to_disk_exit=False, pml_inside=False) execution_options = SimulationExecutionOptions(is_gpu_simulation=True, delete_data=False, verbose_level=0) sensor_data = kspaceFirstOrder3D(medium=deepcopy(medium), kgrid=deepcopy(kgrid), source=deepcopy(source), sensor=deepcopy(sensor), simulation_options=simulation_options, execution_options=execution_options) ``` -------------------------------- ### Configure and Execute 3D Simulation Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_linear_array_transducer/at_linear_array_transducer.ipynb Sets up simulation options, including PML (Perfectly Matched Layer) configuration, data casting, and whether to save to disk. It also specifies if GPU acceleration should be used. The kspaceFirstOrder3DC class is instantiated with all defined components to run the simulation. ```python # SIMULATION simulation_options = SimulationOptions( pml_auto=True, pml_inside=False, save_to_disk=True, data_cast='single', ) execution_options = SimulationExecutionOptions(is_gpu_simulation=True) sensor_data = kspaceFirstOrder3DC(kgrid=kgrid, medium=medium, source=source, sensor=sensor, simulation_options=simulation_options, execution_options=execution_options) p_max = np.reshape(sensor_data['p_max'], (Nx, Nz), order='F') ``` -------------------------------- ### Define Simulation Parameters Source: https://github.com/waltsims/k-wave-python/blob/master/examples/at_focused_bowl_AS/at_focused_bowl_AS.ipynb Sets up various parameters required for the k-wave simulation, including medium properties (sound speed, density), source characteristics (frequency, amplitude, phase, geometry), grid dimensions, and computational settings (points per wavelength, time step, CFL number). ```python verbose: bool = False # medium parameters c0: float = 1500.0 # sound speed [m/s] rho0: float = 1000.0 # density [kg/m^3] # source parameters source_f0 = 1.0e6 # source frequency [Hz] source_roc = 30e-3 # bowl radius of curvature [m] source_diameter = 30e-3 # bowl aperture diameter [m] source_amp = np.array([1.0e6]) # source pressure [Pa] source_phase = np.array([0.0]) # source phase [radians] # grid parameters axial_size: float = 50.0e-3 # total grid size in the axial dimension [m] lateral_size: float = 45.0e-3 # total grid size in the lateral dimension [m] # computational parameters ppw: int = 3 # number of points per wavelength t_end: float = 40e-6 # total compute time [s] (this must be long enough to reach steady state) record_periods: int = 1 # number of periods to record cfl: float = 0.05 # CFL number source_x_offset: int = 20 # grid points to offset the source bli_tolerance: float = 0.01 # tolerance for truncation of the off-grid source points upsampling_rate: int = 10 # density of integration points relative to grid ``` -------------------------------- ### Set simulation and execution options Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_2D_FFT_line_sensor/pr_2D_FFT_line_sensor.ipynb Configures simulation parameters such as PML placement and whether to use GPU acceleration. ```python # set the input arguments: force the PML to be outside the computational grid simulation_options = SimulationOptions( save_to_disk=True, pml_inside=False, pml_size=PML_size, smooth_p0=False, ) execution_options = SimulationExecutionOptions(is_gpu_simulation=True) ``` -------------------------------- ### Plot Reconstructed Initial Pressure with Positivity Condition (Python) Source: https://github.com/waltsims/k-wave-python/blob/master/examples/pr_2D_TR_line_sensor/pr_2D_TR_line_sensor.ipynb This example applies a positivity condition to the reconstructed initial pressure by setting any negative values to zero. It then plots the modified pressure data using matplotlib, similar to the previous example, ensuring that the displayed pressure values are non-negative. This is useful for physical realism in acoustic simulations. ```Python p0_recon[p0_recon < 0] = 0 fig, ax = plt.subplots(1, 1) im = ax.imshow(p0_recon, extent=[kgrid.y_vec.min() * 1e3, kgrid.y_vec.max() * 1e3, kgrid.x_vec.max() * 1e3, kgrid.x_vec.min() * 1e3], vmin=-disc_magnitude, vmax=disc_magnitude, cmap=cmap) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="3%", pad="2%") ax.set_ylabel('x-position [mm]') ax.set_xlabel('y-position [mm]') fig.colorbar(im, cax=cax) plt.show() ``` -------------------------------- ### Check Colab Environment and Install k-wave Source: https://github.com/waltsims/k-wave-python/blob/master/examples/us_bmode_linear_transducer/us_bmode_linear_transducer.ipynb This snippet checks if the code is running in a Google Colab environment and installs the 'k-wave-python' library if it's not already present. It also downloads utility files if needed. ```Python import importlib.util import os def is_running_in_colab()->bool: return 'COLAB_RELEASE_TAG' in os.environ def is_library_installed(library_name): spec = importlib.util.find_spec(library_name) return spec is not None ``` ```Python %%capture if not is_library_installed('kwave'): %pip install k-wave-python if is_running_in_colab(): !wget https://raw.githubusercontent.com/waltsims/k-wave-python/master/examples/us_bmode_linear_transducer/example_utils.py ```