tools Functions
The tools functions provide utilities for signal processing,
visualization, downloading datasets, and other helper tasks.
Signal Processing
- band_pass(p, Fs, F)
BAND_PASS Apply a Kaiser-window FIR band-pass filter
[pf, h, w] = tools.band_pass(p, Fs, F)
- Parameters:
p input signal (column-oriented) Fs sampling frequency [Hz] F frequency band edges [f1 f2 f3 f4] [Hz]
See also TOOLS.LOW_PASS, TOOLS.HIGH_PASS
- high_pass(p, Fs, F)
HIGH_PASS Apply a Kaiser-window FIR high-pass filter
[pf, h, w] = tools.high_pass(p, Fs, F)
- Parameters:
p input signal (column-oriented) Fs sampling frequency [Hz] F transition band edges [f_stop f_pass] [Hz]
See also TOOLS.LOW_PASS, TOOLS.BAND_PASS
- low_pass(p, Fs, F)
LOW_PASS Apply a Kaiser-window FIR low-pass filter
[pf, h, w] = tools.low_pass(p, Fs, F)
- Parameters:
p input signal (column-oriented) Fs sampling frequency [Hz] F transition band edges [f_pass f_stop] [Hz]
See also TOOLS.BAND_PASS, TOOLS.HIGH_PASS
- rf2iq(rf, fs, fdemod, fs_new, f_cutoff, varargin)
RF2IQ Convert RF data to IQ and downsample. Syntax:
>> iq = rf2iq(rf, fs, fdemod, fs_new, f_cutoff)
- Inputs:
rf – N-D array of real-valued rf traces in column orientation fs – sampling frequency [Hz] fdemod – demodulation frequency [Hz] fs_new – new sampling freq after resampling f_cutoff – cutoff frequency above which the signal will be filtered before
resampling
- Outputs
iq – N-D array of downsampled demodulated iq signal f_cutoff – Cutoff filtering frequency for iq signal (= fs for non-filtered)
- estimate_frequency(time, data)
ESTIMATE_FREQUENCY Estimate center frequency and bandwidth of a signal
[fc, bw] = tools.estimate_frequency(time, data)
See also TOOLS.POWER_SPECTRUM
Beamforming
- matlab_beamformer(ch_data, ch_data_time, tx_apodization, rx_apodization, transmit_delay, receive_delay, w0, dim)
- matlab_gpu_beamformer(ch_data, ch_data_time, tx_apodization, rx_apodization, transmit_delay, receive_delay, w0, dim, gpu_id)
- calculate_unified_delay_model(transmit_delay_temp, mask, scan, source)
CALCULATE_UNIFIED_DELAY_MODEL Compute unified transmit delay model
Implements the unified pixel-based transmit delay model from Nguyen & Prager (2016) to avoid discontinuities in focused imaging.
delay = tools.calculate_unified_delay_model(delay, mask, scan, source)
See also MIDPROCESS.DAS, SPHERICAL_TRANSMIT_DELAY_MODEL
- References:
Nguyen & Prager, “High-Resolution Ultrasound Imaging With Unified Pixel-Based Beamforming”, IEEE TMI, vol. 35(1), pp. 98-108, 2016
Scan Conversion
- scan_convert(inputImage, thetas, ranges, sizeX, sizeZ, interpolationMethod)
Set parameters to default values if they are not provdied
- scan_convert_na(inputImage, thetas, ranges, origins, sizeX, sizeZ, interpolationMethod)
Set parameters to default values if they are not provdied
- scan_convert_all_frames(b_data_in, dynamic_range, gain)
Example code on how to easily convert data from uff.beamformed_data.data to gray scale image
Measurement
- measure_contrast_ratio(sta_image, image, xc_nonecho, zc_nonecho, r_nonecho, r_speckle_inner, r_speckle_outer, f_filename, plot_flag)
MEASURE_CONTRAST_RATIO Measure contrast ratio between cyst and speckle regions
- [CR, C] = tools.measure_contrast_ratio(sta_image, image, xc_nonecho, …
zc_nonecho, r_nonecho, r_speckle_inner, r_speckle_outer, filename, plot_flag)
See also TOOLS.MEASURE_CONTRAST_CIRCLES
- measure_contrast_circles(b_data, xc_nonecho, zc_nonecho, xc_echo, zc_echo, r, plot_flag, title_text, file_tag)
- dynamic_range_test(channel_data, b_data, title_txt)
The Dynamic Range Test The dynamic range test (DRT) was introduced in Rindal, O. M. H., Austeng, A., Fatemi, A., & Rodriguez-Molares, A. (2019). The effect of dynamic range alterations in the estimation of contrast. Submitted to IEEE Transactions on Ultrasonics, Ferroelectrics, and Frequency Control. We encourage you to use it, and provide here the data sets and code to run it. You have to reference the publication above when using the test. This script runs the DRT on the DAS (delay-and-sum), CF (coherence factor) and MV (minimum variance) beamformer.
Defining the DRT: To investigate wether a beamforming method is alternating the dynamic range, we have introduced a dynamic range test. This test uses the gradients in the simulated or the experimental dataset. The dynamic range test (DRT) is defined as
DRT=∆/∆_0
where ∆ denotes the gradient of a given beamforming method, estimated via linear regression, and ∆_0 denotes the theoretical gradient, as fixed in the simulated and experimental data. DRT measures how many dB the output dynamic range deviate sfrom the theoretical, for each dB of the input dynamic range.
For the simulated dataset we have both an axial and a lateral gradient and the DRT can be estimated for both. For simplicity, the reported DRT value will be the average of the DRT in theaxial and lateral direction. For the experimental dataset DRT is estimated in the lateral gradient.
- @input channel_datachannel data object
- b_databeamformed data object with the image created by
the beamformer under test
title_txt : title to be used in the plot
- power_spectrum(data, fs, normalised, N)
POWER_SPECTRUM Compute the averaged power spectrum of channel data
[fx, pw] = tools.power_spectrum(data, fs, normalised, N)
See also TOOLS.ESTIMATE_FREQUENCY
- power_spectrum2(data, fs)
function [fx, F] = power_spectrum(data,fs)
Statistics
- weigthed_mean(D, W, dim)
weigthed_mean Multidimensional weigthed mean
Usage: out_std = weigthed_mean(D,W,dim)
Computes the weigthed mean of a multidimensional matrix D for a multidimensional weigth W along dimension dim
- weigthed_var(D, W, dim)
weigthed_var Multidimensional weigthed variance
Usage: out_var = weigthed_var(D,W,dim)
Computes the weigthed variance of a multidimensional matrix D for a multidimensional weigth W along dimension dim
- weigthed_std(D, W, dim)
weigthed_std Multidimensional weigthed std
Usage: out_std = weigthed_std(D,W,dim)
Computes the weigthed standard deviation of a multidimensional matrix D for a multidimensional weigth W along dimension dim
- uniform_fov_weighting(mid)
UNIFORM_FOV_WEIGHTING Calculate weighting to give uniform field of view Compensate for the varying number of elements to go into the sum
Data Management
- download(file, url, local_path)
DOWNLOAD download a dataset from specified URL. download(FILE, URL) checks if the specified file is missing and downlods it from URL. The input argument FILE is a string that contains the absolute path to the file.
This function supports downloading large files from Google drive. In order to download a dataset from Google drive, URL must be provided as URL = https://drive.google.com/uc?export=download&id=ID’ where ID is the file id
- Example:
url = ‘http://ustb.no/datasets/ARFI_dataset.uff’; file = fullfile(ustb_path(), ‘data’, ‘ARFI_dataset.uff’); tools.download(file, url)
- hash(Data, Opt)
DATAHASH - Checksum for Matlab array of any type This function creates a hash value for an input of any type. The type and dimensions of the input are considered as default, such that UINT8([0,0]) and UINT16(0) have different hash values. Nested STRUCTs and CELLs are parsed recursively.
Hash = DataHash(Data, Opt) INPUT:
- Data: Array of these built-in types:
(U)INT8/16/32/64, SINGLE, DOUBLE, (real/complex, full/sparse) CHAR, LOGICAL, CELL (nested), STRUCT (scalar or array, nested), function_handle.
- Opt: Struct to specify the hashing algorithm and the output format.
Opt and all its fields are optional. Opt.Method: String, known methods for Java 1.6 (Matlab 2011b):
‘SHA-1’, ‘SHA-256’, ‘SHA-384’, ‘SHA-512’, ‘MD2’, ‘MD5’.
Call DataHash without inputs to get a list of available methods. Default: ‘MD5’.
- Opt.Format: String specifying the output format:
‘hex’, ‘HEX’: Lower/uppercase hexadecimal string. ‘double’, ‘uint8’: Numerical vector. ‘base64’: Base64 encoded string, only printable ASCII
characters, shorter than ‘hex’, no padding.
Default: ‘hex’.
- Opt.Input: Type of the input as string, not case-sensitive:
- ‘array’: The contents, type and size of the input [Data] are
considered for the creation of the hash. Nested CELLs and STRUCT arrays are parsed recursively. Empty arrays of different type reply different hashs.
- ‘file’: [Data] is treated as file name and the hash is calculated
for the files contents.
- ‘bin’: [Data] is a numerical, LOGICAL or CHAR array. Only the
binary contents of the array is considered, such that e.g. empty arrays of different type reply the same hash.
- ‘ascii’: Same as ‘bin’, but only the 8-bit ASCII part of the 16-bit
Matlab CHARs is considered.
Default: ‘array’.
- OUTPUT:
- Hash: String, DOUBLE or UINT8 vector. The length depends on the hashing
method.
EXAMPLES: % Default: MD5, hex:
DataHash([]) % 5b302b7b2099a97ba2a276640a192485
- % MD5, Base64:
Opt = struct(‘Format’, ‘base64’, ‘Method’, ‘MD5’); DataHash(int32(1:10), Opt) % +tJN9yeF89h3jOFNN55XLg
- % SHA-1, Base64:
S.a = uint8([]); S.b = {{1:10}, struct(‘q’, uint64(415))}; Opt.Method = ‘SHA-1’; Opt.Format = ‘HEX’; DataHash(S, Opt) % 18672BE876463B25214CA9241B3C79CC926F3093
- % SHA-1 of binary values:
Opt = struct(‘Method’, ‘SHA-1’, ‘Input’, ‘bin’); DataHash(1:8, Opt) % 826cf9d3a5d74bbe415e97d4cecf03f445f69225
- % SHA-256, consider ASCII part only (Matlab’s CHAR has 16 bits!):
Opt.Method = ‘SHA-256’; Opt.Input = ‘ascii’; DataHash(‘abc’, Opt)
% ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
% Or equivalently: Opt.Input = ‘bin’; DataHash(uint8(‘abc’), Opt)
- NOTES:
Function handles and user-defined objects cannot be converted uniquely: - The subfunction ConvertFuncHandle uses the built-in function FUNCTIONS,
but the replied struct can depend on the Matlab version.
It is tried to convert objects to UINT8 streams in the subfunction ConvertObject. A conversion by STRUCT() might be more appropriate.
Adjust these subfunctions on demand.
MATLAB CHARs have 16 bits! Use Opt.Input=’ascii’ for comparisons with e.g. online hash generators.
- Matt Raum suggested this for e.g. user-defined objects:
DataHash(getByteStreamFromArray(Data)
This works very well, but unfortunately getByteStreamFromArray is undocumented, such that it might vanish in the future or reply different output.
For arrays the calculated hash value might be changed in new versions. Calling this function without inputs replies the version of the hash.
The C-Mex function GetMD5 is 2 to 100 times faster, but obtains MD5 only: http://www.mathworks.com/matlabcentral/fileexchange/25921
Tested: Matlab 7.7, 7.8, 7.13, 8.6, WinXP/32, Win7/64 Author: Jan Simon, Heidelberg, (C) 2011-2016 matlab.2010(a)n(MINUS)simon.de
See also: TYPECAST, CAST.
- Michael Kleder, “Compute Hash”, no structs and cells:
- Tim, “Serialize/Deserialize”, converts structs and cells to a byte stream:
Visualization
- plot_circle(x, y, r, style)
x and y are the coordinates of the center of the circle r is the radius of the circle 0.01 is the angle step, bigger values will draw the circle faster but you might notice imperfections (not very smooth)
- histogram_match(b_data_reference, b_data_in)
HISTOGRAM MATCH This function histogram match the images in the input variables b_data_reference and b_data_in. The b_data_in is forced to match the b_data_reference. The output is in dB scale as an image in img_out and a uff.beamformed_data object in b_data_out.
The histogram mathing is done on the images in dB scale.
- viridis(m)
VIRIDIS Viridis perceptually-uniform colormap (from matplotlib)
cm = tools.viridis(m)
See also TOOLS.INFERNO, TOOLS.MAGMA, TOOLS.PLASMA
- magma(m)
MAGMA Magma perceptually-uniform colormap (from matplotlib)
cm = tools.magma(m)
See also TOOLS.INFERNO, TOOLS.VIRIDIS, TOOLS.PLASMA
- plasma(m)
PLASMA Plasma perceptually-uniform colormap (from matplotlib)
cm = tools.plasma(m)
See also TOOLS.INFERNO, TOOLS.VIRIDIS, TOOLS.MAGMA
- inferno(m)
INFERNO Inferno perceptually-uniform colormap (from matplotlib)
cm = tools.inferno(m)
See also TOOLS.VIRIDIS, TOOLS.MAGMA, TOOLS.PLASMA
Utilities
- rotate_points(x, y, z, theta, phi)
ROTATE_POINTS Rotate 3-D points by azimuth and elevation angles
[x, y, z] = tools.rotate_points(x, y, z, theta, phi)
- Parameters:
x, y, z point coordinates (matrices) theta azimuth rotation angle [rad] phi elevation rotation angle [rad]
- check_memory(bytes)
CHECK_MEMORY Check that enough RAM is available for an allocation
tools.check_memory(bytes)
See also TOOLS.GETAVAILABLEMEMORY
- getAvailableMemory()
GETAVAILABLEMEMORY Return available physical memory in bytes
val = tools.getAvailableMemory()
See also TOOLS.CHECK_MEMORY
- text_progress_bar(c, previous_msg, barsize)
- workbar(fractiondone, message, progtitle)
- WORKBAR Graphically monitors progress of calculations
WORKBAR(X) creates and displays the workbar with the fractional length “X”. It is an alternative to the built-in matlab function WAITBAR, Featuring:
Doesn’t slow down calculations
Stylish progress look
Requires only a single line of code
Displays time remaining
Display time complete
Capable of title and description
Only one workbar can exist (avoids clutter)
WORKBAR(X, MESSAGE) sets the fractional length of the workbar as well as setting a message in the workbar window.
WORKBAR(X, MESSAGE, TITLE) sets the fractional length of the workbar, message and title of the workbar window.
WORKBAR is typically used inside a FOR loop that performs a lengthy computation. A sample usage is shown below:
- for i = 1:10000
% Calculation workbar(i/10000,’Performing Calclations…’,’Progress’)
end
Another example:
- for i = 1:10000
% Calculation if i < 2000,
workbar(i/10000,’Performing Calclations (Step 1)…’,’Step 1’)
- elseif i < 4000
workbar(i/10000,’Performing Calclations (Step 2)…’,’Step 2’)
- elseif i < 6000
workbar(i/10000,’Performing Calclations (Step 3)…’,’Step 3’)
- elseif i < 8000
workbar(i/10000,’Performing Calclations (Step 4)…’,’Step 4’)
- else
workbar(i/10000,’Performing Calclations (Step 5)…’,’Step 5’)
end
end
See also: WAITBAR, TIMEBAR, PROGRESSBAR
- dialog_timeout(delay, varargin)
questdlg function with timeout property
Based on timeoutDlg by MathWorks Support Team https://uk.mathworks.com/matlabcentral/answers/96229-how-can-i-have-a-dialog-box-or-user-prompt-with-a-time-out-period
button = questdlgtimeout(delay,’qstring’) button = questdlgtimeout(delay,qstring,title) button = questdlgtimeout(delay,qstring,title,default) button = questdlgtimeout(delay,qstring,title,str1,str2,default) button = questdlgtimeout(delay,qstring,title,str1,str2,str3,default) button = questdlgtimeout(delay,qstring,title, …, options)
INPUT ARGUMENTS delay Duration in second during withich the dialog is maintained
- var1,var2,…
Accepts input arguments for builtin questdlg. See documentation of questdlg
OUTPUT ARGUMENTS button The dialog has three default buttons, Yes, No, and Cancel.
If the user presses one of these three buttons, button is set to the name of the button pressed. If the user presses the close button on the dialog without making a choice, button returns as an empty character vector (‘’). If the user presses the Return key, button returns with a value of ‘Yes’.
If you provide default or options, button will be the default value.
See also questdlg, timer, scr20170308_154424_questdlgtimeout
Written by Kouichi C. Nakamura Ph.D. MRC Brain Network Dynamics Unit University of Oxford 08-Mar-2017 16:06:58
- sector_MLA(sector_scan_input, MLA)
- makehtmldoc(filename, varargin)
MAKEHTMLDOC Create HTML help files from a set of M-Files MAKEHTMLDOC(FILENAME) creates an html help file for each M-File matching FILENAME. This help file contains the header of the M-File (the first block of contiguous comment lines, see HELP for details), with links between each M-File matching FILENAME referencing each other.
If no input argument specified, works with all the M-files of the current directory (ie, MAKEHTMLDOC(’*.m’)).
MAKEHTMLDOC(FILENAME, ‘Property1’, ‘Property2’…) where ‘Property.’ may be:
- ‘code’ adds a link to the source code (except for the
file ‘Contents.m’);
‘upper’ makes a link only for words in upper case. ‘quiet’ does not display informations during the
processing.
- ‘color’, string any HTML color code for the upper and lower
panels. Default = ‘#e7ebf7’.
‘title’, string title of the browser window. Default = ‘f’. ‘firstline’, string text at the top of the page. Default =
‘Contents’.
‘lastline’, string text at the bottom of the page. Default = ‘’.
Note: In the string of the last three properties, ‘f’ will be replaced by the name of the current M-file. Web links may be used, e.g. string = ‘f (<a href=”MyToolbox.html”>MyToolbox</a>)’
MAKEHTMLDOC works essentially as Matlab’s DOC function, except that the links are only established between the set of files matching FILENAME. So the resulting set of HTML pages only have link between themselves, and will not have broken links when consulted from an external web site.
- Examples:
makehtmldoc(’*.m’,’code’) produces a set of *.html help files for all the *.m files of the current directory, with a link to the corresponding source code.
makehtmldoc(’*.m’,’title’,’f (MyToolbox)’,’lastline’,’(c) 2006’);
- makehtmldoc(’*.m’, …
‘color’, ‘#ffff00’, … ‘title’, ‘Help for f’, … ‘firstline’, ‘<a href=”Contents.html”>Back</a>’, … ‘lastline’, ‘<a href=”www.mytoolbox.com”>MyToolBox</a>’, … ‘upper’, ‘code’);
F. Moisy Revision: 1.22, Date: 2006/10/30.
See also HELP, DOC, WEB.