Color

Color Management

class opencsp.common.lib.render.Color.Color(red: float, green: float, blue: float, name: str, short_name: str)

Bases: object

Class representing an color.

This will begin as a simple [R,G,B] model, but is likely to grow into something more sophisticated.

Potential directions for growth:
  • Support matplotlib color names: ‘g’, ‘cyan’, etc.

  • Support transparency

  • Support more sophisticated color models.

Perhaps there is an existing Python class that we should use instead.

__init__(red: float, green: float, blue: float, name: str, short_name: str)
Parameters:
  • red (float) – The red component in the RGB color space. Range 0-1.

  • green (float) – The green component in the RGB color space. Range 0-1.

  • blue (float) – The blue component in the RGB color space. Range 0-1.

  • name (str) – A descriptive name for the color. For example “black”.

  • short_name (str) – A short hand name for the color. For example “k”.

build_colormap(*next_colors: Color) Colormap

Build a colormap that will return a color between this instance and the next color(s), given a value between 0 and 1.

TODO add a “N” parameter to increase the number of colors in the colormap. See the “N” parameter of https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.ListedColormap.html#matplotlib-colors-listedcolormap.

Parameters:

next_colors (list[Color]) – The color(s) to fade this instance with. Typically this will only be one color, such as for a red-to-blue fade. However, it could also be multiple colors, such as for a blue-to-purple-to-yellow fade (the matplotlib ‘viridis’ default).

classmethod convert(val: Color | str | tuple | None) Color

Convert a color value to a Color object.

Parameters:

val (Color, str, tuple, or None) – The color value to convert.

Returns:

The converted Color object, or None if the input is None.

Return type:

Color or None

Notes

If the input is already a Color object, it is returned unchanged. If the input is a string, it is parsed using the from_str() method. If the input is a tuple, it is assumed to be an RGB value.

classmethod from_generic(val: str | tuple | Color | Callable) Color

Create a color instance from any of the possible input methods.

Parameters:

val (str, tuple, Color, Callable) – The value to create the color from. Can be any of: - hex string such as “0x1f77b4” - name of a color such as “blue” - a tuple of floating point values such as (.12, .47, .71) - a tuple of integer values in the range 0-255 such as (31, 119, 180) - a function that, when called, generates a Color instance

Returns:

The new Color instance for the given value.

Return type:

Color

classmethod from_hex(hexval: str, name: str, short_name: str) Color

Create a Color instance from a hexadecimal color code, with RGB color values in the range 00-FF. For example “0xCCFF00” for greenish yellow.

classmethod from_hsv(hue: float, saturation: float, value: float, name: str, short_name: str)

Create a Color instance from HSV color values in the range 0-1.

classmethod from_i255(red: int, green: int, blue: int, name: str, short_name: str)

Create a Color instance from integer RGB values in the range 0-255.

classmethod from_str(sval='b') Color

Create a Color instance from a color string.

Parameters:

sval (str, optional) – The color string. Should be either a previously registered shorthand string or matplotlib.colors.to_rgb value. Default ‘b’.

rgb() tuple[float, float, float]

Returns color in [R,G,B] format, with range [0,1] for each.

rgb_255() tuple[int, int, int]

Returns color in [R,G,B] format, with range [0,255] for each.

rgba(alpha=1.0) tuple[float, float, float, float]

Returns color in [R,G,B,A] format, with range [0,1] for each.

Parameters:

alpha (float, optional) – The alpha (transparency) value, by default 1.0

Returns:

The color in [R,G,B,A] format

Return type:

tuple[float, float, float, float]

to_hex() str

Returns the color as a hexadecimal string.

Returns:

The color as a hexadecimal string

Return type:

str

to_hsv() tuple[float, float, float]

Returns the color in HSV (Hue, Saturation, Value) format.

Returns:

The color in HSV format

Return type:

tuple[float, float, float]

opencsp.common.lib.render.Color.black()

returns rgb black color

opencsp.common.lib.render.Color.blue()

returns rgb blue color

opencsp.common.lib.render.Color.color_map(*colors_sequence: Color) Colormap

Builds a colormap that will return a color between the given color sequence, given a value between 0 and 1.

Parameters:

*colors_sequence (Color) – The color sequence to build the colormap from

Returns:

The built colormap

Return type:

matplotlib.colors.Colormap

opencsp.common.lib.render.Color.cyan()

returns rgb cyan color

opencsp.common.lib.render.Color.dark_grey()

returns rgb dark grey color

opencsp.common.lib.render.Color.green()

returns rgb green color

opencsp.common.lib.render.Color.grey()

returns rgb grey color

opencsp.common.lib.render.Color.light_grey()

returns rgb light grey color

opencsp.common.lib.render.Color.magenta()

returns rgb magneta color

opencsp.common.lib.render.Color.red()

returns rgb red color

opencsp.common.lib.render.Color.white()

returns rgb white color

opencsp.common.lib.render.Color.yellow()

returns rgb yellow color

opencsp.common.lib.render.Color.plot_colorsi = {0: <opencsp.common.lib.render.Color.Color object>, 1: <opencsp.common.lib.render.Color.Color object>, 2: <opencsp.common.lib.render.Color.Color object>, 3: <opencsp.common.lib.render.Color.Color object>, 4: <opencsp.common.lib.render.Color.Color object>, 5: <opencsp.common.lib.render.Color.Color object>, 6: <opencsp.common.lib.render.Color.Color object>, 7: <opencsp.common.lib.render.Color.Color object>, 8: <opencsp.common.lib.render.Color.Color object>, 9: <opencsp.common.lib.render.Color.Color object>}

//matplotlib.org/stable/users/prev_whats_new/dflt_style_changes.html

We enumerate these colors here as the simplest possible way of accessing these colors, so that we can use or remix them as necessary.

Color order: blue, orange, green, red, purple, brown, pink, gray, yellow, cyan

Type:

Matplotlib default ‘tab10’ colors, from https

View

class opencsp.common.lib.render.View3d.View3d(figure: Figure, axis: Axes, view_spec: dict, equal: bool | None = None, parent: Any | None = None)

Bases: AbstractPlotHandler

Class representing a view of 3d data.

The view may be 2d or 3d, including various projections.

Parameters:
  • view_spec – One of 3d, xy, xz, or yz. Built with Lib.Render.view_spec.view_spec_X().

  • equal – Whether to ensure axes have equal size tick spacing.

__init__(figure: Figure, axis: Axes, view_spec: dict, equal: bool | None = None, parent: Any | None = None)
contour(*args, colorbar=False, **kwargs) None

Will plot the contour lines on top of an image. See matplotlib.axes.Axes.contour for more information.

Parameters:
  • X – They must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.

  • Y – They must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.

  • Z – The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.

draw_heatmap_2d(heatmap_2d, x_range=None, y_range=None, scale=100.0, style=None, colorbar_unimplemented=False)

Draw a 2D heatmap.

Parameters:
  • heatmap_2d (array_like) – The heatmap data, shape (Y, X).

  • x_range (tuple of float, optional) – The range of the x-axis, or None to use shape[1]. Default is None.

  • y_range (tuple of float, optional) – The range of the y-axis, or None to use shape[0]. Default is None.

  • scale (float, optional) – The scale of the heatmap. Uses spline zoom for scaling. Default is 100.0.

  • style (RenderControlHeatmap, optional) – The style of the heatmap, or None for the default style. Default is None.

  • colorbar_unimplemented (bool, optional) – Whether to display a colorbar (not implemented). Default is False.

draw_hist2d(h, xedges, yedges, *args, colorbar=False, **kwargs)

Draw a histogram of the given data.

Parameters:
  • h (array_like) – The histogram data. (shape 1xN or Nx1?)

  • xedges (array_like) – The ticks (bins?) of the histogram along the x-axis.

  • yedges (array_like) – The ticks (scale?) of the histogram along the y-axis.

  • *args – Additional arguments passed to imshow.

  • colorbar (bool, optional) – Whether to display a colorbar. Default is False.

  • **kwargs – Additional keyword arguments passed to imshow.

draw_image(path_or_array_or_cacheable: str | ndarray | CacheableImage, xy_location: tuple[float, float] | None = None, width_height: tuple[float, float] | None = None, cmap: str | Colormap | None = None, draw_on_top: int | bool | None = True, invert_ylim: bool = False)

Draw an image on top of an existing plot.

This method is best for drawing images on top of other plots (example on top of 3D data). For drawing an image by itself use imshow instead.

Parameters:
  • path_or_array_or_cacheable (str | np.ndarray | CacheableImage) – The image to be drawn.

  • xy_location (tuple[float, float], optional) – The location at which to draw the image, in graph coordinate units. None to draw at the lowest extent of the graph. By default None.

  • width_height (tuple[float, float], optional) – The size to scale the image to, in graph coordinate units. None to fit the x-dimension. By default None.

  • cmap (str | matplotlib.colors.Colormap, optional) – The color map to color in the image, or None to not color in the image. Only applicable to grayscale images. By default None.

  • draw_on_top (int | bool | None, optional) – If True, then draw this image on top of other plots. If False, then draw below. A specific zorder can be used by setting this to be an integer. None to use the matplotlib default. Default is True.

  • invert_ylim (bool, optional) – If True, then invert the y axis limits so that they are are in large to small order instead of small to large order. This effectively puts the origin for the graph at the top.

draw_p_list(input_p_list: list[Number], style: RenderControlPointSeq | None = None, label: str | None = None) None

