SPINS MATLAB tools

From Fluids Wiki
Revision as of 13:13, 14 October 2021 by A2grace (talk | contribs) (Added short summaries for every script)
Jump to navigation Jump to search

Many versatile MATLAB functions have been written to easily read and analyze SPINS outputs. They are accessible for use on Belize and Boogaloo, and can also be pulled from github at https://github.com/ddeepwel/SPINSmatlab.git.

The main functionality is:

  • parse spins.conf file into a matlab structure
  • automatic calculation of secondary grid parameters (spacing, expansion type, ...)
  • easy reading of grid
  • easy cross-sectional plotting
  • plotting of spins diagnostics
  • functions for calculating characteristics (amplitude, wavelength) of waves
  • SPINS resize

See David Deepwell (ddeepwel@uwaterloo.ca) or the github page for more information on usage, making bug reports, or suggesting other options or functions to add.

SPINSmatlab has a host of useful functions. Some are very general, while some are specialized. Below is a list of every function included in SPINSmatlab (as of October 2021), as well as a short description of what the function does. In parentheses is the directory in which the described script is located.

Following the description of the scripts, a list of "MUST KNOW" scripts is included. These scripts are the most widely used on the day-to-day and fluency in them is imperative to a smooth workflow. Many of these codes rely on the spins.conf, so ensure that the working directory contains it. For this software to work wherever the user needs it, include a file called startup.m in your ~/Documents/MATLAB folder (on Unix based systems). A sample startup.m file is included below.

sm_loc = genpath('<path to wherever you installed SPINSmatlab>');
addpath(sm_loc);
% remove all hidden subdirectories
all_subs =  strsplit(sm_loc,':');
for ii = 1:length(all_subs)
	    if ~isempty(strfind(all_subs{ii},'.')) 
	        rmpath(all_subs{ii});
	    end
end
% clean work space
clear all


Reading in parameters from the spins.conf

Reading in parameters from the spins.conf takes place in two steps. The first is to generate a MATLAB structure containing all the parameters from the spins.conf. This is done by writing params = spins_gridparams(). The output params is a structure containing all of the parameters from the spins.conf.

The second step is to access the variables within the structure params and recast then as workspace variables. This is done by writing par2var(params). Now, all parameters from the spins.conf can be accessed as MATLAB variables. To learn more about the size and datatype of each parameter, type whos in the MATLAB command window.


spins_reader()

spins_reader() is the function one uses to read in SPINS output into a MATLAB array. The basic functionality comes rom specifying the field name as a character vector, as well as the output index. As an example, if one would like to import the file rho.14 (i.e. the density field at the 14th output), they could write my_rho = spins_reader('rho',14).

For larger datasets, it is often impractical to load the entire dataset into MATLAB. To this end, the user can specify certain subsets of the data they wish to import. This is done by specifying index ranges in the dimension (xrange), dimension (yrange), and/or dimension (zrange). Each of the range arguments take an index or set of indices and return the field values at those indices. To access this functionality, one could write my_rho = spins_reader('rho',14,xstart:xend,y_slice_ind,[]). For the dimension, a custom range of indices beginning at xstart and ending at xend was used. For the dimension, the field was sliced at a single location indicated by y_slice_ind. Finally, the entire dimension was imported by using [].

If data is two-dimensional, accessing custom subsets of the data is done by ignoring the fifth argument. When only four arguments are supplied, spins_reader() assumes that the data only has an and dimension and no dimension.


plot_diagnos()

plot_diagnos() is the function used to parse and plot data from diagnostics.txt (a text file containing certain information about a simulation saved at every iteration). Entering info = plot_diagnos() saves the information from the diagnostics.txt in a MATLAB structure called info, and plots several figures with information pertaining to the simulation. To suppress the plots, enter diagnos = plot_diagnos(false).

The MATLAB structure info contains several structures within it, each holding related information. They are diagnos, Scales, EnergyBudget, EnergyRates, and Mixing.

Scales holds information on the Kolmogorov and Batchelor scales of the simulation.

Mixing contains information pertaining to mixing (efficiency, cumulative efficiency, and coefficients).

EnergyBudget contains information about the energy reservoirs in the flow. Information on total, kinetic, available, and available potential energy are found here. (cite winters) Additionally, information on the total energy exchange between different reservoirs is contained here.

EnergyRate contains information about the rate of energy exchange between the reservoirs in the flow.

diagnos is a catch-all, and should be used as a first order assessment of the dynamics. It holds timing information, domain averaged quantities such as kinetic energy, enstrophy, and dissipation, and maximum quanities. It also hold diagnostics such as total mass and maximum density, which can be used to quickly assess whether or not there are significant numerical instabilities in a simulation.


cmocean()

cmocean() is a package of perceptually uniform colourmaps(Add Thyng reference). These colourmaps should be used whenever possible, as they avoid artificial gradients created by using some other colourmaps.

To access the colourmaps within the package, when writing the colormap command, write colormap(cmocean(my_colourmap)) where my_colourmap(character vector) is any of the available colourmaps found by typing help cmocean.


print_figure()

