Utilities#

Here we can find the documentation for the utility classes and functions implemented in the Combustion Toolbox (CT).

Display subpackage#

The display subpackage contains functions and classes designed to assist with visualizing and presenting data. These utilities are useful for generating plots to aid in the analysis and interpretation of results obtained from the CT modules.

Canvas#

The Canvas superclass manages figure creation and plotting layout configuration

Routines
class Canvas(config)#

Bases: sphinxcontrib.mat_types.handle

The Canvas() class is an abstract base class used to manage figure creation and plotting layout configuration in the display subpackage.

The Canvas() class standardizes figure and axis formatting, provides tiled layout management, and offers utilities for axis selection and cycling.

A Canvas() subclass can be initialized as follows:

config = combustiontoolbox.utils.display.PlotConfig();
fig = combustiontoolbox.utils.display.PlotFigure(config);

See also: PlotConfig(), PlotFigure(), PlotComposition()

Canvas(config)#

Constructor

add()#

Add a new axis to the figure This method is intended to be overridden in subclasses to add specific axes or plots.

ax = None#

Axis handle

config = None#

Plot configuration object

currentIndex = '1'#

Current index for sequential filling of axes

fig = None#

Figure handle

getAxis(varargin)#

Return axis to use for plotting

Parameters:

obj (PlotFigure) – Instance of the PlotFigure superclass

Optional Args:

index (vector): Index of the axis to use [row, col] FLAG_SEQUENTIAL (bool): If true, use sequential filling of axes

Returns:

ax (Axes) – Axis to use for plotting

Examples

  • ax = obj.getAxis();

  • ax = obj.getAxis(‘index’, [1, 2]);

  • ax = obj.getAxis(‘FLAG_SEQUENTIAL’, true);

  • ax = obj.getAxis(‘index’, [1, 2], ‘FLAG_SEQUENTIAL’, true); % Start sequence at (1, 2)

new()#

Create and configure a new figure

newArray(varargin)#

Create a figure with an nrows x ncols tiled layout and return an array of PlotFigure subclass instances

next()#

Cycle to the next index

numAxis = None#

Number of axes in the figure

onFigureClose()#

Reset the axes and figure when the figure is closed

setFormat(ax)#

Set the format of the axes based on the configuration

Parameters:
  • obj (PlotFigure) – Instance of the PlotFigure superclass

  • ax (Axes) – Axes to format

Returns:

ax (Axes) – Formatted axes

Example

ax = obj.setFormat(gca);

setLegend(legendLabels)#

Set legend on the axis

setTitle(titleText)#

Set figure title with LaTeX interpreter

size = None#

Size of the axis array

tiled = None#

Tiled layout for multiple axes

PlotFigure#

The PlotFigure class extends Canvas to provide a unified plotting interface for thermodynamic and transport properties (e.g., cp, h, Xi) against an arbitrary independent variable.

Routines
class PlotFigure(config)#

Bases: combustiontoolbox.utils.display.Canvas

The PlotFigure() class extends Canvas() to provide a unified plotting interface for thermodynamic and transport properties (e.g., cp, h, Xi) against an arbitrary independent variable.

A PlotFigure() object can be initialized as follows:

config = combustiontoolbox.utils.display.PlotConfig();
fig = combustiontoolbox.utils.display.PlotFigure(config);
fig.plot('equivalenceRatio', mixArray, 'T', mixArray);

This creates a formatted plot with consistent styling using PlotConfig().

See also: Canvas(), PlotComposition(), PlotConfig()

PlotFigure(config)#

Constructor

colorIndex = '1'#

Index for color cycling

nextColor()#

Cycle to the next color in the color palette

plot(x_field, x_var, y_field, y_var, varargin)#

Plot method for scalar or multiple y_fields

Parameters:
  • x_field (char) – Field name for x-axis

  • x_var (cell) – Cell array of structures/objects with x_field

  • y_fields (char or cell) – Field name(s) for y-axis

  • y_var (cell) – Cell array with same length as x_var

  • varargin – Optional key-value arguments

Supported options:

‘config’, ‘legend’, ‘legend_location’, ‘linestyle’, ‘linewidth’, ‘fontsize’, ‘title’, ‘xlabel’, ‘ylabel’, ‘label_type’, ‘xscale’, ‘yscale’, ‘xdir’, ‘ydir’, ‘color’, ‘basis’, ‘validation’, ‘nfrec’

plotArray(x_field, x_var, y_field, y_var, varargin)#

Plot method for multiple y_fields in an array format

Parameters:
  • x_field (char) – Field name for x-axis

  • x_var (cell) – Cell array of structures/objects with x_field

  • y_fields (char or cell) – Field name(s) for y-axis

  • y_var (cell) – Cell array with same length as x_var

  • varargin – Optional key-value arguments

PlotComposition#

The PlotComposition class extends Canvas to generate species composition plots (e.g., molar fractions Xi) against an independent variable.

Routines
class PlotComposition(config)#

Bases: combustiontoolbox.utils.display.Canvas

The PlotComposition() class extends Canvas() to generate species composition plots (e.g., molar fractions Xi) against an independent variable.

A PlotComposition() object can be initialized as follows:

config = combustiontoolbox.utils.display.PlotConfig();
fig = combustiontoolbox.utils.display.PlotComposition(config);
fig.plot(mixtureArray, 'equivalenceRatio', 'Xi');

This creates a formatted figure with species composition plotted over the selected parameter.

See also: Canvas(), PlotFigure(), PlotConfig()

FLAG_PLOT_VALIDATION = 'false'#