Draw a list of points in 3D space.

Parameters:
  • input_p_list (list) – The list of points to draw.

  • style (rcps.RenderControlPointSeq) – The style to use for drawing, defaults to rcps.default().

  • label (str) – The label to use for the drawn points, defaults to None.

draw_pq(pq: tuple[list, list], style=None, label=None)

Draws the given points to this view. Only draws the points.

Parameters:
  • pq (tuple[list,list]) – A pair of pq lists to be plotted on the x and y axis, respectively. Most typically these will be lists of floats. For example: ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])

  • style (RenderControlPointSeq, optional) – The style used to render the points. By default rcps.default().

  • label (str, optional) – The label for this plot for use in the legend, or None for no label. By default None.

draw_pq_list(input_pq_list: Iterable[tuple[any, any]], close: bool = False, style: RenderControlPointSeq | None = None, label: str | None = None, gradient: bool | str = False)

Draws the given list to this view.

Parameters:
  • input_pq_list (Iterable[tuple[any, any]]) – A list of pq pairs to be plotted on the x and y axis, respectively. Most typically this will be a list of [p,q] float pairs. For example: [[0,5], [1,3], [2,5], …]

  • close (bool) – Draw as a closed polygon. Ignored if less than three points. By default False.

  • style (RenderControlPointSeq, optional) – The style used to render the points. By default rcps.default(), which will draw a line plot.

  • label (str, optional) – The label for this plot for use in the legend, or None for no label. By default None.

  • gradient (bool | str, optional) –

    If True or a string, then the given list is drawn as a linecollection with color map gradient (default ‘Viridis’). If False, then the list is drawn with the single ‘style.color’ color. Default is False.

    Note: the color map is applied as a single color per segment. To get a fade across a single line, you should do something similar to:

    x1, y1 = line_start
    x2, y2 = line_end
    gradient_line_x = np.arange(x1, x2, 20).tolist()
    gradient_line_y = np.arange(y1, y2, 20).tolist()
    gradient_line = list(zip(gradient_line_x, gradient_line_y))
    draw_pq_list(gradient_line, gradient=True)
    

draw_pq_text(pq: tuple[float, float], text: str, style: RenderControlText | None = None)

Draw the given text at the given location.

Parameters:
  • pq (tuple[float, float]) – The location at which to draw the text, in graph units.

  • text (str) – The text to be drawn.

  • style (RenderControlText | None, optional) – The style with which to render the text, or None for rctxt.default(). Default is rctxt.default().

draw_pqdpq_list(input_pqdpq_list, close=False, style=None, label=None)

Draw a list of 2D points with direction vectors.

Parameters:
  • input_pqdpq_list (list[list[list, list]]) – A list of 2D points with direction vectors, where each point is represented as [[p, q], [dp, dq]].

  • close (bool, optional) – Whether to draw the points as a closed polygon (from the last point back to the first). If less than three points are provided, this parameter is ignored. Default is False.

  • style (rcps.RenderControlPointSeq, optional) – The rendering style for the points and vectors. Default is rcps.default().

  • label (str, optional) – A label for the drawn points and vectors, for the legend. Default is None.

draw_xyz(xyz: tuple[float, float] | tuple[float, float, float] | tuple[list, list] | tuple[list, list, list] | ndarray, style: RenderControlPointSeq | None = None, label: str | None = None)

Plots one or more points.

This is similar to draw_xyz_list(), except that it accepts the point locations in a different format. Example usage:

# viewspec xy or pq
draw_xyz((0, 1))
draw_xyz((2, 3))
# or
draw_xyz(([0, 2], [1, 3]))
# or
draw_xyz(np.array([[0, 1], [2, 3]]))

# viewspec xyz or pqr
draw_xyz((0, 1, 2))
draw_xyz((3, 4, 5))
# or
draw_xyz(([0, 3], [1, 4], [2, 5]))
draw_xyz(np.array([[0, 1, 2], [3, 4, 5]]))
Parameters:
  • xyz (tuple[any, any] | tuple[any, any, any] | np.ndarray) – A set of x, y, and z points. This can be a set of numbers, a set of equal-length lists, or a numpy array with shape (2,N) or (3,N).

  • style (rcps.RenderControlPointSeq, optional) – The style used to render the points, or None for the default style (blue, marker ‘.’, line style ‘-‘). By default None.

  • label (str, optional) – The label used to identify this plot on the graph legend. None not to be included in the legend. By default None.

draw_xyz_list(input_xyz_list: Iterable[tuple[float, float, float]], close=False, style: RenderControlPointSeq | None = None, label: str | None = None) None

Draw points, lines, or closed polygons.

Parameters:
  • input_xyz_list (Iterable[tuple[float, float, float]]) – List of xyz three vectors (eg [[0,0,0], [1,1,1]]). The vectors must be indexable, such as with input_xyz_list[0][0].

  • close (Bool, optional) – Draw as a closed polygon. This is done by adding the first value to the end of the input list as a new last value. Ignored if input_xyz_list < 3 points. Default is False.

  • style (RenderControlPointSeq | None, optional) – The style with which to render the input, or None for rcps.default() (blue, marker ‘.’, line style ‘-‘). Default is None.

  • label (str | None, optional) – The label used for this graph in the legend, or None to be excluded from the legend. Default is None.

draw_xyz_surface(surface: ndarray, surface_style: RenderControlSurface | None = None, **kwargs)

Draw a 3D plot for the given z_mesh surface.

Example from https://matplotlib.org/stable/plot_types/3D/surface3d_simple.html#sphx-glr-plot-types-3d-surface3d-simple-py:

# Make data
X = np.arange(-5, 5)
Y = np.arange(-5, 5)
X_mesh, Y_mesh = np.meshgrid(X, Y)
R = np.sqrt(X_mesh**2 + Y_mesh**2)
Z = np.sin(R)

print(X)
# array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4],
#        [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4]])
print(np.round(Z, 2))
# array([[ 0.71,  0.12, -0.44, -0.78, -0.93, -0.96, -0.93, -0.78, -0.44,  0.12],
#        [ 0.12, -0.59, -0.96, -0.97, -0.83, -0.76, -0.83, -0.97, -0.96, -0.59],
#        [-0.44, -0.96, -0.89, -0.45, -0.02,  0.14, -0.02, -0.45, -0.89, -0.96],
#        [-0.78, -0.97, -0.45,  0.31,  0.79,  0.91,  0.79,  0.31, -0.45, -0.97],
#        [-0.93, -0.83, -0.02,  0.79,  0.99,  0.84,  0.99,  0.79, -0.02, -0.83],
#        [-0.96, -0.76,  0.14,  0.91,  0.84,     0,  0.84,  0.91,  0.14, -0.76],
#        [-0.93, -0.83, -0.02,  0.79,  0.99,  0.84,  0.99,  0.79, -0.02, -0.83],
#        [-0.78, -0.97, -0.45,  0.31,  0.79,  0.91,  0.79,  0.31, -0.45, -0.97],
#        [-0.44, -0.96, -0.89, -0.45, -0.02,  0.14, -0.02, -0.45, -0.89, -0.96],
#        [ 0.12, -0.59, -0.96, -0.97, -0.83, -0.76, -0.83, -0.97, -0.96, -0.59]])

# Plot the surface
rc_fig = rcf.RenderControlFigure(tile=False)
rc_axis = rca.RenderControlAxis(z_label='Light Intensity')
rc_surf = rcs.RenderControlSurface()
fig_record = fm.setup_figure_for_3d_data(
    rc_fig, rc_axis, equal=False, name='Light Intensity', code_tag=f"{__file__}")
view = fig_record.view
view.draw_xyz_surface(Z)
plt.show()
Parameters:
  • surface (ndarray) – 2D array of surface values.

  • surface_style (RenderControlSurface, optional) – How to style the surface, by default RenderControlSurface()

draw_xyz_surface_customshape(x_mesh: ndarray, y_mesh: ndarray, z_mesh: ndarray, surface_style: RenderControlSurface | None = None, **kwargs)

Draw a custom-shaped surface in 3D space.

Parameters:
  • x_mesh (np.ndarray) – The x-coordinates of the surface mesh.

  • y_mesh (np.ndarray) – The y-coordinates of the surface mesh.

  • z_mesh (np.ndarray) – The z-coordinates of the surface mesh.

  • surface_style (RenderControlSurface, optional) – The style of the surface, or None for the default style. By default None.

  • **kwargs – Additional keyword arguments passed to Axes3d.plot_surface().

Notes

This method is currently only implemented for view_spec “3d”.

draw_xyz_text(xyz: tuple[float, float, float], text: str, style: RenderControlText | None = None)

Draws the given text at the given location.

Parameters:
  • xyz (tuple[float, float, float]) – The x, y, and z location to draw the text at.

  • text (str) – The text to be drawn.

  • style (rctxt.RenderControlText | None, optional) – The style with which to draw the text, or None for rctxt.default(). By default None

draw_xyz_trisurface(x: ndarray, y: ndarray, z: ndarray, surface_style: RenderControlSurface | None = None, **kwargs)

Draws a 3D trisurface plot.

Parameters:
  • x (np.ndarray) – The x-coordinates of the surface points.

  • y (np.ndarray) – The y-coordinates of the surface points.

  • z (np.ndarray) – The z-coordinates of the surface points.

  • surface_style (RenderControlSurface, optional) – The color and alpha style, or None for the default value. Default is None.

  • **kwargs – Additional keyword arguments passed to the plot_trisurf function.

