Auxiliary Tool Functions

Auxiliary functions for the manipulation of data and plots.

comfit.tool.tool_add_spacing_2D.tool_add_spacing_2D(X, Y, U, V, spacing)

Add spacing to a 2D field.

Return type:

Tuple[ndarray, ndarray, ndarray, ndarray]

Parameters

Xnp.ndarray

The x-coordinates.

Ynp.ndarray

The y-coordinates.

Unp.ndarray

The x-components of the field.

Vnp.ndarray

The y-components of the field.

spacingint

The spacing to be added.

Returns

Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]

The spaced x-coordinates, y-coordinates, x-components of the field, and y-components of the field.

comfit.tool.tool_add_spacing_3D.tool_add_spacing_3D(X, Y, Z, U, V, W, spacing)

Add spacing to a 3D field.

When working with plot vectors, it is often useful to reduce the number of vectors to make the plot more readable. This function allows you to do that by adding spacing to the field.

Return type:

Tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray]

Parameters

Xnp.ndarray

The x-coordinates.

Ynp.ndarray

The y-coordinates.

Znp.ndarray

The z-coordinates.

Unp.ndarray

The x-components of the field.

Vnp.ndarray

The y-components of the field.

Wnp.ndarray

The z-components of the field.

spacingint

The spacing to be added.

Returns

Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]

The spaced x-, y-, z-coordinates, x-, y-, and z-components of the field.

comfit.tool.tool_make_animation.tool_make_animation_gif(counter, name=None, fps=24, ID=None, delete_png=True)

Make an animation from a series of plot img and save it as a GIF file.

Return type:

None

Parameters

counterint

The number of plot img to include in the animation.

nameOptional[str], optional

The filename for the output GIF, by default None

fpsOptional[int], optional

The frames per second for the GIF, by default 24

IDOptional[str], optional

A unique identifier for the plot image files, by default None

delete_pngOptional[bool], optional

Whether to delete the png files after creating the GIF, by default True

Returns

None

Saves the GIF file.

comfit.tool.tool_make_animation.tool_make_animation_movie(counter, name=None, fps=24, ID=None, delete_png=True)

Make an animation from a series of plot img and save it as an MP4 video file.

Return type:

None

Parameters

counterint

The number of plot img to include in the animation.

nameOptional[str], optional

The filename for the output video, by default None

fpsOptional[int], optional

The frames per second for the video, by default 24

IDOptional[str], optional

A unique identifier for the plot image files, by default None

delete_pngOptional[bool], optional

Whether to delete the png files after creating the video, by default True

Returns

None

Saves the video file.

comfit.tool.tool_colormap.tool_colormap(colormap_string, plot_lib='plotly')

Get a colormap for a plot.

Return type:

Union[LinearSegmentedColormap, List[Tuple[float, str]]]

Parameters

colormap_stringstr

The name of the colormap. See options at https://comfitlib.com/Plotting/

plot_libstr, optional

The plotting library to use, either ‘plotly’ or ‘matplotlib’, by default ‘plotly’

Returns

Union[mcolors.LinearSegmentedColormap, List[Tuple[float, str]]]

For plotly: List of tuples with (position, rgb color string) For matplotlib: A matplotlib colormap object

comfit.tool.tool_complete_field.tool_complete_field(self, field)

Extends a partial field array to a complete array by tiling.

Return type:

ndarray

Parameters

self‘BaseSystem’

A BaseSystem (or derived) instance.

fieldnp.ndarray

Input field array to be extended. Can be 1D, 2D, or 3D array with partial dimensions.

Returns

np.ndarray

Extended field array with complete dimensions matching self.xRes, self.yRes, and self.zRes.

Notes

If input field is incomplete (has dimensions of 1 in some axes), it will be tiled to match the full resolution specified by self.xRes, self.yRes, and self.zRes.

comfit.tool.tool_configure_axis.tool_configure_axis(dim, name, xlim=None, xmin=None, xmax=None, xRes=None, dx=None)

Configure a single axis (x, y, or z) based on the provided parameters.

When constructing a grid, providing all parameters will over-specify the axis. This function takes care of the hierarchy of values and determines the axis limits, minimum value, maximum value, resolution, and step size.

The hierarchy of values is as follows: xlim > xmin > xmax > xRes > dx

Return type:

Tuple[List[float], float, float, int, float]

Parameters

dimint

Dimension of the system (1, 2, or 3)

namestr

Name of the axis (‘x’, ‘y’, ‘z’) for error messages

xlimlist of float, optional

A 2-element list [min, max] for the axis limits

xminfloat, optional

Minimum value of the axis

xmaxfloat, optional

Maximum value of the axis

xResint, optional

Resolution (number of points) along the axis

dxfloat, optional

Step size (spacing between points) along the axis

Returns

tuple

(xlim, xmin, xmax, xRes, dx) where: - xlim is a list of [min, max] values - xmin is the minimum value (float) - xmax is the maximum value (float) - xRes is the resolution (int) - dx is the step size (float)