Flag to indicate to plot validation data

PlotComposition(config)#

Constructor

static cleanDisplaySpecies(molar_fractions, species, index_species, mintolDisplay, FLAG_PLOT_VALIDATION)#

Remove species that do not appear

plot(mixture, x_var, x_field, y_field, varargin)#

Plot molar fractions againts any variable

Parameters:
  • obj (PlotComposition) – Instance of the PlotComposition class

  • mixture (Mixture) – Data of the mixture, conditions, and databases

  • x_var (cell) – Properties of the mixture for all the cases

  • x_field (char) – Field name for the x-axis data

  • y_field (char) – Field name for the y-axis data

Optional Name-Value Pair Args:
  • validation (struct): Struct that contains validations with (x_field, y_field)

  • nfrec (float): Frequency points to plot validations

  • mintol (float): Minimum limit i-axis with the composition of the mixture

  • displaySpecies (cell): List of species to plot

  • y_var (cell): Get y-axis data from a different mixture

  • config (struct): Struct with the configuration for plots

  • axis_x (char): Set x-axis limits

  • axis_y (char): Set y-axis limits

  • xscale (char): Set x-axis scale (linear or log)

  • yscale (char): Set y-axis scale (linear or log)

  • xdir (char): Set x-axis direction (normal or reverse)

  • ydir (char): Set y-axis direction (normal or reverse)

  • ax (object): Handle of the axes to plot on

Returns:

Tuple containing

  • ax (object): Handle of the axes

  • fig (object): Handle of the figure

Examples

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’)

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’, ‘y_var’, mixArray2)

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’, ‘y_var’, mixArray2, ‘validation’, resultsCEA)

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’, ‘y_var’, mixArray2, ‘validation’, resultsCEA, ‘displaySpecies’, displaySpecies)

PlotConfig#

The PlotConfig class provides a set of predefined plot configurations that can be used to customize the appearance of plots generated by the Combustion Toolbox.

Routines
class PlotConfig(varargin)#

Bases: sphinxcontrib.mat_types.handle

Class to store plot configuration data

position#

Default figure position [pixels]

Type:

float

innerposition#

Set figure inner position [normalized]

Type:

float

outerposition#

Set figure outer position [normalized]

Type:

float

linestyle#

Set line style for plots

Type:

char

symbolstyle#

Set symbol style for plots

Type:

char

linewidth#

Set line width for plots

Type:

float

fontsize#

Set fontsize

Type:

float

colorpalette#

Set Color palette (see brewermap function for more options)

Type:

char

colorpaletteLenght#

Set Maximum number of colors to use in the color palette

Type:

float

cmap#

Color map for plotting

Type:

float

box#

Display axes outline

Type:

char

grid#

Display or hide axes grid lines

Type:

char

hold#

Retain current plot when adding new plots

Type:

char

axis_x#

Set x-axis limits

Type:

char

axis_y#

Set y-axis limits

Type:

char

xscale#

Set x-axis scale (linear or log)

Type:

char

yscale#

Set y-axis scale (linear or log)

Type:

char

xdir#

Set x-axis direction (normal or reverse)

Type:

char

ydir#

Set y-axis direction (normal or reverse)

Type:

char

title#

Set title

Type:

char

label_type#

Set label with variable (short), name (medium), or name and variable (long)

Type:

char

labelx#

Set x label

Type:

char

labely#

Set y label

Type:

char

legend_name#

Set legend labels

Type:

char

legend_location#

Set legend location

Type:

char

colorline#

Default colorline

Type:

float

colorlines#

Default colorlines

Type:

float

blue#

Default colorline

Type:

float

gray#

Default colorline

Type:

float

red#

Default colorline

Type:

float

orange#

Default colorline

Type:

float

brown#

Default colorline

Type:

float

brown2#

Default colorline

Type:

float

id_polar1#

Axes id for pressure-deflection polar diagrams

Type:

float

id_polar2#

Axes id for wave-deflection polar diagrams

Type:

float

id_polar3#

Axes id for velocity polar diagrams

Type:

float

PlotConfig(varargin)#

Class constructor

axis_x = "'tight'"

Set x-axis limits

axis_y = "'auto'"

Set y-axis limits

blue = '[0.3725, 0.7373, 0.8275]'

Default colorline

box = "'off'"

Display axes outline

brown = '[200, 190, 183]/255'

Default colorline

brown2 = '[72, 55, 55]/255'

Default colorline

cmap = None

Color map for plotting

colorline = '[44, 137, 160]/255'

Default colorline

colorlines = '[135, 205, 222;                      95, 188, 211;                      44, 137, 160;                      22,  68,  80]/255'

Default colorlines

colorpalette = "'Seaborn'"

Set Color palette (see brewermap function for more options)

colorpaletteLenght = '11'

Set Maximum number of colors to use in the color palette

displaySpecies = None#

Display species

fontsize = '22'

Set fontsize

gray = '[0.50, 0.50, 0.50]'

Default colorline

grid = "'off'"

Display or hide axes grid lines

hold = "'on'"

Retain current plot when adding new plots

id_polar1 = '1001'

Axes id for pressure-deflection polar diagrams

id_polar2 = '1002'

Axes id for wave-deflection polar diagrams

id_polar3 = '1003'

Axes id for velocity polar diagrams

innerposition = '[0.15 0.15 0.35 0.45]'

Set figure inner position [normalized]

innerpositionLayout = '[0.15 0.05 0.7 0.9]'#

Set figure inner position [normalized]

label_type = "'short'"