draw_xyzdxyz_list(input_xyzdxyz_list: list[list[list, list]], close: bool = False, style: RenderControlPointSeq | None = None, label: str | None = None)

Draw a list of 3D points with direction vectors.

Parameters:
  • input_xyzdxyz_list (list[list[list, list]]) – A list of 3D points with direction vectors, where each point is represented as [[x, y, z], [dx, dy, dz]].

  • close (bool, optional) – Whether to draw the points as a closed polygon (from the last point back to the first). If less than three points are provided, this parameter is ignored. Default is False.

  • style (rcps.RenderControlPointSeq, optional) – The rendering style for the points and vectors. Default is rcps.default().

  • label (str, optional) – A label for the drawn points and vectors, for the legend. Default is None.

imshow(*args, colorbar=False, **kwargs) None

Draw an image on a 2D plot. Requires view_spec type to be ‘image’.

This method is best for drawing an image by itself. For drawing images on top of other plots (example on top of 3D data) use draw_image instead.

is_3d() bool

True if the view spec type is ‘3d’.

limit_suffix()

Generates a suffix string based on the current axis limits.

For example, if the y-axis is limited to the range 0-100, then the return value will be “_0x100”.

Returns:

A string representing the axis limits, or an empty string if no limits are set.

Return type:

str

on_key_press(event: KeyEvent, draw_func: Callable)

Handle a key press event.

Parameters:
  • event (backb.KeyEvent) – The key press event.

  • draw_func (callable) – The function to call to redraw the view.

Notes

If the pressed key is ‘f5’, the view will be cleared and redrawn using the provided draw function.

pcolormesh(*args, colorbar=False, **kwargs) None

Allows plotting like imshow, with the additional option of sizing the boxes at will. Look at matplotlib.axes.Axes.pcolormesh for more information.

Parameters:
  • x (iterable) – The coordinates of the x values of quadrilaterals of a pcolormesh

  • y (iterable) – The coordinates of the y values of quadrilaterals of a pcolormesh

  • C (2d numpy array) – The vaues corresponding to the regtangle made by the x and y lists.

pq2xyz(pq)

Convert PQ coordinates to XYZ coordinates for use in a model coordinate system.

How the values are converted is based on the view_spec for this view instance.

pqw2xyz(pqw)

Convert PQW coordinates to XYZ coordinates for use in model coordinate system.

How the values are converted is based on the view_spec for this view instance.

quiver(X: ndarray, Y: ndarray, Z: ndarray, U: ndarray, V: ndarray, W: ndarray, length: float = 0) None

# TODO tjlarki: currently unused # TODO tjlarki: might want to remove, this is a very slow function

register_event_handler(event_type: str, callback: Callable[[Event], None])

Register an event handler for a specific event type.

Parameters:
  • event_type (str) – The type of event to register the handler for. For example “key_release_event”.

  • callback (callable) – The function to call when the event occurs.

Notes

If a callback is already registered for the given event type, it will be deregistered before the new callback is registered.

save(output_dir, output_figure_body, format='png', dpi=300, include_view_suffix=True, include_limit_suffix=True) str

Saves this view to an image file.

Parameters:
  • output_dir (str) – The directory where the output image will be saved.

  • output_figure_body (str) – The base name of the output image.

  • format (str, optional) – The file format to use (default is “png”).

  • dpi (int, optional) – The resolution of the output image, in dots per inch (default is 300).

Returns:

The full path to the saved output image file.

Return type:

str

show(equal=None, x_limits=None, y_limits=None, z_limits=None, grid=None, crop_to_image_frame=True, draw_image_frame=True, image_frame_style=<opencsp.common.lib.render_control.RenderControlPointSeq.RenderControlPointSeq object>, image_frame_legend=False, legend=False, block=False) None

Shows a plot, ensuring that equal axis is set if applicable.

show_and_save(output_dir, output_figure_body, x_limits=None, y_limits=None, z_limits=None, grid=True, crop_to_image_frame=True, draw_image_frame=True, image_frame_style=<opencsp.common.lib.render_control.RenderControlPointSeq.RenderControlPointSeq object>, image_frame_legend=False, legend=True, format='png', dpi=600)

Constructs and displays the figure, and then saves all figures to disk. This routine is useful when you construct a complex figure, and then want to save versions with different axis limits.

The save_all_figures() routine avoids overwriting previously-existing figures, so the work of saving is not replicated, even though it considers saving figures that might already have been saved.

show_and_save_multi_axis_limits(output_dir, output_figure_body, limits_list: list[tuple], grid=True)

Draw and save the same plot multiple times with different axis limits.

Parameters:
  • output_dir – Directory where the figures will be saved.

  • output_figure_body – Body of the figure to be saved.

  • limits_list – List of axis limits. Each limit is a 4 tuple of (x_min, x_max, y_min, y_max) for 2D plots or a 6 tuple of (x_min, x_max, y_min, y_max, z_min, z_max) for 3D plots. If None, the default limits will be used.

  • grid (bool, optional) – Whether to display grid lines on the plot (default is True).

Notes

If limits_list is None, the default limits will be used for all plots. If a limit in limits_list is None, the default limits will be used for that plot.

xyz2pq(xyz)

Convert XYZ coordinates to PQ coordinates for use in a 2d visualization.

How the values are converted is based on the view_spec for this view instance.

xyz2pqw(xyz)

Convert XYZ coordinates to PQW coordinates for use in a 3d visualization.

How the values are converted is based on the view_spec for this view instance.

property view: Figure
class opencsp.common.lib.render.lib.PowerpointImage.PowerpointImage(val: str | ndarray | Image | RenderControlFigureRecord | None = None, dims: tuple[float, float, float, float] | None = None, cell_dims: tuple[float, float, float, float] | None = None, caption_is_above=False, caption: str | None = None, stretch=False, parent_slide=None, persistent_save_path=None)

Bases: PowerpointShape

OpenCSP representation of a pptx powerpoint image, for more control over layouts.

Like all PowerpointShapes, this class can be initialized as a placeholder. Being a placeholder means that it does not have a specific image assigned to it yet. You can check if an image has been assigned with the method has_val().

Typical lifecycle for this class:

  1. Initialization (possibly including image assignment)

  2. Assignment to a PowerpointSlide instance

  3. Assignment of an image with set_val()

  4. Serialize the instance to a file with _to_text_file() to reduce memory usage

  5. De-serialize into a new instance with from_text_file()

  6. Clean up temporary files with clear_tmp_save()

__init__(val: str | ndarray | Image | RenderControlFigureRecord | None = None, dims: tuple[float, float, float, float] | None = None, cell_dims: tuple[float, float, float, float] | None = None, caption_is_above=False, caption: str | None = None, stretch=False, parent_slide=None, persistent_save_path=None)
Parameters:
  • image (str | np.ndarray | Image.Image | rcfr.RenderControlFigureRecord) – The image to add. If an array, image, or figure record, then it will be saved to a temporary file with save(). Defaults to None.

  • dims (tuple[float,float,float,float]) – The (left, top, width, height) of the image on the powerpoint slide, or None to fill in one of the cells from the template slides. Units are inches. Defaults to None.

  • cell_dims (tuple[float,float,float,float]) – The (left, top, width, height) of the bounds for this shape on the powerpoint slide, or None to fill in one of the cells from the template slides. Units are inches. Defaults to None.

  • caption_is_above (bool) – True to put the image caption (if any) above the image, False to put the caption below the image. Defaults to False.

  • caption (str) – The image caption. Defaults to None.

  • stretch (bool) – True to stretch the image dims to fit the entire cell, False to fit the image dims within cell. Most useful with template slides. Default false.

  • parent_slide (PowerpointSlide) – The slide containing this image. Used for fitting within the slide format. If None then the default format will be used. Default None.

clear_tmp_save()

Reloads the image for this instance from the temporary save file, then deletes the temporary save file and its associated metadata file.

classmethod clear_tmp_save_all()

Remove all temporary save files for all saved PowerpointImages

dims_pptx()

Returns the PowerPoint-style dimensions (left, top, width, height) for this image.

Returns:

The dimensions of the image in inches.

Return type:

tuple[float, float, float, float]

fit_to_cell_dimensions(cell_dims: tuple[float, float, float, float])

Fit the image to the specified cell dimensions.

Parameters:

cell_dims (tuple[float, float, float, float]) – The dimensions of the cell (left, top, width, height).

classmethod from_txt_file(path_name_ext: str)

Reconstruct a PowerpointImage instance from a text file.

Parameters:

path_name_ext (str) – The path to the text file containing the serialized data.

Returns:

A new instance of PowerpointImage reconstructed from the text file.

Return type:

PowerpointImage

Raises:

RuntimeError – If the file type or version is incorrect.

get_saved_path() str

Get the pathname.ext to the original or temporary file version of the image content.

Calls save() as necessary to ensure the image is saved.

Returns:

The full path to the saved image file.

Return type:

str

get_size(force_reload=False)

Get the width and height of this image in pixels.

Calls save() as necessary to ensure the image is saved (as in the case that the assigned image is a string or RenderControlFigureRecord).

Parameters:

force_reload (bool, optional) – If True, forces a reload of the image size even if cached values are available. Defaults to False.

Returns:

A tuple containing the width and height of the image in pixels. Returns (None, None) if no image is set.

Return type:

tuple[int, int]