Notes

Even though the function takes parameters ‘x’-specific parameters, it is used for ‘y’ and ‘z’ as well.

comfit.tool.tool_create_orthonormal_triad.tool_create_orthonormal_triad(t)

Create an orthonormal triad given a vector t.

Return type:

Tuple[ndarray, ndarray, ndarray]

Parameters

tnp.ndarray

Input vector of shape (3,). Does not need to be normalized.

Returns

Tuple[np.ndarray, np.ndarray, np.ndarray]

A tuple (e1, e2, t) containing the orthonormal triad vectors. Each vector is a normalized numpy array of shape (3,).

comfit.tool.tool_extract_node_arrays.tool_extract_node_arrays(self, nodes)

Extracts node arrays from a dictionary of nodes.

Return type:

Dict[str, Any]

Parameters

self‘BaseSystem’

A BaseSystem (or derived) instance.

nodesList[Dict]

List of node dictionaries containing position and other properties

Returns

Dict[str, Any]

Dictionary containing arrays of node properties including: - coordinates (x,y,z) - velocity components if present - charge-separated coordinates if charges present - Burgers vector components if present - tangent vector components if present

comfit.tool.tool_math_functions.levi_civita_symbol(i, j, k)

Calculate the Levi-Civita symbol (antisymmetric tensor).

The Levi-Civita symbol is defined as:

1 if (i,j,k) is an even permutation of (0,1,2) -1 if (i,j,k) is an odd permutation of (0,1,2) 0 if any indices are repeated or not in {0,1,2}

Parameters

iint

First index

jint

Second index

kint

Third index

Returns

int

Value of Levi-Civita symbol: 1, -1, or 0

Examples

>>> levi_civita_symbol(0,1,2)
1
>>> levi_civita_symbol(1,0,2) 
-1
>>> levi_civita_symbol(0,0,1)
0
comfit.tool.tool_math_functions.tool_multinom(*args)

Calculate the multinomial coefficient.

Return type:

float

Parameters

*argsint

Sequence of integers representing the counts of each category.

Returns

float

The multinomial coefficient value.

comfit.tool.tool_matplotlib_define_2D_plot_ax.tool_matplotlib_define_2D_plot_ax(fig, ax=None)

Defines the axes for a 2D plot in matplotlib.

Return type:

Axes

Parameters

figmatplotlib.figure.Figure

Figure object.

axmatplotlib.axes._subplots.AxesSubplot

Axes object.

Returns

axmatplotlib.axes._subplots.AxesSubplot

Axes object.

comfit.tool.tool_matplotlib_define_3D_plot_ax.tool_matplotlib_define_3D_plot_ax(fig, ax=None)

Defines the axes for a 3D plot in matplotlib.

Return type:

Axes3D

Parameters

figmatplotlib.figure.Figure

Figure object.

axmatplotlib.axes._subplots.Axes3DSubplot

Axes object.

Returns

axmatplotlib.axes._subplots.Axes3DSubplot

Axes object.

comfit.tool.tool_plotly_colorbar.format_tick_value(val)

Format a numeric value with appropriate SI prefix and significant figures. This function formats numeric values using SI prefixes and adjusts decimal places based on the magnitude of the number. For values that don’t align with standard SI prefixes, scientific notation is used as a fallback.

Return type:

str

Parameters

valfloat

The numeric value to format.

Returns

str

A string representation of the value with appropriate SI prefix and formatting.

comfit.tool.tool_plotly_colorbar.generate_numbers_between(cmin, cmax)

Generate evenly spaced numbers between given minimum and maximum values.

This function generates a sequence of numbers between cmin and cmax with appropriate step sizes based on the range magnitude. The step size is adjusted to maintain a readable number of ticks.

Return type:

Tuple[ndarray, float]

Parameters

cminfloat

Minimum value of the range.

cmaxfloat

Maximum value of the range.

Returns

tuple[np.ndarray, float]

A tuple containing: - np.ndarray: Array of evenly spaced numbers between cmin and cmax - float: The exponent of the range magnitude (delta_exp)

Raises

ValueError

If cmin is greater than cmax.

Notes

The step size is determined based on the range magnitude: - If range <= 5 units: step = 10^delta_exp - If range <= 10 units: step = 2×10^delta_exp - If range <= 15 units: step = 3×10^delta_exp - If range <= 20 units: step = 4×10^delta_exp

comfit.tool.tool_plotly_colorbar.tool_plotly_colorbar(ax, type='normal')

Add a colorbar to a plotly figure subplot with customizable type and placement.

Return type:

Union[Scatter, Scatter3d]

Parameters

axdict

Dictionary containing subplot information with keys: - ‘vmin’: Minimum value for normal colorbar - ‘vmax’: Maximum value for normal colorbar - ‘plot_dimension’: Integer (2 or 3) indicating plot dimensions - ‘colormap_object’: Plotly colormap object - ‘row’: Row index of subplot - ‘col’: Column index of subplot - ‘nrows’: Total number of rows in figure - ‘ncols’: Total number of columns in figure