Set label with variable (short), name (medium), or name and variable (long)

labelx = '[]'

Set x label

labely = '[]'

Set y label

legend_location = "'northeastoutside'"

Set legend location

legend_name = '[]'

Set legend labels

lineStyles = "{'-', '--', ':', '-.'}"#

Line styles for plotting

linestyle = "'-'"

Set line style for plots

linewidth = '1.8'

Set line width for plots

mintolDisplay = '1e-6'#

Minimum tolerance to display species

numPlotProperties = None#

Number of properties to plot

numStyles = None#

Number of line styles available

orange = '[212, 85, 0]/255'

Default colorline

outerposition = '[0.15 0.15 0.35 0.45]'

Set figure outer position [normalized]

outerpositionLayout = '[0.15 0.05 0.7 0.9]'#

Set figure outer position [normalized]

padding = "'loose'"#

Set padding for tiled layout (‘none’, ‘tight’, ‘loose’, ‘compact’)

plotProperties = "{'T', 'p', 'rho', 'h', 'e', 'g', 'cp', 's', 'gamma_s', 'sound'}"#

Plot properties

plotPropertiesBasis = "{[], [], [], 'mi', 'mi', 'mi', 'mi', 'mi', [], []}"#

Plot properties basis

position = None

Figure position [pixels]

red = '[0.64,0.08,0.18]'

Default colorline

symbolStyles = "{'d', 'o', 's', '<'}"#

Symbol styles for plotting

symbolstyle = "'o'"

Set symbol style for plots

tilespacing = "'loose'"#

Set tile spacing for tiled layout (‘none’, ‘tight’, ‘loose’, ‘compact’)

title = '[]'

Set title

xdir = "'normal'"

Set x-axis direction (normal or reverse)

xscale = "'linear'"

Set x-axis scale (linear or log)

ydir = "'normal'"

Set y-axis direction (normal or reverse)

yscale = "'linear'"

Set y-axis scale (linear or log)

Functions#

A collection of functions in the display subpackage.

Routines
getMonitorPositions(varargin)#

Routine that gets the position in pixels of the monitor(s) connected to the device using Java (default) or MATLAB’s routines. If no monitor is specified, the position of the main monitor is returned.

Optional Args:

monitor_id (float): Get position in pixels for the given monitor

Returns:

position (float) – Position of the monitor(s)

Examples

  • position = get_monitor_positions() returns the position of the main monitor

  • position = getMonitorPositions(2) returns the position of the second monitor

  • position = getMonitorPositions(1) returns the position of the first monitor

  • position = getMonitorPositions(monitor_id) returns the position in pixels of the given monitor

Notes

This function first tries using Java to get the screen size values that do not take into account ui scaling, so it will return the proper screen size values. Otherwise, it gets the screen position using MATLAB’s routines

getMonitorPositionsMATLAB(varargin)#

Routine that gets the position in pixels of the monitor(s) connected to the device using MATLAB’s routines. If no monitor is specified, the position of the main monitor is returned.

Optional Args:

monitor_id (float): Get position in pixels for the given monitor

Returns:

position (float) – Position of the monitor(s)

Examples

  • position = get_monitor_positions() returns the position of the main monitor

  • position = getMonitorPositions(2) returns the position of the second monitor

  • position = getMonitorPositions(1) returns the position of the first monitor

  • position = getMonitorPositions(monitor_id) returns the position in pixels of the given monitor

getTitle(obj)#

Get a title based on the problem type and species involved

Parameters:

obj (Mixture) – Mixture object

Returns:

titlename (char) – Title based on the problem type and species involved

interpreterLabel(property, varargin)#

Interpreter label for properties - returns property name

Note

The ‘interpreter_label.m’ routine considers that the properties are in mass basis. This will be fixed in a future patch.

Parameters:

property (char) – Property name

Optional Args:
  • type (char): Type of label to return. Can be ‘short’, ‘medium’ or ‘long’ (default: medium)

  • FLAG_BASIS (bool): Flag indicating label with basis, e.g., kg or mol (default: true)

  • basis (char): Specific basis (default: kg)

Returns:

value (char) – Corresponding name of the property

plotComposition(obj, x_var, x_field, y_field, varargin)#

Plot molar fractions againts any variable

Parameters:
  • obj (Mixture) – Data of the mixture, conditions, and databases

  • x_var (cell) – Properties of the mixture for all the cases

  • x_field (char) – Field name for the x-axis data

  • y_field (char) – Field name for the y-axis data

Optional Name-Value Pair Args:
  • validation (struct): Struct that contains validations with (x_field, y_field)

  • nfrec (float): Frequency points to plot validations

  • mintol (float): Minimum limit i-axis with the composition of the mixture

  • displaySpecies (cell): List of species to plot

  • y_var (cell): Get y-axis data from a different mixture

  • config (struct): Struct with the configuration for plots

  • axis_x (char): Set x-axis limits

  • axis_y (char): Set y-axis limits

  • xscale (char): Set x-axis scale (linear or log)

  • yscale (char): Set y-axis scale (linear or log)

  • xdir (char): Set x-axis direction (normal or reverse)

  • ydir (char): Set y-axis direction (normal or reverse)

  • ax (object): Handle of the axes to plot on

Returns:

Tuple containing

  • ax (object): Handle of the axes

  • fig (object): Handle of the figure

Examples

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’)

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’, ‘y_var’, mixArray2)

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’, ‘y_var’, mixArray2, ‘validation’, resultsCEA)

  • [ax, fig] = plotComposition(mixArray(1), mixArray, ‘equivalenceRatio’, ‘Xi’, ‘y_var’, mixArray2, ‘validation’, resultsCEA, ‘displaySpecies’, displaySpecies)