get_text_file_path() str

Get the path to the metadata text file for the image.

Returns:

The path to the text file containing metadata for the saved image.

Return type:

str

get_val() None | str | ndarray | Image | RenderControlFigureRecord

Get the image assigned to this instance. What you probably actually want is get_saved_path(). Returns None if has_val() is False.

Returns:

The image value assigned to this instance. Returns None if no image is assigned (has_val() is False).

Return type:

None | str | np.ndarray | Image.Image | rcfr.RenderControlFigureRecord

has_dims()

Check if dimensions are set for this image.

Returns:

True if dimensions are set, False otherwise.

Return type:

bool

has_val() bool

Returns true if an image has been assigned to this instance, or False if this instance was created without an assigned image and has not had an image assigned yet.

is_saved_to_file()

Check if the image has been saved to a file.

Returns:

True if the image has been saved to a file, False otherwise.

Return type:

bool

reduce_size(reduced_image_size_scale: float = -1)

Reduce the size of the image if it is significantly larger than its rendered size.

This will save the image to disk first if necessary.

Parameters:

reduced_image_size_scale (float) – The scale factor to reduce the image size. If negative, no resizing occurs.

replace_with_save()

Replace this instance’s image with its saved file path.

This method is used to save memory by releasing images.

save() None | str

Saves the metadata for this instance to a text file in the temporary directory, and saves the assigned image (as necessary) to an image file in the same directory.

After saving, this instance can be reconstructed by calling from_text_file() with the returned path+name+ext.

Returns:

ppi_path_name_ext – The path to the serialized instance. None if no image is assigned or saving failed.

Return type:

str | None

set_val(image: str | ndarray | Image | RenderControlFigureRecord)

Assigns an image to this instance. If this instance already has an image assigned then the old value is overwritten without any checking.

Parameters:

image ((str | np.ndarray | Image.Image | rcfr.RenderControlFigureRecord)) – The image to set. Can be a file path, NumPy array, PIL Image, or RenderControlFigureRecord.

stretch_to_cell_dimensions(cell_dims: tuple[float, float, float, float])

Stretch the image to fit the specified cell dimensions.

Parameters:

cell_dims (tuple[float, float, float, float]) – The dimensions of the cell (left, top, width, height).

update_save_path(save_path: str)

Set the path where the image and its associated serialized text will be saved.

If the image has already been saved, it will move the existing image and associated text files to the new save path.

Parameters:

(str) (save_path) – The new directory path where the image should be saved.

dims

The left, top, width, and height of this image on the powerpoint slide, in inches.

height: int

height in pixels (-1 if not yet saved)

width: int

Width in pixels (-1 if not yet saved)

Specifying a view of a three-dimensional space.

Options include general 3-d (allowing interactive rotation), xy, xz, yz, general section plane.

In all of the 2-d cases, there is an embedded (p,q) parameter space, which corresponds to different projections of the 3-d coordinates.

opencsp.common.lib.render.view_spec.pq2xyz(pq, view_spec)

Converts (p, q) coordinates to 3D coordinates based on the view specification.

Parameters:
  • pq (list[float]) – The (p, q) coordinates to convert.

  • view_spec (dict) – The view specification that determines the conversion method.

Returns:

The converted 3D coordinates.

Return type:

list[float]

opencsp.common.lib.render.view_spec.pqw2xyz(pqw, view_spec)

Converts (p, q, w) coordinates back to 3D coordinates based on the view specification.

Parameters:
  • pqw (list[float]) – The (p, q, w) coordinates to convert.

  • view_spec (dict) – The view specification that determines the conversion method.

Returns:

The converted 3D coordinates.

Return type:

list[float]

Raises:

ValueError – If the view specification type is unrecognized.

opencsp.common.lib.render.view_spec.view_spec_3d() dict

Returns a specification dictionary for a 3D view.

Returns:

A dictionary containing the view type set to ‘3d’.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_camera(camera, camera_xform) dict

Returns a specification dictionary for a camera view.

Parameters:
  • camera (object) – The camera object representing the camera’s properties.

  • camera_xform (object) – The transformation object for the camera.

Returns:

A dictionary containing the view type set to ‘camera’ and the camera properties.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_im() dict

Returns a specification dictionary for an image view.

Returns:

A dictionary containing the view type set to ‘image’.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_pq() dict

Returns a specification dictionary for an PQ view.

This function generates a dictionary that specifies the view type as ‘xy’, which can be used for rendering or visualization purposes.

Returns:

A dictionary containing the view type set to ‘xy’.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_pqw() dict

Returns a specification dictionary for an PQW view.

This function generates a dictionary that specifies the view type as ‘xyz’, which can be used for rendering or visualization purposes.

Returns:

A dictionary containing the view type set to ‘xyz’.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_xy() dict

Returns a specification dictionary for an XY view.

Returns:

A dictionary containing the view type set to ‘xy’.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_xyz() dict

Returns a specification dictionary for an XYZ view.

This function generates a dictionary that specifies the view type as ‘xyz’, which can be used for rendering or visualization purposes.

Returns:

A dictionary containing the view type set to ‘xyz’.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_xz() dict

Returns a specification dictionary for an XZ view.

Returns:

A dictionary containing the view type set to ‘xz’.

Return type:

dict

opencsp.common.lib.render.view_spec.view_spec_yz() dict

Returns a specification dictionary for a YZ view.

This function generates a dictionary that specifies the view type as ‘yz’, which can be used for rendering or visualization purposes.

Returns:

A dictionary containing the view type set to ‘yz’.

Return type:

dict

opencsp.common.lib.render.view_spec.xyz2pq(xyz, view_spec)

Converts 3D coordinates to (p, q) coordinates based on the view specification.

Parameters:
  • xyz (np.ndarray) – The 3D coordinates to convert.

  • view_spec (dict) – The view specification that determines the conversion method.

Returns:

The converted (p, q) coordinates, or None if the point is behind the camera in a camera view.

Return type:

list[float] | None

opencsp.common.lib.render.view_spec.xyz2pqw(xyz, view_spec)

Converts 3D coordinates to (p, q, w) coordinates based on the view specification.

Parameters:
  • xyz (np.ndarray) – The 3D coordinates to convert.

  • view_spec (dict) – The view specification that determines the conversion method.

Returns:

The converted (p, q, w) coordinates, or None if the point is behind the camera in a camera view.

Return type:

list[float] | None

Axis

3-d Axis Management

opencsp.common.lib.render.axis_3d.set_3d_axes_equal(ax: Axes3D, set_zmin_zero=False, box_aspect: None | tuple[int, int, int] = (1, 1, 1))

Make axes of 3D plot have equal scale so that spheres appear as spheres, cubes as cubes, etc.. This is one possible solution to Matplotlib’s ax.set_aspect(‘equal’) and ax.axis(‘equal’) not working for 3D.

Input

ax: a matplotlib axis, e.g., as output from plt.gca(). set_zmin_zero: If true, then set the z axis lower limit to 0. box_aspect: If none, do nothing (use the standard 4:4:3 aspect). Otherwise, this should be a 3 tuple. For example, (1:1:1)

Link: https://stackoverflow.com/questions/13685386/matplotlib-equal-unit-length-with-equal-aspect-ratio-z-axis-is-not-equal-to

Image

class opencsp.common.lib.render.ImageAttributeParser.ImageAttributeParser(current_image_source: str | None = None, original_image_source: str | None = None, date_collected: datetime | None = None, experiment_name: str | None = None, notes: str | None = None)

Bases: AbstractAttributeParser

Subclass of AbstractAttributeParser that adds the following extra attributes to the attributes file:

  • current_image_source (str): The most recent filename (or network streamed name) that this image was loaded from.

  • original_image_source (str): The definitive filename (or network streamed name) that this image was loaded from. This is usually going to be the name of the original file, such as “Nikon_2024-04-16.png”.

  • date_collected (datetime): Notes from the specific image processors about this image.

  • experiment_name (str): The name of the measurement or experiment that this image was collected as a part of.

  • notes (str): Extra notes about the image, typically added by the user.

__init__(current_image_source: str | None = None, original_image_source: str | None = None, date_collected: datetime | None = None, experiment_name: str | None = None, notes: str | None = None)

Manager for the most common attributes associated with processed images, for maintaining the context and history of the image.

Parameters:
  • current_image_source (str, optional) – The current source of the image, probably a file name. If not None, then this will attempt to populate the rest of the fields by looking for a sibling “.txt” attributes file. By default None.

  • original_image_source (str, optional) – The original source of the image, probably a file name. If not None, and current_image_source is None, then this will attempt to populate the rest of the fields by looking for a sibling “.txt” attributes file. By default None.

  • date_collected (datetime, optional) – The date (and time) that the original image was collected at, by default None

  • experiment_name (str, optional) – A descriptive name of the experiment that the original image was collected in, if it was part of an experiment. By default None.

  • notes (str, optional) – Any additional notes that would help with understanding the context or history of the image, by default None

attributes_key() str

Returns the key this class (or this instance) uses to index into the attributes file. This key should closely match the class name.

has_contents() bool

Returns True if there are contents that have been set for this instance. False to skip this instance when saving out an attributes file.

my_contents_to_json(file_path_name_ext: str) any

Prepare the contents from this parser to be written to an attributes file. If has_contents() == False, then this parser will be skipped.

_extended_summary_

Parameters:

file_path_name_ext (str) – The path to the attributes file. May be None.