print_figure() is used to print the contents of a figure to a file whose filetype is specified by the user. To use the basic functionality, write print_figure(filename,'opt1',val1,'opt2',val2,...). The filename is a character vector. The different options, opt1, opt2, ... and values val1, val2, ... are given in the following table.

print_figure() options
Option Value Description
fig_hand integer/figure handle Figure window
format 'pdf', 'pdf', 'eps' (not recommended) ... File format to save figure
units 'inches', 'cm' Units of figure size
size [width height] Vector of dimensions (in units specified by units)
res integer Resolution in dpi
renderer 'painters', 'opengl' This option can often be ignored


resize_all()

resize_all() is used to spectrally interpolate existing SPINS data onto a finer (or more coarse) grid where the size of the grid is specified by the user. The intention of this function is to refine data from a chosen output so as to manually restart a simulation to achieve a higher resolution. These scripts can be used with Fourier and Chebyshev( only) grids.

To use resize_all(), go to the directory where the data is located, and run resize_all(output, [Nx_new Ny_new Nz_new]). This script will create a new directory called resized/ that holds the new refined data to be used as the initial condition for the refined simulation. Included in this directory is the executable, and the spins.conf updated to reflect the new grid and restarting information.

To use resize_all() in two dimensions, in the directory with the unrefined data, simply enter resize_all(output, [Nx_new Nz_new]) (the code implicitly assume two dimensional data is in the plane).


extend_all()

extend_all() provides a means to starting a three-dimensional simulation based on a two dimensional ( plane) initial condition. The intended use is for running a two dimensional simulation until three dimensional effects are expected to occur, then extending the last output from the two dimenisonal simulation into three dimensions and re-running from there. extend_all() works in a similar fashion to resize_all(). Running it creates a new directory, where the now three dimensional extended data is placed, along with an updated spins.conf and new executable file.

To use extend_all(), go to the directory where the data is located, and run extend_all(output, Ly, Ny). This script will create a new directory called extended/ that holds the new refined data to be used as the initial condition for the refined simulation. Ly is the length in the spanwise dimension, and Ny is the number of grid points in that dimension.


More information can be found on the following functions by typing help followed by the name of the function in MATLAB command window.

characterize_wave() Tracks the core of a propagating wave.

clean_diagnostics Removes errors due to restarts in diagnostics.txt.

find_contour() Finds the positions of a contour specified by the user.

find_halfmax() Finds the halfmax of a wave height.

find_position() Finds the position of a value specified by the user.

find_wave_max() Finds the local maximum in a field.

FiniteDiff() Creates an arbitrary order finite difference matrix.

choose_caxis() Chooses an appropriate colour axis based on data.

figure_defaults()

print_all() Prints all figures on screen to separate files.

rgb() Returns the colour vecotr based on standardized colour naming conventions from CSS colour module (source).

rotate_axes() Rotates coordinate axes based on user input.

shift_axes() Translates coordinate axes based on user input.

subplot_labels() Provides text subplot labels.

make_movie()/make_movie_bare() Strings together user generated figures to make a mp4 video. Notes that this function requires installation of ffmpeg.

plot_stress() Plots surface and bottom stresses from files called stresses_top.txt and stresses_bottom.txt.

spins_hovmoller() Creates space-time data of a field at a user-specified location.

spins_plot2D() General plotting software for use with spins_params(), spins_gridparams(), and spins_grid().

spins_grid() Reads in grid data from the spins.conf.

spins_gridparams() Reads in both grid and parameter data from the spins.conf.

spins_readdata() Reads in data at a user specifed location in space and time.

spins_writer() Writes a MATLAB array to a SPINS readable format.

xz_reader()/xy_reader() Reads in and ( and ) grids.

clear_except() Clears variables from the workspace except those specified by the user.

completion() Checks the completion percentage of a script.

check_make_dir() Checks if a path exists.

contour_data() Obtain structured contour data.

fftfreq() Obtains sampling frequencies for the fft.

filters() Provides examples of different types of numerical filters.

find_fields() Finds valid SPINS fields given an index.

first_output() Finds the first SPINS output.

get_fixed_z() Finds a 2D slice at a constant depth.

get_lab_frame() Wrapper for rotate_refframe().

get_output_times() Gets output times from a run.

get_planar_grid() Returns cross sections of a three dimensional grid.

get_plot_points() Gives grid info to plot sections of a field.

get_rectilinear_grid() Interpolates a mapped grid onto a rectilinear.

get_vector_grid() Gets one dimensional vectors of grids.

interp_onto_rect_grid() Interpolates a mapped field onto a rectilinear grid.

last_output() Gets last output in a SPINS run.

max_grid_spacing() Finds max grid spacing in each dimension.

nearest_index() Finds the nearest index to a user supplied value.

rotate_refframe()/rotation_transform() Rotates grid to lab frame (rotate_refframe()) or to an arbitrary angle (rotation_transform()).

spins_plotoptions Helper script for spins_plot2D.

split_gdpar Splits the structure generated by spins_gridparams() into separate strucutres. One contains the grid and the other the parameters from the spins.conf.

wave_region Finds a region surrounding a wave by looking to a file called wave_characteristics.mat.