plotFigure(x_field, x_var, y_field, y_var, varargin)#

Plot figure with customizable settings

Note

The ‘interpreterLabel.m’ routine considers that the properties are in mass basis. This will be fixed in a future patch.

Parameters:
  • x_field (char) – Field name for the x-axis data

  • x_var (cell) – Cell array containing the x-axis data

  • y_field (char) – Field name for the y-axis data

  • y_var (cell) – Cell array containing the y-axis data

Optional Name-Value Pair Args:
  • config (struct): Struct with the configuration for plots

  • leg or legend (cell): Cell array of strings containing the legend names

  • legend_location (char): Location of the legend

  • ax or axes (object): Handle of the axes to plot on

  • linestyle (char): Line style

  • linewidth (float): Line width

  • fontsize (float): Font size

  • title (char): Title of the figure

  • labelx, xlabel, label_x, or x_label (char): x-axis label

  • labely, ylabel, label_y, or ‘y_label (char): y-axis label

  • label_type (char): Label type

  • xscale (char): Set x-axis scale (linear or log)

  • yscale (char): Set y-axis scale (linear or log)

  • xdir (char): Set x-axis direction (normal or reverse)

  • ydir (char): Set y-axis direction (normal or reverse)

  • color (float): Line color [R, G, B]

Returns:

Tuple containing

  • ax (object): Handle of the axes

  • dline (object): Handle of the plotted line

plotPolar(mixArray1, mixArray2, varargin)#

Routine to obtain shock polar plots, namely:

  • Plot (pressure, deflection)

  • Plot (wave angle, deflection)

  • Plot (velocity_x velocity_y)

Parameters:
  • mixArray1 (Mixture) – Mixture object with the pre-shock state

  • mixArray2 (Mixture) – Mixture object with the post-shock state

Optional Args:
  • mix2_case (Mixture): Mixture object with the post-shock state (case 2)

  • mix0 (Mixture): Mixture object with the post-shock state (case 0)

Returns:

Tuple containing

  • ax1 (object): Handle of the axes with (pressure, deflection)

  • ax2 (object): Handle of the axes with (wave angle, deflection)

  • ax3 (object): Handle of the axes with (velocity_x velocity_y)

Examples

  • [ax1, ax2, ax3] = plotPolar(mixArray1, mixArray2)

  • [ax1, ax2, ax3] = plotPolar(mixArray1, mixArray2, mix2_case, mix0)

plotProperties(x_field, x_var, y_field, y_var, varargin)#

Plot figure with customizable settings

Parameters:
  • x_field (cell) – Cell array containing field names for the x-axis data

  • x_var (cell) – Cell array containing the x-axis data

  • y_field (cell) – Cell array containing field names for the y-axis data

  • y_var (cell) – Cell array containing the y-axis data

Optional Name-Value Pair Args:
  • config (plotConfig): object with the plot configuration

  • leg or legend (cell): Cell array of strings containing the legend names

  • legend_location (char): Location of the legend

  • ax or axes (object): Handle of the axes to plot on

  • linestyle (char): Line style

  • linewidth (float): Line width

  • fontsize (float): Font size

  • title (char): Title of the figure

  • labelx, xlabel, label_x, or x_label (char): x-axis label

  • labely, ylabel, label_y, or ‘y_label (char): y-axis label

  • label_type (char): Label type

  • xscale (char): Set x-axis scale (linear or log)

  • yscale (char): Set y-axis scale (linear or log)

  • xdir (char): Set x-axis direction (normal or reverse)

  • ydir (char): Set y-axis direction (normal or reverse)

  • color (float): Line color [R, G, B]

Returns:

mainfigure (obj) – Figure object

setFigure(varargin)#

Initialize figure with a standard composition

Optional Args:
  • ax (axis): Figure axis

  • config (struct): Struct with default plot parameters

Returns:

Tuple containing

  • ax (axis): Axis of the standard figure

  • config (struct): Struct with default plot parameters

  • fig (figure): Standard figure

Example

[ax, config, fig] = setFigure(); [ax, config, fig] = setFigure(ax); [ax, config, fig] = setFigure(config); [ax, config, fig] = setFigure(ax, config);

See also: plot_settings

setLegends(ax, legend_name, varargin)#

Set legend to the given axes

Parameters:
  • ax (object) – Handle to the axes

  • legend_name (cell) – Cell array of char containing the legend names

Optional Name-Value Pairs Args:
  • config (struct): Struct containing the configuration parameters for the plots

  • obj (object): Handle to the plotted objects (e.g. lines, patches, etc.)

setTitle(ax, varargin)#

Set legend to the given axes

species2latex(species, varargin)#

Convert species name into LateX format

Parameters:

species (char) – Species name

Optional Args:

FLAG_BURCAT (bool): If true, do not remove Burcat database prefix (default: true)

Returns:

speciesLatex (char) – Species name in LateX format

Examples

  • species2latex(‘H2ObLb’)

  • species2latex(‘Si2H6_M’)

  • species2latex(‘Si2H6_M’, false)

Math subpackage#

The math subpackage includes a variety of mathematical functions that are essential for performing numerical calculations.

Routines
computeFirstDerivative(x, y)#

Compute first central derivate using a non-uniform grid

Parameters:
  • x (float) – Grid values

  • y (float) – Values for the corresponding grid

Returns:

dxdy (float) – Value of the first derivate for the given grid and its corresponding values

fftfreq(n, varargin)#

Return the Discrete Fourier Transform sample frequencies

The returned float array f contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second.

Given a window length n and a sample spacing d:

f = [0, 1, …, n/2-1, -n/2, …, -1] / (d*n) if n is even f = [0, 1, …, (n-1)/2, -(n-1)/2, …, -1] / (d*n) if n is odd

Parameters:

n (float) – Window length

Optional Args:

d (float): Sample spacing (inverse of the sampling rate) [default: 1]

Returns:

value (float) – Array of length n//2 + 1 containing the sample frequencies

floorDiv(a, b)#

Round the result of division toward negative infinity

Parameters:
  • a (float) – Value a

  • b (float) – Value b

Returns:

x (float) – Floor division

Example

x = floorDiv(5, 2);

getAlignment(field1, field2)#

Computes the local cosine of the angle (alignment) between two vector fields

Parameters:
  • field1 (float) – 3D vector field

  • field2 (float) – 3D vector field

Returns:

cosTheta (float) – 3D array representing the pointwise cosine of the angle between two vectors

getGradientAlignment(field1, field2, x, y, z)#

Compute the alignment between two gradient fields

Parameters:
  • field1 (float) – 3D scalar field for which the gradient is computed

  • field2 (float) – 3D scalar field for which the gradient is computed

  • x (float) – 3D array with the x-coordinate of the grid

  • y (float) – 3D array with the y-coordinate of the grid

  • z (float) – 3D array with the z-coordinate of the grid

Returns:

cosTheta (float) – 3D array with the cosine of the angle between gradients

getOrder(value)#

Get order of magnitude of a number in base 10

Parameters:

value (float) – number in base 10

Returns:

order (float) – order of magnitude of a number in base 10

Example

order = getOrder(0.0001)

gradientPeriodic(phi, x, y, z)#

Computes the gradient of a three-dimensional scalar field using second-order central finite differences considering a periodic box

Parameters:
  • phi (float) – Scalar field to compute the gradient of

  • x (float) – 3D array with the x-coordinate of the grid

  • y (float) – 3D array with the y-coordinate of the grid

  • z (float) – 3D array with the z-coordinate of the grid

Returns:

grad_x (float) – 3D array with the gradient of phi over x grad_y (float): 3D array with the gradient of phi over y grad_z (float): 3D array with the gradient of phi over z

Example

[grad_x, grad_y, grad_z] = gradientPeriodic(phi, x, y, z);

Optimization subpackage#

The optimization subpackage includes algorithms for minimizing or maximizing objective functions, solving constrained and unconstrained optimization problems.

Routines
simplex(A, b, c)#
Use simplex method to solve the next linear programming problem:
  • min c’x,

  • A * x = b,

  • x >= 0.

Parameters:
  • A (float) – Coefficient matrix for the equality constraints (Ax = b)

  • b (float) – Right-hand side vector of the equality constraints

  • c (float) – Coefficient vector of the objective function (minimize c’x)

Returns:

x (float) – Optimal solution vector

Example

x = simplex(A, b, c)

simplexCheck(A, b, c)#
Use Matlab’s simplex method to solve the next linear programming problem:
  • min c’x,

  • A * x = b,

  • x >= 0.

Parameters:
  • A (float) – Coefficient matrix for the equality constraints (Ax = b)

  • b (float) – Right-hand side vector of the equality constraints

  • c (float) – Coefficient vector of the objective function (minimize c’x)

Returns:

x (float) – Optimal solution vector

Example

x = simplexCheck(A, b, c)

simplexDual(A, b)#
Use simplex method to solve the next linear programming problem:
  • max(min x) -> max t,

  • A * x = b,

  • x >= 0.

Parameters:
  • A (float) – Coefficient matrix for the equality constraints (A * x = b)

  • b (float) – Right-hand side vector of the equality constraints

Returns:

x (float) – Optimal solution vector x_min (float): Minimum value of x

Example

[x, x_min] = simplexDual(A, b)

simplexDualCheck(A_eq, b_eq, c, A_ineq, b_ineq)#
Use Matlab’s simplex method to solve the next linear programming problem:
  • max(min x) -> max t,

  • A * x = b,

  • x >= 0.

Parameters:
  • A_eq (float) – Coefficient matrix for the equality constraints (A * x = b)

  • b_eq (float) – Right-hand side vector of the equality constraints

  • c (float) – Coefficient vector of the objective function max t -> min -t

  • A_ineq (float) – Coefficient matrix for the inequality constraints (x_j - t >= 0)

  • b_ineq (float) – Right-hand side vector of the inequality constraints

Returns:

x (float) – Optimal solution vector x_min (float): Minimum value of x

Example

[x, x_min] = simplexDualCheck(A_eq, b_eq, c, A_ineq, b_ineq)

Extensions subpackage#

The extensions subpackage is designed for third-party functions. It includes utilities and tools developed by external contributors that extend the capabilities of the Combustion Toolbox.

Other functions and classes#

This section includes various other utility functions and classes that don’t fall under the specific subpackages mentioned above. These general-purpose tools support a wide range of tasks within the Combustion Toolbox.

Benchmark#

The Benchmark class is used to perform a set of benchmark tests using the Combustion Toolbox code. It measures and reports the average computational time of selected functions over multiple iterations.

Routines
class Benchmark(varargin)#

Bases: sphinxcontrib.mat_types.handle

The Benchmark() class is used to perform a set of benchmark tests using the Combustion Toolbox code. It measures and reports the average computational time of selected functions over multiple iterations.