Returns:

my_contents – The contents to be recorded. Should be json-ifiable.

Return type:

dict|list|str|float

parse_my_contents(file_path_name_ext: str, raw_contents: str, my_contents: any)

Parse this attribute parser’s specific contents.

Parameters:
  • file_path_name_ext (str) – The path to the attributes file. May be None.

  • raw_contents (str) – The unparsed string contents of the attributes file.

  • my_contents (any) – The JSON interpretted value for the attributes_key() in the raw_contents.

set_defaults(other: ImageAttributeParser)

Replaces this instance’s None-valued contents with non-None-valued contents from the given other of the same parser type.

Figure Management

Manages figure creation and display.

Features include:

Tiling figures across a window, so they do not appear one on top of the other. Providing Figure names for window names and later fetching Control of figure creation with a figure_control object.

opencsp.common.lib.render.figure_management.do_show_figures(flag: bool = True)

Sets the global flag for displaying figures.

This function updates the global variable show_figures to control whether figures should be displayed or not.

Parameters:

flag (bool, optional) – A boolean flag indicating whether to show figures. Defaults to True.

Return type:

None

opencsp.common.lib.render.figure_management.formatted_fig_display(block: bool = False) None

Displays the current figure in a formatted manner.

This function utilizes Matplotlib’s plt.show() to display the current figure. The block parameter controls whether the display is blocking or non-blocking.

Parameters:

block (bool, optional) – If True, the function will block execution until the figure window is closed. If False, the function will return immediately, allowing further code execution. Defaults to False.

Return type:

None

opencsp.common.lib.render.figure_management.hide_axes(fig_record: RenderControlFigureRecord, figure_control: RenderControlFigure, force_hide: bool = False)

Hides the axes for the plot if axis_control.draw_axes is False. Hides the whitespace around the plot if figure_control.draw_whitespace_padding is False.

Parameters:
  • fig_record (RenderControlFigureRecord) – The figure record to be modified.

  • figure_control (RenderControlFigure) – The control that manages if axes and whitespace are drawn.

  • force_hide (bool, optional) – True to hide the axes and whitespace regardless of the axis_control and figure_control settings. Default is False.

opencsp.common.lib.render.figure_management.mpl_pyplot_figure(*vargs, **kwargs)

Initializes and returns a matplotlib.pyplot.figure() instance.

If creating the figure fails, try again (up to two more times).

Sometimes initializing a matplotlib figure fails. But if you try to initialize the figure() class again, it seems to always succeed. The measured failure rate for first time initialization is between 7% and 15%. When it fails, it is often with an error about not being able to find a file. Something like:

_tkinter.TclError: Can't find a usable init.tcl in the following directories
opencsp.common.lib.render.figure_management.print_figure_summary() None

Prints a summary of recorded figures.

This function iterates through a global list of figure records (fig_record_list) and prints comments associated with each figure. It provides a way to review the details of the figures that have been recorded during the session.

Return type:

None

opencsp.common.lib.render.figure_management.reset_figure_management()

Resets the figure management system to its initial state.

This function resets the figure tile index, sets the figure number to zero, and clears the list of recorded figure records. It effectively reinitializes the figure management system, allowing for a fresh start in managing figures.

Return type:

None

opencsp.common.lib.render.figure_management.reset_figure_tiles()

Resets the index of figure tiles to zero.

This function sets the global variable figure_tile_idx to 0, effectively resetting the state of figure tiles for subsequent operations.

Return type:

None

opencsp.common.lib.render.figure_management.save_all_figures(output_path: str, format: str | None = None)

Saves all figures opened with setup_figure (since reset_figure_management) to the given directory.

Args:

  • output_path (str): The directory to save figures to.

  • format (str): The file format for figures. None for RenderControlFigureRecord.save default. Defaults to None.

Returns:

  • figs: list[str] The list of image files

  • txts: list[str] The list of image descriptor text files

  • failed: list[RenderControlFigureRecord] The list of figure records that failed to save

opencsp.common.lib.render.figure_management.setup_figure(figure_control: RenderControlFigure, axis_control=None, view_spec=None, equal: bool = True, number_in_name: bool = True, input_prefix: str | None = None, name: str | None = None, title: str | None = None, caption: str | None = None, comments: list[str] | None = None, code_tag: str | None = None) RenderControlFigureRecord

Create and setup a new RenderControlFigureRecord for rendering on a 2D graph.

Example:

# draw an image using figure_management
img = cv.imread(os.path.join(img_dir, img_name))
axis_control = rca.image(grid=False)
figure_control = rcfg.RenderControlFigure()
view_spec_2d = vs.view_spec_im()
fig_record = fm.setup_figure(figure_control, axis_control, view_spec_2d, title=img_name, code_tag=f"{__file__}", equal=False)
fig_record.view.imshow(img)
fig_record.view.show(block=True)
# ...
fig_record.close()

Note that even through the returned figure_record will ensure that the associated plot is closed when the associated view object is destructed, it is almost always better to close the figure as soon as it’s not needed any more via the figure_record.close() method.

Arguments:

  • view_spec (view_spec dict): Defines how to draw the plot (which axis is horizontal and vertical). Defaults to view_spec_xy.

  • See setup_figure_for_3d_data() for a description of the other arguments.

See Also:

A similar function for setting up figures for 3D rendering is setup_figure_for_3d_data

opencsp.common.lib.render.figure_management.setup_figure_for_3d_data(figure_control: RenderControlFigure, axis_control=None, view_spec=None, equal: bool = True, number_in_name: bool = True, input_prefix: str | None = None, name: str | None = None, title: str | None = None, caption: str | None = None, comments: list[str] | None = None, code_tag: str | None = None) RenderControlFigureRecord

Create and setup a new RenderControlFigureRecord for rendering on a 3D graph.

Note that even through the returned figure_record will ensure that the associated plot is closed when the associated view object is destructed, it is almost always better to close the figure as soon as it’s not needed any more via the figure_record.close() method.

Arguments:

  • figure_control (RenderControlFigure): Controls how multiple figures get plotted at the same time in multiple windows.

  • axis_control (RenderControlAxis): Defines the axis labels and whether to draw the grid. Defaults to RenderControlAxis().

  • view_spec (view_spec dict): Defines how to draw the plot (which axis is horizontal and vertical, or XYZ for 3D data). Defaults to view_spec_xy.

  • equal (bool): Equal axis ticks. Passed to Lib.Render.View3d.View3D()

  • number_in_name (bool): Each figure record has a unique identifier. If True, add this identifier to the plot name, after the input_prefix. Defaults to True.

  • input_prefix (str): Prefix to include at beginning of figure name, before number is added.

  • name (str): The name for the figure. Used as the file name when saved. Defaults to title.

  • title (str): The title for the plot. Used as the name if the name is None.

  • caption (str): Caption providing concise description plot. Optional details may be added via comments.

  • comments (list[str]): List of strings including comments to associate with the figure.

  • code_tag (str): String of form “code_file.function_name()” showing where to look in code for call that generated this figure.

See Also:

A similar function for setting up figures for 2D rendering is setup_figure

opencsp.common.lib.render.figure_management.show_axes(fig_record: RenderControlFigureRecord, figure_control: RenderControlFigure, force_show: bool = False)

Shows the axes for the plot if axis_control.draw_axes is True. Shows the whitespace around the plot if figure_control.draw_whitespace_padding is True.

Parameters:
  • fig_record (RenderControlFigureRecord) – The figure record to be modified.

  • figure_control (RenderControlFigure) – The control that manages if axes and whitespace are drawn.

  • force_show (bool, optional) – True to show the axes and whitespace regardless of the axis_control and figure_control settings. Default is False.

Video

Video and frames manipulation and creation.

class opencsp.common.lib.render.VideoHandler.VideoHandler(src_video_dir_name_ext: str | None = None, dst_video_dir_name_ext: str | None = None, src_frames_dir: str | None = None, dst_frames_dir: str | None = None, dst_example_frames_dir: str | None = None, video_control: RenderControlVideo | None = None, frame_control: RenderControlVideoFrames | None = None)

Bases: object

Handle video creation, frame extraction, and video transcoding. The format for generated videos and frames is controlled by the video_control and frame_control render controllers.

Not all of these arguments are required for every use case of this class. The generator methods VideoCreator(), VideoTransformer(), and VideoExtractor() can be used to simplify the required parameters down to the most common use cases.

classmethod VideoCreator(src_frames_dir: str, dst_video_dir_name_ext: str, video_control: RenderControlVideo, frame_control: RenderControlVideoFrames)

Create a VideoHandler for creating a video from frames.

Parameters:
  • src_frames_dir (str) – Directory containing the frames to use for creating the video.

  • dst_video_dir_name_ext (str) – Path to the output video file.

  • video_control (rcv.RenderControlVideo) – Video control settings.

  • frame_control (rcvf.RenderControlVideoFrames) – Frame control settings.

Returns:

A VideoHandler instance for creating the video.

Return type:

VideoHandler

classmethod VideoExtractor(src_video_dir_name_ext: str, dst_frames_dir: str, dst_example_frames_dir: str, frame_control: RenderControlVideoFrames)

Create a VideoHandler for extracting frames from a video.

Parameters:
  • src_video_dir_name_ext (str) – Path to the input video file.

  • dst_frames_dir (str) – Directory to store the extracted frames in.

  • dst_example_frames_dir (str) – Directory to store example frames in.

  • frame_control (rcvf.RenderControlVideoFrames) – Frame control settings.