typestr, optional

Type of colorbar to create, by default ‘normal’ - ‘normal’: Linear scale with auto-formatted tick values - ‘angle’: Angular scale from -π to π with radian labels

Returns

Union[plotly.graph_objects.Scatter, plotly.graph_objects.Scatter3d]

A scatter trace containing the colorbar configuration. The trace has no data points and is used solely for displaying the colorbar.

Notes

The colorbar placement is automatically calculated based on the subplot position. For normal type, tick values are auto-formatted with scientific notation. For angle type, tick values are displayed in π radians.

comfit.tool.tool_plotly_define_2D_plot_ax.tool_plotly_define_2D_plot_ax(fig, ax)

Define x-axis, y-axis and plot dimension parameters for 2D Plotly plots.

This function sets up axis naming conventions and validates plot dimensions for 2D plots in Plotly. It determines the next available x-axis identifier and corresponding y-axis.

Return type:

Dict[str, Any]

Parameters

figplotly.graph_objects.Figure

The Plotly figure object to define axes for.

axDict[str, Any]

Dictionary containing axis parameters. May include: xN : str (optional, X-axis identifier, e.g., ‘x’, ‘x2’, ‘x3’), yN : str (optional, Y-axis identifier, e.g., ‘y’, ‘y2’, ‘y3’), plot_dimension : int (optional, plot dimension, must be 2 for 2D plots).

Returns

Dict[str, Any]

Updated dictionary containing: xN : str (X-axis identifier), yN : str (Y-axis identifier), plot_dimension : int (Plot dimension, always 2), xaxisN : str (Full x-axis reference, e.g., ‘xaxis’, ‘xaxis2’), yaxisN : str (Full y-axis reference, e.g. ‘yaxis’, ‘yaxis2’).

Raises

ValueError

If plot_dimension is not 2.

Notes

The function automatically determines the next available x-axis identifier if not provided in the input dictionary.

comfit.tool.tool_plotly_define_3D_plot_ax.tool_plotly_define_3D_plot_ax(fig, ax)

Defines and validates parameters for a 3D plot axis in Plotly.

This function checks and sets required parameters for 3D plotting, including validating the plot dimension and assigning a scene number.

Return type:

Dict[str, Any]

Parameters

figplotly.graph_objects.Figure

The Plotly figure object to which the 3D plot will be added.

axdict
Dictionary containing axis parameters. Must include or will set:
  • plot_dimensionint

    Must be 3 for 3D plots

  • sceneNint

    Scene number for the 3D plot, auto-generated if not provided

Returns

dict

Updated axis parameters dictionary with validated 3D plot settings.

Raises

ValueError

If plot_dimension is not 3.

comfit.tool.tool_plotly_find_next_sceneN.tool_plotly_find_next_sceneN(fig)

Find the next available scene name in a Plotly figure.

Return type:

str

Parameters

figplotly.graph_objects.Figure

The Plotly figure to analyze.

Returns

str

The next available scene name. Returns ‘scene’ if no scenes are used, otherwise returns ‘sceneN’ where N is one more than the current highest scene number.

comfit.tool.tool_plotly_find_next_xN.tool_plotly_find_next_xN(fig)

Find the next available x-axis identifier in a Plotly figure.

Return type:

str

Parameters

figplotly.graph_objects.Figure

The Plotly figure to analyze.

Returns

str

The next available x-axis identifier. Returns ‘x’ if no x-axes are used, or ‘xN’ where N is one more than the current highest axis number.

comfit.tool.tool_plot_manipulation_functions.tool_zoom_plot_matplotlib(zoom_factor, ax=None)

Zoom in/out on a matplotlib plot by adjusting axis limits.

Return type:

None

Parameters

zoom_factorfloat

Factor by which to zoom. Values > 1 zoom in, values < 1 zoom out.

axplt.Axes, optional

The axes to apply zoom to. If None, uses current axes, by default None.

Returns

None

Modifies the plot in place.

comfit.tool.tool_print_in_color.tool_print_in_color(string, color='red')

Print a string in color.

Parameters

stringstr

The string to be printed.

colorstr

The color of the string. Options are ‘red’ (default), ‘green’, ‘yellow’, ‘blue’, ‘magenta’, ‘cyan’, ‘white’, ‘black’.

Returns

None

Prints the string

comfit.tool.tool_set_plot_axis_properties_matplotlib.tool_set_plot_axis_properties_matplotlib(self, **kwargs)

Set the properties of the axis for a plot.

Return type:

Axes

Parameters

kwargsdict

Keyword arguments for the axis properties.

Returns

matplotlib.axes.Axes

The axis object with the properties set.

comfit.tool.tool_set_plot_axis_properties_plotly.tool_set_plot_axis_properties_plotly(self, **kwargs)

Set the properties of the axis for a plot.

Return type:

None

Parameters

kwargsdict

Keyword arguments for the axis properties.

Returns

None

Function updates the layout and scene dictionaries with the axis properties.