The Benchmark() object can be initialized as follows:

bench = Benchmark(tests, numIterations)

Here tests is a cell array of function handles representing the benchmarked functions, and numIterations specifies the number of times each function will be executed to compute the average execution time.

Example usage:

% Define benchmark tests as function handles tests = {@run_validation_TP_CEA_6, @another_test_function};

% Create the Benchmark object with tests and number of iterations bench = Benchmark(tests, ‘numIterations’, 20);

% Run the tests bench = bench.run();

% Generate and display the report bench.report();

See also: timeFunction(), cpuinfo()

Benchmark(varargin)#

Constructor

static getDefaultTests()#

Get default tests

metadata = None#

BenchmarkMetadata array storing metadata for each test

numIterations = None#

Number of iterations for each test

numTest = None#

Number of tests

report()#

The report() method displays a formatted benchmark report, showing the average execution times for each test.

Parameters:

obj (Benchmark) – Benchmark object containing recorded execution times.

Examples

  • bench.report();

See also: Benchmark(), runTests()

run()#

The run() method executes the benchmark tests and records the average execution time for each test function.

Parameters:

obj (Benchmark) – Benchmark object containing the tests to be executed.

Returns:

obj (Benchmark) – Benchmark object updated with the execution times of each test.

Examples

  • bench = bench.run();

system = None#

Struct storing CPU and system information

tests = None#

Cell array of function handles

BenchmarkMetadata#

The BenchmarkMetadata class class is used to store and manage metadata information for benchmark tests in the Combustion Toolbox.

Routines
class BenchmarkMetadata(solver, mixtureArray, filename, varargin)#

Bases: sphinxcontrib.mat_types.handle

The BenchmarkMetadata() class is used to store and manage metadata information for benchmark tests in the Combustion Toolbox.

The BenchmarkMetadata() object can be initialized as follows:

metadata = BenchmarkMetadata(solver, mixtureArray, 'filename', 'run_validation_TP_CEA_1', 'testname', 'C6H6_air1_TP')

Here the parameters specify various metadata attributes such as the module name, problem type, filename, test name, number of cases, number of species, and tolerance.

See also: Benchmark()

BenchmarkMetadata(solver, mixtureArray, filename, varargin)#

Constructor

asTable()#

Export metadata as a single-row MATLAB table

avgTime = None#

Average execution time for the benchmark

filename = None#

Name of the file containing benchmark data

getMetadata()#

Get metadata

mixtureArray = None#

Array of mixture objects used in the benchmark

module = None#

Name of the module being benchmarked

numCases = None#

Number of cases in the benchmark

numSpecies = None#

Number of species involved

print()#

Display metadata information

problemType = None#

Type of problem (e.g., ‘TP’, ‘TV’, ‘HP’, etc.)

setTime(time)#

Set average execution time

solver = None#

Solver used in the benchmark

tolerance = None#

Tolerance level for the benchmark

Export#

The Export class provides functionalities to export results into different formats.

Routines
class Export(varargin)#

Bases: sphinxcontrib.mat_types.handle

Class to export and save data to different formats (Excel, CSV, and mat)

Export(varargin)#

Class constructor

FLAG_PROMT = None#

Flag to show promt to save data

compositionUnit = None#

Composition unit (kg or mol)

compositionVariable = None#

Composition variable (molar fraction)

export(mixArray, varargin)#

Export results of reactants (mix1) and products (mix2) into a .xls file

Parameters:
  • obj (Export) – Export object

  • mixArray (Mixture) – Array of mixture objects

Optional Args:
  • mixArray_i (Mixture): Additional arrayy of mixture objects

Examples

  • exportResults(Export(), mixArray1)

  • exportResults(Export(), mixArray1, mixArray2)

  • exportResults(Export(), mixArray1, mixArray2, mixArray3)

filename = None#

Filename to save data

format = None#

Format to save data (Excel, CSV, or mat)

generateMatrix(mixArray, listSpecies, equivalenceRatio)#

Construct a cell with the thermodynamic data of the given mixture

Parameters:
  • obj (Export) – Export object

  • mixArray (Mixture) – Mixture object

  • listSpecies (cell) – List of species

  • equivalenceRatio (float) – Vector of equivalence ratio

Returns:

data (cell) – Cell array with the thermodynamic data of the given mixture

Example

data(Export(), mixArray, {‘CH4’, ‘O2’, ‘CO2’, ‘H2O’}, [0.5, 1.0, 1.5])

SystemUtils#

The SystemUtils class contains utility functions for system operations, such as identifying the operating system and opening URLs in the default web browser. This class provides convenient methods to interact with the system environment, aiding in the integration and functionality of the Combustion Toolbox.

Routines
class SystemUtils#

Bases: sphinxcontrib.mat_types.handle

SystemUtils - A class containing utility functions for system operations

Examples

static getOS()#

This function returns a char indicating the operating system.

Returns:

os (char) – Operating system

Example

os = SystemUtils.getOS();

static openWebsite(url)#

Open website in default web browser

Example