Returns:

A VideoHandler instance for extracting frames from the video.

Return type:

VideoHandler

classmethod VideoInspector(src_video_dir_name_ext: str)

Create a VideoHandler for inspecting a video.

Video inspectors can be useful for retrieving properties of a video, such as with the methods get_width_height(), get_duration(), or get_num_frames().

Parameters:

src_video_dir_name_ext (str) – Path to the video file to inspect.

Returns:

A VideoHandler instance for inspecting the video.

Return type:

VideoHandler

classmethod VideoMerger(src_videos_path, src_videos_ext, dst_video_dir_name_ext)

Create a VideoHandler for merging (concatenating) videos.

Parameters:
  • src_videos_path (str) – Path to the directory containing the videos to merge.

  • src_videos_ext (str) – File extension of the videos to merge.

  • dst_video_dir_name_ext (str) – Path to the output video file.

Returns:

A VideoHandler instance for merging the videos.

Return type:

VideoHandler

classmethod VideoTransformer(src_video_dir_name_ext: str, dst_video_dir_name_ext: str, video_control: RenderControlVideo)

Create a VideoHandler for transforming a video, such as changing the resolution or the encoding method.

Parameters:
  • src_video_dir_name_ext (str) – Path to the input video file.

  • dst_video_dir_name_ext (str) – Path to the output video file.

  • video_control (rcv.RenderControlVideo) – Video control settings.

Returns:

A VideoHandler instance for transforming the video.

Return type:

VideoHandler

__init__(src_video_dir_name_ext: str | None = None, dst_video_dir_name_ext: str | None = None, src_frames_dir: str | None = None, dst_frames_dir: str | None = None, dst_example_frames_dir: str | None = None, video_control: RenderControlVideo | None = None, frame_control: RenderControlVideoFrames | None = None)

Handle video creation, frame extraction, and video transcoding. The format for generated videos and frames is controlled by the video_control and frame_control render controllers.

Not all of these arguments are required for every use case of this class. The generator methods VideoCreator(), VideoTransformer(), and VideoExtractor() can be used to simplify the required parameters down to the most common use cases.

Parameters:
  • src_video_dir_name_ext (str, optional) – The source file name for manipulation of an existing video. Not needed for creating a video from frames.

  • dst_video_dir_name_ext (str, optional) – The destination file name for creating a video. Not needed for extracting frames.

  • src_frames_dir (str, optional) – Where to find frames for video creation.

  • dst_frames_dir (str, optional) – Where to put frames for frame extraction. Defaults to default_output_path()/output_frames.

  • dst_example_frames_dir (str, optional) – Where to put example (debugging) frames for frame extraction. Defaults to default_output_path()/example_frames.

  • video_control (rcv.RenderControlVideo, optional) – Render controller for video creation.

  • frame_control (rcvf.RenderControlVideoFrames, optional) – Render controller for frames.

construct_video(tmp_dir: str | None = None, overwrite: bool = False)

Creates a video “self.dst_video_dir_name_ext” from the images in the “self.src_frames_dir” directory. To precisely control which image files are sourced, call frames_to_video(…) instead.

Parameters:
  • tmp_dir (str) – Where to create a file to temporarily save the frame names to.

  • overwrite (bool) – If true, then remove the existing video before calling ffmpeg.

Returns:

The generated video file (name and extension). None if frame_names is empty.

Return type:

str

extract_frames(start_time: float | None = None, end_time: float | None = None)

Extracts all frames from a video file, placing them in the specified output directory. Creates the directory and its parents if it does not exist. The extracted frame format and directory overwrite option is controlled by the RenderControlVideoFrames.

This takes about 7 hours to finish a 14m30s, 4K, 30fps video on a single 16-core server. This takes about 16 minutes to finish a similar video when parallelized across 20 16-core servers with parallel_video_tools.

Raises:

subprocess.CalledProcessError – Raised if the subprocess returns an error code.

Parameters:
  • start_time (-) – The time to start extracting at.

  • end_time (-) – The time to stop extracting at.

Returns:

The number of frames extracted (not including example frames)

Return type:

int

frames_to_video(frame_names: list[str], tmp_dir: str | None = None, overwrite: bool = False)

Converts specific frames in into a video (vs construct_video() which uses all available frames).

This takes about ~2 minutes for 450 frames with two Xeon E5-2695 36-thread cpus. This can also be parallelized with parallel_video_tools.

Raises:

subprocess.CalledProcessError – Raised if the subprocess returns an error code.

Parameters:
  • frame_names (list[str]) – The list of frame names to generate a video from. This list will be temporarily saved as a file in tmp_dir.

  • tmp_dir (str) – Where to create a file to temporarily save the frame names to.

  • overwrite (bool) – If true, then remove the existing video before calling ffmpeg.

Returns:

The generated video file (name and extension). None if frame_names is empty.

Return type:

str

get_duration(input_or_output='input')

Returns the duration of the source video in seconds.

get_extracted_frame_path_and_name_format(frame_type='output')

Build the frame output name format, including the frame number (ex “-%05d”).=

Parameters:

frame_type (str) – Whether this should be for a normal “output” frame or an “example” frame. Defaults to “output”.

Returns:

The path/nameformat.ext of the output frame.

Return type:

frame_format (str)

get_num_frames(input_or_output='input')

Returns the number of frames in the source video.

get_width_height(input_or_output='input')

Returns the width and height of the source video (or image), in pixels.

identify_duplicate_frames(tolerance_image_size: int, tolerance_image_pixel: int)

Finds all frame duplicates in self.src_frames_dir.

Parameters:
  • tolerance_image_size (-) – Size difference, in bytes, for which the two files can be considered identical.

  • tolerance_image_pixel (-) – How many pixels are allowed to be different and the images are still considered identical.

Returns:

The non-duplicate image’s name+ext - list[str]: The duplicate image’s name+ext

Return type:

  • list[str]

merge_videos(src_video_names: list[str] | None = None, tmp_dir: str | None = None, overwrite: bool = False)

Merges many videos into a single video. For H.265 videos, this is a very fast operation.

Raises:

subprocess.CalledProcessError – Raised if the subprocess returns an error code.

Parameters:
  • src_video_names (-) – The list of videos names to generate a video from, or None to use all videos in the src_video_dir_name_ext directory. This list will be temporarily saved as a file in tmp_dir.

  • tmp_dir (-) – Where to create a file to temporarily save the frame names to.

  • overwrite (-) – If true, then remove the existing video before calling ffmpeg.

Returns:

The generated video file (name and extension). None if src_video_names is empty.

Return type:

  • str

classmethod transform_powerpoint(src_video_dir_name_ext: str, dst_dir: str | None = None, overwrite: bool = False)

Makes a copy of the given video as ‘[path_and_name]_ppt[ext]’ with a reduced size and codec suitable for inclusion in power point. This takes ~3 minutes for 26,000 1080p frames with two Xeon E5-2695 18-core cpus. This takes ~36 minutes for 26,000 4K frames with one Xeon E5-2670 16-core cpu.

Returns:

The dir_name_ext of the output video.

Return type:

str

transform_video(overwrite: bool = False)

Makes a copy of the given video as out_video_path_name_ext, with the various options from the render control.

This can be used to, for example, create a video suitable for power point as with transform_powerpoint(…).

Raises:

subprocess.CalledProcessError – Raised if the subprocess returns an error code.

Plot

Annotations to add to plots and images.

class opencsp.common.lib.render.PlotAnnotation.PlotAnnotation(type, pt_list, text, style)

Bases: object

Class representing an annotation to add to a plot or image.

__init__(type, pt_list, text, style)
crop_pt_list_to_box(input_point_list: list[tuple[float, float]], crop_box: list[tuple, tuple]) list

Crop a list of points to a specified box.

Parameters:
  • input_point_list (list) – List of points, where each point is a [x, y] pair.

  • crop_box (list, optional) – Box defined by the corners [xy_min, xy_max]. If None, no cropping is performed.

Returns:

A new list of the points that are within the crop box, or the input list if crop_box is None.

Return type:

list

image_draw(image, crop_box=None)

Add annotations to the image, modifying the image.

Uses OpenCV drawing routines. For documentation, see:

https://docs.opencv.org/4.5.3/d3/d96/tutorial_basic_geometric_drawing.html https://docs.opencv.org/4.5.3/d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670 https://docs.opencv.org/4.5.3/d6/d6e/group__imgproc__draw.html#gaf076ef45de481ac96e0ab3dc2c29a777

Here is some demonstration code:

cv.circle(img, ( 700,1500), 100, (255,0,0), 10, 8) # Blue cv.circle(img, (1000,1500), 100, (0,255,0), -1, 8) # Green (filled) cv.circle(img, (1300,1500), 100, (0,0,255), 30, 8) # Red cv.line(img, ( 700,1500), ( 900,1700), (255,255,0), 10, 8) # Cyan cv.line(img, (1000,1500), (1200, -50), (255,0,255), 10, 8) # Magenta (cropped) cv.line(img, (1300,1500), (1500,7000), (0,255,255), 10, 8) # Yellow (cropped) example_xy_list = [ [200,100], [800,150], [1800,400], [300,900] ] example_xy_array = np.array(example_xy_list, np.int32) example_xy_reshaped_array = example_xy_array.reshape((-1, 1, 2)) cv.fillPoly(img, [example_xy_reshaped_array], (255,0,255), 8) # Magenta (filled) cv.polylines(img, [example_xy_reshaped_array*2], True, (255,255,0), 8) # Cyan (outline, closed) cv.polylines(img, [example_xy_reshaped_array*3], False, (255,0,0), 8) # Blue (outline, not closed) print(‘In demo_routine(), saving annotated image file: ‘, img_dir_body_ext) cv.imwrite(img_dir_body_ext, img)