SystemUtils.openWebsite(’https://combustion-toolbox-website.readthedocs.io/’)

url = 'getUrl()'#

URLs

static websiteCT()#

Open Combustion Toolbox’s website in default web browser

HTRDataAverage#

The HTRDataAverage class is designed for postprocessing and statistical analysis of simulation data from the HTR solver. It provides utilities to compute spatial and temporal averages of key flow properties, such as velocity, temperature, pressure, and species concentrations.

Routines
class HTRDataAverage(filepath, varargin)#

Bases: sphinxcontrib.mat_types.handle, combustiontoolbox.utils.HTRDataReader

The HTRDataAverage() class provides methods to process averaged data from the HTR solver [1] output files, which are stored in the Hierarchical Data Format (HDF) file format.

The Hypersonic Task-based Research (HTR) solver [1] is an open-source exascale-oriented task-based multi-GPU high-order code for hypersonics aerothermodynamics. The HTR solver is available at the GitHub repository [2].

Note: The root-mean-square (rms) values from the HTR solver output files are not the true rms values, they are the square of the rms values.

References

[1] Di Renzo, M., Fu, L., and Urzay, J., HTR solver: An open-source

exascale-oriented task-based multi-GPU high-order code for hypersonics aerothermodynamics, Comput. Phys. Commun, Vol. 255, 2020, p. 107262

[2] https://github.com/stanfordhpccenter/HTR-solver

FLAG_K0 = 'false'#

Flag to normalize the grid coordinate

FLAG_SHIFT = 'true'#

Flag to shift the grid coordinate to the shock location

HTRDataAverage(filepath, varargin)#

Constructor for HTRDataAverage

Parameters:

filepath (char) – Path to the .hdf file

applyWeight(property)#

Apply weight to the raw data

averages = None#

Struct holding computed averages and derived data

axis = "'x'"#

Axis for cross-plane averaging (‘x’, ‘y’, or ‘z’)

eta = None#

Ratio of dilatational to solenoidal turbulent kinetic energy

filepath = None#

Path to the .hdf file

getAverages()#

Complet averaging of the raw data

getCorrelations()#

Compute two-point statistics of the data (correlations)

Note: The correlations are normalized by the pre-shock values

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

correlations (float) – Correlations of the data

getDissipation()#

Compute dissipation rate from the data

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

dissipation (float) – Dissipation rate

getFarfieldLocation()#

Get far-field location from the data

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

indexFarfield (float) – Index of the far-field location

getFavreRMS(property)#

Compute Favre root-mean-square (rms) of the data

getGrid()#

Get grid coordinate in the axis for cross-plane averaging and find shock location

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

x (float) – 1D array with the grid coordinate in the axis for cross-plane averaging dx (float): 1D array with the grid spacing in the axis for cross-plane averaging

getKolmogorovLength()#

Compute Kolmogorov length scale from the data

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

lengthKolmogorov (float) – Kolmogorov length scale ratioGridLengthKolmogorov (float): Ratio of the grid length to the Kolmogorov length scale

getLocalTurbulentMachNumber()#

Compute local turbulent Mach number from the data

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

Mt (float) – Local turbulent Mach number

getRMS(property)#

Compute Reynolds root-mean-square (rms) of the data

getShockLocation()#

Identify the mean shock location based on velocity gradients

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

xShock (float) – Shock location indexShock (float): Index of the mean shock location

getTurbulentKineticEnergy()#

Compute turbulent kinetic energy (TKE) amplification ratio from the data

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

TKE_f (float) – Turbulent kinetic energy (TKE) R11_f (float): Reynolds stress R11 R22_f (float): Reynolds stress R22 R33_f (float): Reynolds stress R33 RTT_f (float): Reynolds stress RTT (mean of R22 and R33)

getVariances()#

Compute one-point statistics of the data

Note: The correlations are normalized by the pre-shock values

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Returns:

variances (float) – Variances of the data

indexFarfield = None#

Index of the far-field location to compare with LIA results

indexPostShock = None#

Index of the post-shock location

indexPreShock = None#

Index of the pre-shock location

indexShock = None#

Index of the mean shock location

k0 = None#

Energy-peak wavenumber

listProperties = None#

List of properties in the raw data

listProperties_favg = None#

List of properties in the raw data with Favre average

listProperties_frms = None#

List of properties in the raw data with Favre rms

listProperties_rms = None#

List of properties in the raw data with rms

load(varargin)#

Load raw data from the HTR solver output file

numProperties = None#

Number of properties in the raw data

numProperties_favg = None#

Number of properties in the raw data with Favre average

numProperties_frms = None#

Number of properties in the raw data with Favre rms

numProperties_rms = None#

Number of properties in the raw data with rms

plot(xField, yField, varargin)#

Plot the average data

Parameters:
  • obj (HTRDataAverage) – HTRDataAverage object

  • xField (char) – Name of the x-coordinate property

  • yField (char) – Name of the y-coordinate property

Additional key-value arguments:

ax (matlab.graphics.axis.Axes): Axes object to plot the data

Returns:

ax (matlab.graphics.axis.Axes) – Axes object with the plot

plotConfig = None#

PlotConfig object

plotYaxisScale = '[0.9, 1.3]'#

Factor to scale the y-axis in the plot

print()#

Print summary of the average data

Parameters:

obj (HTRDataAverage) – HTRDataAverage object

Example

print(obj);

rawData = None#

Struct holding raw data from the .hdf file

sliceDim = None#

Slicing dimension

tolShock = '1e-4'#

Relative tolerance for shock detection

weight = None#

Data weighting factor

HTRDataReader#

The HTRDataReader class is responsible for reading and parsing raw simulation data produced by the HTR solver. It enables efficient data extraction for further analysis and visualization.

Routines
class HTRDataReader#

Bases: sphinxcontrib.mat_types.handle

The HTRDataReader() class provides static methods to read 3D fields, coordinates, and general data from HTR solver [1] output files, which are stored in the Hierarchical Data Format (HDF) file format.

The Hypersonic Task-based Research (HTR) solver [1] is an open-source exascale-oriented task-based multi-GPU high-order code for hypersonics aerothermodynamics. The HTR solver is available at the GitHub repository [2].

References

[1] Di Renzo, M., Fu, L., and Urzay, J., HTR solver: An open-source

exascale-oriented task-based multi-GPU high-order code for hypersonics aerothermodynamics, Comput. Phys. Commun, Vol. 255, 2020, p. 107262

[2] https://github.com/stanfordhpccenter/HTR-solver

static read(filepath, property)#

Read general data from the .hdf file

Parameters:
  • filepath (char) – Path to the .hdf file

  • property (char) – Name of the property to read

Returns:

value (float) – Data array for the specified property

static read3D(filepath, property)#

Read a 3D property field from the .hdf file

Parameters:
  • filepath (char) – Path to the .hdf file

  • property (char) – Name of the property to read

Returns:

x, y, z (float) – 3D arrays with the x, y, z components sz (float): Size of the 3D array

static readAverage(filepath, property)#

Read general data from the .hdf file

Parameters:
  • filepath (char) – Path to the .hdf file

  • property (char) – Name of the property to read

Returns:

value (float) – Data array for the specified property

static readCoordinates(filepathNodes)#

Read coordinates and domain length from the .hdf file

Parameters:

filepathNodes (char) – Path to the nodes file

Returns:

x, y, z (float) – 1D arrays of coordinates L (float): Domain length

static readVelocityField(filepath)#

Read a 3D property field from the .hdf file

Parameters:

filepath (char) – Path to the .hdf file

Returns:

velocity (VelocityField) – Velocity field object sz (float): Size of the 3D array

Uncategoized#

Uncategorized utility functions and classes that do not fit into any of the specific subpackages are included here.

Routines
checkUpdate(varargin)#

Check if there is a new release of the Combustion Toolbox

Optional Args:

fig (object): UIFigure class

Returns:

Tuple containing

  • FLAG_UPDATE (bool): FLAG indicating true (false) if there is (not) an update of the Combustion Toolbox

  • message (char): Message displayed

Examples

  • [FLAG_UPDATE, message] = checkUpdate();

  • [FLAG_UPDATE, message] = checkUpdate(UIFigure);

clearCache()#

Function to clear the variables stored in the cache

Example

clearCache()

clusteredMesh1D(xDense, xCoarse, nDense, nCoarse, varargin)#

Create a 1D nonuniform mesh with dense and coarse regions.

Parameters:
  • xDense (float) – Dense region [xDense(1), xDense(2)]

  • xCoarse (float) – Coarse region [xCoarse(1), xCoarse(2)]

  • nDense (float) – Number of points in the dense region

  • nCoarse (float) – Number of points in the coarse region

Optional key-value pairs:
  • ‘SpacingDense’ : ‘log’ (default) or ‘linear’

  • ‘SpacingCoarse’ : ‘log’ (default) or ‘linear’

  • ‘Sort’ : true (default), sorts final mesh

Returns:

x (float) – 1D array of nonuniform mesh points

Examples

  • x = clusteredMesh1D([1, 1.2], [1.2, 10], 50, 50);

  • x = clusteredMesh1D([1, 1.2], [1.2, 10], 50, 50, ‘SpacingDense’, ‘log’, ‘SpacingCoarse’, ‘linear’);

findIndex(LS, species)#

Find the index of the species based on the given list (LS)

Parameters:
  • LS (cell) – List of species

  • species (cell) – Species to find index values

Returns:

index (float) – List with the index of the species based on the given list (LS)

Example

index = findIndex({‘H2O’, ‘CO2’, ‘CH4’}, {‘H2O’, ‘CH4’})

generateID(value)#

Generate a deterministic numeric identifier from input data.

Parameters:

value (char) – Input character array used to generate the ID

Returns:

id (double) – Deterministic 32-bit numeric identifier

Example

id = generateID(‘this_is_an_example’)

getAir(FLAG_IDEAL_AIR)#

Define the chemical species that compound air and its molar composition

Parameters:

FLAG_IDEAL_AIR (bool) – Flag indicating consider ideal or non-ideal air mixture

Returns:

Tuple containing

  • listSpecies (cell): List of species

  • moles (float): Array with molar composition

prettyHeader(txt, varargin)#

Display a formatted header in the command window.

Parameters:

txt (char) – Text to be displayed

Optional Args:

% style (char): Style of the header (‘unicode’, ‘ascii’, ‘banner’). Default is ‘unicode’.

Returns:

header (char) – Formatted header string

Example

prettyHeader(‘My Header’, ‘style’, ‘ascii’)

printConvergence(it, itMax, T, STOP, TOL)#

Print error of the method if the number of iterations is greater than maximum iterations allowed

Parameters:
  • it (float) – Number of iterations executed in the method

  • itMax (float) – Maximum nNumber of iterations allowed in the method

  • T (float) – Temperature [K]

  • STOP (float) – Relative error [-]

  • tol (float) – Relative tolerance [-]

timeFunction(f, nFrec, varargin)#

Function to compute mean evaluation time of a given function f

Parameters:
  • f (function) – Function to be evaluated

  • nFrec (float) – Number of evaluations

Returns:

Tuple containing

  • tMean (float): Average evaluation time

  • tArray (float): Array with the evaluation times

  • varargout: Output of the function f

Note: The function needs at least one input

Example

[tMean, tArray, varargout] = timeFunction(@Example_TP_scoggins2015, 10)