opencv_color(plot_color)

OpenCV colors are (B,G,R) tuples.

opencv_font(plot_fontstyle)

See https://codeyarns.com/tech/2015-03-11-fonts-in-opencv.html

opencv_font_line_type()

See https://docs.opencv.org/4.5.3/d6/d6e/group__imgproc__draw.html#gaf076ef45de481ac96e0ab3dc2c29a777

opencv_font_scale(plot_fontsize)

OpenCV font thickness must be an integer.

opencv_font_thickness(plot_fontweight)

OpenCV font thickness must be an integer.

opencv_line_type()

See https://docs.opencv.org/4.5.3/d6/d6e/group__imgproc__draw.html#gaf076ef45de481ac96e0ab3dc2c29a777

opencv_origin(text, int_pt, font=0, font_scale=1.0, font_thickness=1, plot_horizontalalignment: str | None = None, plot_verticalalignment: str | None = None)

Compute the origin point for OpenCV text drawing.

Parameters:
  • text (str) – The text to be drawn.

  • int_pt (list[int, int]) – The input point (x, y) where the text will be drawn.

  • font (int, optional) – The OpenCV font type. Default 0.

  • font_scale (float, optional) – The font scale. Default 1.0.

  • font_thickness (int, optional) – The font thickness. Default 1.

  • plot_horizontalalignment (str, optional) – The horizontal alignment of the text. Can be ‘left’, ‘center’, or ‘right’. Default “center”.

  • plot_verticalalignment (str, optional) – The vertical alignment of the text. Can be ‘bottom’, ‘center’, or ‘top’. Default “center”.

Returns:

The origin point (x, y) for OpenCV text drawing.

Return type:

list[int, int]

Notes

This method uses OpenCV’s getTextSize function to determine the size of the text, and then computes the origin point based on the input point and the text alignment.

plot(crop_box=None)

Plot the annotation. assumes that desired plot is active.

point_is_in_crop_box(point: list, crop_box: list) bool

Check if a point is within a specified box.

Parameters:
  • point (list) – Point defined by a [x, y] pair.

  • crop_box (list, optional) – Box defined by the corners [xy_min, xy_max]. If None, then return True.

Returns:

True if the point is within the crop box, False otherwise.

Return type:

bool

opencsp.common.lib.render.PlotAnnotation.data_curve_annotation(point_list, color='b', linewidth=1)

A data curve with data points identified.

opencsp.common.lib.render.PlotAnnotation.marker_annotation(point_list, marker='o', color='b', markersize=3)

A data curve with data points identified.

opencsp.common.lib.render.PlotAnnotation.outline_annotation(point_list, color='k', linewidth=1)

Outlines of physical objects.

opencsp.common.lib.render.PlotAnnotation.text_annotation(point, text_str, fontsize='medium', color='b', horizontalalignment='center', verticalalignment='center')

A text annotation.

class opencsp.common.lib.render.lib.AbstractPlotHandler.AbstractPlotHandler(*vargs, **kwargs)

Bases: ABC

Class to automatically track and close matplotlib plot windows.

Note that even through this will ensure that all registered plots are closed when the this instance is destructed, it is almost always better to close the figure as soon as it’s not needed any more via the close() method.

Implementing classes need to make calls to: - super().__init__() - super().__del__() - self._register_plot(fig)

__init__(*vargs, **kwargs)
close()

Closes all registered plots.

This method frees up system resources associated with the plots.

General Plotting Support

See also image_plot.py, pandas_plot.py, View3d.py, PlotAnnotation.py.

opencsp.common.lib.render.general_plot.add_xy_list_to_plot(figure_record, xy_list, style, label=None)

Adds a list of (x, y) points to an existing plot.

This function appends additional data points to an already created plot. It updates the figure with the new data and displays the updated plot.

Parameters:
  • figure_record (object) – The figure to which the new data will be added.

  • xy_list (list[tuple[float, float]]) – A list of (x, y) tuples representing the data points to add to the plot.

  • style (RenderControlPointSeq) – An object defining the style of the plot (line style, color, etc.).

  • label (str | None, optional) – The label for the legend. If None, no label is shown. Defaults to None.

Returns:

The updated figure record object containing information about the modified figure.

Return type:

object

opencsp.common.lib.render.general_plot.plot_xy_list(figure_control, xy_list, title, style, label, x_axis_label, y_axis_label, x_axis_grid=False, y_axis_grid=False, legend=True)

Plots a list of (x, y) points on a 2D graph.

This function creates a 2D plot using the provided data points, styles, and labels. It sets up the figure, plots the data, and displays the plot.

Parameters:
  • figure_control (object) – Control object for managing the figure.

  • xy_list (list[tuple[float, float]]) – A list of (x, y) tuples representing the data points to plot.

  • title (str) – The title of the plot.

  • style (RenderControlPointSeq) – An object defining the style of the plot (line style, color, etc.).

  • label (str | None) – The label for the legend. If None, no label is shown.

  • x_axis_label (str | None) – The label for the x-axis. If None, no label is shown.

  • y_axis_label (str | None) – The label for the y-axis. If None, no label is shown.

  • x_axis_grid (bool, optional) – If True, vertical grid lines are drawn on the x-axis. Defaults to False.

  • y_axis_grid (bool, optional) – If True, horizontal grid lines are drawn on the y-axis. Defaults to False.

  • legend (bool, optional) – If True, the plot legend is displayed. Defaults to True.

Returns:

A figure record object containing information about the created figure.

Return type:

object

Image plotting, with annotations.

opencsp.common.lib.render.image_plot.plot_image_figure(image, draw_image=True, rgb=True, title=None, annotation_list=None, crop_box=None, context_str=None, save=True, output_dir=None, output_body='image', dpi=200, include_figure_idx_in_filename=True)

Plots an image with optional annotations and saves it to disk.

This is meant to be a simplistic version of a plot. For a more standard OpenCSP plot, please use something similar to the example in figure_management.setup_figure().

This function creates a figure to display an image, optionally drawing annotations and saving the figure to a specified directory. The image can be displayed in either RGB or BGR format.

Parameters:
  • image (np.ndarray) – The image to be plotted, represented as a NumPy array.

  • draw_image (bool, optional) – If True, the image will be displayed in the figure. Defaults to True.

  • rgb (bool, optional) – If True, the image is assumed to be in RGB format. If False, it is assumed to be in BGR format. Defaults to True.

  • title (str | None, optional) – The title to display at the top of the figure. Defaults to None.

  • annotation_list (list, optional) – A list of annotations to draw on the plot. Each annotation should have a plot method. Defaults to None.

  • crop_box (list[list[int]] | None, optional) – A list defining the crop box as [[x_min, y_min], [x_max, y_max]]. If None, no cropping is applied. Defaults to None.

  • context_str (str | None, optional) – An explanatory string to include in the status output line. Defaults to None.

  • save (bool, optional) – If True, the figure will be saved to disk. Defaults to True.

  • output_dir (str | None, optional) – The directory where the figure will be saved. Defaults to None.

  • output_body (str, optional) – The base filename for the saved figure. Defaults to ‘image’.

  • dpi (int, optional) – The resolution (dots per inch) for the saved figure. Defaults to 200.

  • include_figure_idx_in_filename (bool, optional) – If True, the figure index will be included in the filename. Defaults to True.

Return type:

None

Raises:

ValueError – If the output directory is not specified when saving the figure.

Plotting Pandas Objects

opencsp.common.lib.render.pandas_plot.dataframe_plot(figure_control, df, title, x_column, y_column_label_styles, x_axis_label, y_axis_label, x_axis_grid=False, y_axis_grid=False, legend=True)

Plots data from a Pandas DataFrame.

This function creates a plot using data from the specified DataFrame, allowing for multiple curves to be plotted based on the provided column specifications. It sets up the figure, plots the data, and displays the plot.

Parameters:
  • figure_control (object) – Control object for managing the figure.

  • df (pd.DataFrame) – The DataFrame containing the data to plot.

  • title (str) – The title of the plot.

  • x_column (str) – The name of the column to use for the horizontal axis.

  • y_column_label_styles (list[list]) – A list of specifications for the data curves to plot. Each specification should be a list containing the column heading, legend label (or None), and point sequence render control.

  • x_axis_label (str | None) – The label for the x-axis. If None, no label is shown.

  • y_axis_label (str | None) – The label for the y-axis. If None, no label is shown.

  • x_axis_grid (bool, optional) – If True, vertical grid lines are drawn on the x-axis. Defaults to False.

  • y_axis_grid (bool, optional) – If True, horizontal grid lines are drawn on the y-axis. Defaults to False.

  • legend (bool, optional) – If True, the plot legend is displayed. Defaults to True.

Returns:

A figure record object containing information about the created figure.

Return type:

object

Raises:

ValueError – If the specified x_column or any y_column in y_column_label_styles does not exist in the DataFrame.

Powerpoint

class opencsp.common.lib.render.PowerpointSlide.PowerpointSlide(slide_control: RenderControlPowerpointSlide, images: list[PowerpointImage] | None = None, texts: list[PowerpointText] | None = None)

Bases: object

Generate a powerpoint slide. Once completed, it should be added to a powerpoint presentation. See RenderControlPowerpointPresentation for an example usage.

Typically the template methods are used to generate a slide instead of instantiating an instance from the class constructor. See template_title(), template_planning(), template_overview(), template_content_simple(), template_content_grid().

__init__(slide_control: RenderControlPowerpointSlide, images: list[PowerpointImage] | None = None, texts: list[PowerpointText] | None = None)

Typically the template methods are used to generate a slide instead of instantiating an instance from the class constructor. See template_title(), template_planning(), template_overview(), template_content_simple(), template_content_grid().

Parameters:
add_image(image: PowerpointImage | Any, fit_or_stretch: str | None = None, index: int = -1)

Add an image to this slide.

If this slide has predefined spaces still available, then fits this image into the first of those spaces. Which space is filled can be overridden by specifying the index value.

Parameters:
  • image (-) – The image to be added. Can be any type that PowerpointImage accepts. At the time of this writing, this includes str, ndarray, Image, and RenderControlFigureRecord.

  • index (-) – The cell index (position) in the template into which to set this image, or -1 for the next available cell. Defaults to -1.

add_text(text: PowerpointText, index: int = -1, replace_or_shift='replace')

Add a copy of the text object to the slide.

Parameters:
  • text (PowerpointText) – The text object to add to the slide.

  • index (int, optional) – The cell index at which to insert the text. If -1, the text is appended as a new cell. If the index is out of range, the text is inserted into the next available slot.

  • replace_or_shift (str, optional) – How to handle existing text at the specified index. Can be “replace” or “shift”. If “replace”, the existing text is replaced with the new text. If “shift”, the existing text and all subsequent texts are shifted one cell down.

Returns:

text – The copy of the text object.

Return type:

PowerpointText

align_text(shape, alignment: PP_PARAGRAPH_ALIGNMENT)

Aligns the text within a shape.

Parameters:
  • shape ([powerpoint shape]) – The shape containing the text to be aligned.

  • alignment (pptx.enum.text.PP_ALIGN) – The alignment to apply to the text.

clean(slide)

Clean the given pptx slide (remove all existing shapes).

clear_tmp_saved_images_files()

Removes the temporary saved image files for this slide. To remove all saved images, use PowerpointImage.clear_tmp_save_all().

clear_tmp_saved_text_files()

Removes the temporary saved text files for this slide. To remove all saved texts, use PowerpointText.clear_tmp_save_all().

format_text(shape, size: int)

Formats the text within a shape by setting the font size.

Parameters:
  • shape ([Powerpoint shape]) – The shape containing the text to be formatted.

  • size (int) – The font size to apply to the text.

free_image_memory()

Releases image data from system RAM by saving this slide’s images to files.

See also PowerpointImage.replace_with_save()

classmethod from_txt_file(file_path_name_ext: str, slide_control: RenderControlPowerpointSlide | None = None)

Deserializes a PowerpointSlide instance from a file previously used with to_txt_file. The newly generated instance is then returned.

get_non_title_texts()

Retrieves a list of all text instances on this slide that are not the title text.

get_title_text()

Retrieves the title text instance associated with this slide, if it exists.

render(presentation, layout, tmp_render_path: str)

Generates a slide, and adds all images and texts to be rendered to the slide. This has the side effect of calling save_and_bake().

save()

Saves images and texts out to temporary files, as necessary.

save_and_bake()

Saves the images and texts to temporary files, as with save().

This also reduces image size and frees them from memory (note that this happens normally, it just happens in render instead).

The temporary files can later be cleared with PowerpointImage.clear_tmp_save_all() and PowerpointText.clear_tmp_save_all().

set_index(slide_index: int)

Sets the index of this slide in the slide deck.

The slide index indicates the ordering of the slides. This method should probably only be called from the slide deck class.

Parameters:

slide_index (int) – The new index for this slide.

Notes

If the new index is the same as the current index, this method does nothing.

set_title(title: str | PowerpointText)

Sets or replaces the title of this slide.

classmethod template_content_grid(nrows=2, ncols=2, slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide

Create an information-containing slide, split into a ncols by nrows grid.

Images or text boxes can be added to specific points in the grid by specifying the index, which proceeds from left to right, top to bottom. For example, in a 3x2 grid (3 columns, 2 rows), the cell indicies would be:

0 | 1 | 2
3 | 4 | 5

Any space that an image isn’t assigned to is assumed to be reserved to a text box.

classmethod template_content_simple(slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide

Create an information-containing slide with a bulleted description on the left.

classmethod template_overview(slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide

Create an overview slide.

classmethod template_planning(slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide

Create a planning slide.

classmethod template_title(title: str, authors: str, slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide

Create a title slide for the first slide in a slide deck.

Parameters:
  • title (str) – The title to be displayed.

  • authors (str) – The authors of the slide deck and any contained work.

  • slide_control (RenderControlPowerpointSlide, optional) – The slide control. Uses a default if not set.

Returns:

The new title slide.

Return type:

PowerpointSlide

to_txt_file(file_path_name_ext: str)

Serializes this instance to files. This instance can then be reconstructed with the from_txt_file() method.

Saves the images and texts for this slide in the given path and saves the references to them in the given file.

class opencsp.common.lib.render.lib.PowerpointShape.PowerpointShape(cell_dims: tuple[float, float, float, float] | None = None, code_location: str | None = None)

Bases: object

A class that supplements the shape class from python-pptx, facilitating custom layouts.

__init__(cell_dims: tuple[float, float, float, float] | None = None, code_location: str | None = None)

Initializes the PowerpointShape with specified dimensions and code location.

Parameters:
  • cell_dims (tuple[float, float, float, float], optional) – The left, right, top, and bottom dimensions of the confining area of this shape (in inches). Defaults to None.

  • code_location (str, optional) – The location in the code where the instance was created. Defaults to None.

cell_dims_pptx()

Returns the PowerPoint-style inches that bound this shape (left, top, width, height).

Returns:

A list of the dimensions in PowerPoint inches.

Return type:

list[int]

class opencsp.common.lib.render.lib.PowerpointText.PowerpointText(val: str | None = None, dims: tuple[float, float, float, float] = (1.0, 1.0, 1.0, 1.0), cell_dims: tuple[float, float, float, float] | None = None, is_title=False, parent_slide=None)

Bases: PowerpointShape

A class representing text elements in a PowerPoint presentation.

This class allows for the creation, manipulation, and storage of text elements that can be added to PowerPoint slides. It supports saving to and loading from text files for persistence.

dims

The dimensions of the text element in the PowerPoint slide.

Type:

tuple[float, float, float, float]

is_title

A flag indicating whether this text element is a title.

Type:

bool

parent_slide

The parent slide to which this text element belongs.

Type:

PowerpointSlide

__init__(val: str | None = None, dims: tuple[float, float, float, float] = (1.0, 1.0, 1.0, 1.0), cell_dims: tuple[float, float, float, float] | None = None, is_title=False, parent_slide=None)

Initializes the PowerpointText instance.

Parameters:
  • val (str, optional) – The text value of the PowerPoint text element. Defaults to None.

  • dims (tuple[float, float, float, float], optional) – The dimensions of the text element (left, top, width, height). Defaults to None.

  • cell_dims (tuple[float, float, float, float], optional) – The dimensions of the cell containing the text. Defaults to None.

  • is_title (bool, optional) – A flag indicating whether this text element is a title. Defaults to False.

  • parent_slide (PowerpointSlide, optional) – The parent slide to which this text element belongs. Defaults to None.

clear_tmp_save()

Clears the temporary save of the text element.

classmethod clear_tmp_save_all()

Clears all temporary saves of text elements.

compute_and_assign_height(font_pnt: int)

Attempts to calculate a height, in inches, for this text based on the given font size.

static compute_height(font_pnt: int, nlines: int = 1)

Attempts to calculate a height, in inches, based on the given font size.

dims_pptx()

Returns the powerpoint-style inches to place this text at (left, top, width, height).

classmethod from_txt_file(path_name_ext: str)

Given the text file from get_text_file_path(), this reconstructs a PowerpointText instance.

get_text_file_path() str

Gets the file path of the saved text element.

Returns:

path – The file path of the saved text element, or None if it is not saved.

Return type:

str

get_val() str | None

Gets the value of the text element.

Returns:

val – The value of the text element, or None if it has no value.

Return type:

str | None

has_dims()

Checks if the text element has dimensions (top, left, width, height).

Returns:

has_dims – True if the text element has dimensions, False otherwise.

Return type:

bool

has_val()

Checks if the text element has a value.

Returns:

has_value – True if the text element has a value, False otherwise.

Return type:

bool

is_saved_to_file()

Checks if the text element has been serialized and saved to a file.

Returns:

is_saved – True if the text element is saved to a file, False otherwise.

Return type:

bool

save()

Saves this instance to a text file, as necessary. It can then be reconstructed by calling from_text_file() with the returned path_name_ext.

Returns:

ppt_path_name_ext (str|None): The path to the serialized instance. None if saving failed.

set_val(val: str)

Sets the value of the text element.

Parameters:

val (str) – The new value of the text element.

update_save_path(save_path: str)

Updates the save file path of the text element. Moves the existing save file if there is one.

Parameters:

save_path (str) – The new save path of the text element.