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

Builds a colormap that transitions between this color and the specified next colors, given a value between 0 and 1.

Parameters:

next_colors (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).

Returns:

A colormap object that can be used for rendering.

Return type:

matplotlib.colors.Colormap

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

Converts various representations to a Color instance.

Parameters:

val (Color | str | tuple | None) – The value to convert, which can be a Color instance, a string, or a tuple of RGB values.

Returns:

A Color instance corresponding to the input value.

Return type:

Color

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

Creates a Color instance from a hexadecimal color string.

Parameters:
  • hexval (str) – The hexadecimal color string (e.g., “#RRGGBB”).

  • name (str) – A descriptive name for the color.

  • short_name (str) – A shorthand name for the color.

Returns:

A Color instance with the RGB values extracted from the hexadecimal string.

Return type:

Color

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

Creates a Color instance from HSV values.

Parameters:
  • hue (float) – The hue component in the HSV color space (0-1).

  • saturation (float) – The saturation component in the HSV color space (0-1).

  • value (float) – The value (brightness) component in the HSV color space (0-1).

  • name (str) – A descriptive name for the color.

  • short_name (str) – A shorthand name for the color.

Returns:

A Color instance with the RGB values converted from the HSV values.

Return type:

Color

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

Creates a Color instance from 8-bit RGB values.

Parameters:
  • red (int) – The red component in the RGB color space (0-255).

  • green (int) – The green component in the RGB color space (0-255).

  • blue (int) – The blue component in the RGB color space (0-255).

  • name (str) – A descriptive name for the color.

  • short_name (str) – A shorthand name for the color.

Returns:

A Color instance with the specified RGB values.

Return type:

Color

classmethod from_str(sval='b') Color

Creates a Color instance from a string representation.

Parameters:

sval (str, optional) – The string representation of the color (e.g., ‘b’ for blue). Defaults to ‘b’.

Returns:

A Color instance corresponding to the specified string representation.

Return type:

Color

rgb() tuple[float, float, float]

Returns the RGB values of the color.

Returns:

A tuple containing the RGB values of the color, each in the range [0, 1].

Return type:

tuple[float, float, float]

rgb_255() tuple[int, int, int]

Returns the RGB values of the color in the range [0, 255].

Returns:

A tuple containing the RGB values of the color, each in the range [0, 255].

Return type:

tuple[int, int, int]

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

Returns the RGBA values of the color.

Parameters:

alpha (float, optional) – The alpha (transparency) value of the color. Defaults to 1.0 (fully opaque).

Returns:

A tuple containing the RGBA values of the color, each in the range [0, 1].

Return type:

tuple[float, float, float, float]

to_hex() str

Converts the color to a hexadecimal string representation.

Returns:

The hexadecimal string representation of the color (e.g., “#RRGGBB”).

Return type:

str

to_hsv() tuple[float, float, float]

Converts the RGB color to HSV representation.

Returns:

A tuple containing the HSV values of the color, each in the range [0, 1].

Return type:

tuple[float, float, float]

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

Returns a Color instance representing black.

Returns:

A Color instance with RGB values (0.0, 0.0, 0.0).

Return type:

Color

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

Returns a Color instance representing blue.

Returns:

A Color instance with RGB values (0.0, 0.0, 1.0).

Return type:

Color

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

Creates a colormap that transitions between a sequence of colors.

This function takes a sequence of Color instances and builds a colormap that smoothly transitions between the specified colors. The first color in the sequence is used as the starting point, and the subsequent colors are used to define the transitions.

Parameters:

colors_sequence (Color) – A variable number of Color instances that define the colors to be included in the colormap. The first color is the starting color, and the subsequent colors define the transitions.

Returns:

A colormap object that can be used for rendering.

Return type:

matplotlib.colors.Colormap

Raises:

ValueError – If no colors are provided in the sequence.

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

Returns a Color instance representing cyan.

Returns:

A Color instance with RGB values (0.0, 1.0, 1.0).

Return type:

Color

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

Returns a Color instance representing dark grey.

Returns:

A Color instance with RGB values (0.25, 0.25, 0.25).

Return type:

Color

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

Returns a Color instance representing green.

Returns:

A Color instance with RGB values (0.0, 1.0, 0.0).

Return type:

Color

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

Returns a Color instance representing grey.

Returns:

A Color instance with RGB values (0.5, 0.5, 0.5).

Return type:

Color

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

Returns a Color instance representing light grey.

Returns:

A Color instance with RGB values (0.75, 0.75, 0.75).

Return type:

Color

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

Returns a Color instance representing magenta.

Returns:

A Color instance with RGB values (1.0, 0.0, 1.0).

Return type:

Color

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

Returns a Color instance representing red.

Returns:

A Color instance with RGB values (1.0, 0.0, 0.0).

Return type:

Color

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

Returns a Color instance representing white.

Returns:

A Color instance with RGB values (1.0, 1.0, 1.0).

Return type:

Color

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

Returns a Color instance representing yellow.

Returns:

A Color instance with RGB values (1.0, 1.0, 0.0).

Return type:

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=None, parent=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=None, parent=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: ndarray, x_range: tuple[float, float] | None = None, y_range: tuple[float, float] | None = None, scale=100.0, style: RenderControlHeatmap | None = None, colorbar_unimplemented=False)
draw_hist2d(h, xedges, yedges, *args, colorbar=False, **kwargs)
draw_image(path_or_array: str | ndarray, 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)

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 (str | np.ndarray) – 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.

draw_p_list(input_p_list, style=<opencsp.common.lib.render_control.RenderControlPointSeq.RenderControlPointSeq object>, label=None)
draw_pq(pq: tuple[list, list], style=<opencsp.common.lib.render_control.RenderControlPointSeq.RenderControlPointSeq object>, 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=<opencsp.common.lib.render_control.RenderControlPointSeq.RenderControlPointSeq object>, label=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_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)
draw_xyzdxyz_list(input_xyzdxyz_list: list[list[list, list]], close: bool = False, style: ~opencsp.common.lib.render_control.RenderControlPointSeq.RenderControlPointSeq = <opencsp.common.lib.render_control.RenderControlPointSeq.RenderControlPointSeq object>, label: str | None = 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
limit_suffix()
on_key_press(event: KeyEvent, draw_func: Callable)
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)
pqw2xyz(pqw)
quiver(X: ndarray, Y: ndarray, Z: ndarray, U: ndarray, V: ndarray, W: ndarray, length: float = 0) None
register_event_handler(event_type: str, callback: Callable[[Event], None])
save(output_dir, output_figure_body, format='png', dpi=300) 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, grid=True)
xyz2pq(xyz)
xyz2pqw(xyz)
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)

Bases: PowerpointShape

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

__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)

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

Parameters:
  • image (str | np.ndarray | 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, or None to fill in one of the cells from the template slides. Defaults to None.

  • dims – The left, top, width, height of the bounds for this shape, or None to fill in one of the cells from the template slides. 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 to fit the entire cell, False to fit within cell. Most useful with template slides. Default false.

append_tmp_path(append_dir: str)
classmethod append_tmp_path_all(append_dir: str)
clear_tmp_save()

Remove the temporarily saved file from this image saving to said file.

classmethod clear_tmp_save_all()

Remove all temporarily saved files from PowerpointImage.save()

dims_pptx()

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

fit_to_cell_dimensions(cell_dims: tuple[float, float, float, float])
classmethod from_txt_file(path_name_ext: str)

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

get_saved_path() str

Get the path+name+ext to the saved file version of the image content. Calls save() as necessary.

get_size(force_reload=False)

Get the width and height of this image in pixels. Calls save() as necessary.

get_text_file_path() str

Get the path to the PowerpointImage metadata for the image at get_saved_path().

See also:

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

Get the image assigned to this instance. What you probably actually want is get_saved_path().

has_dims()
has_val()
is_saved_to_file()
reduce_size(reduced_image_size_scale: float = -1)

If the given image is significantly bigger than its rendered size, then resize the image to take up less disk space. This will save the image to disk first if necessary.

replace_with_save()

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

We do this mainly to save on memory by releasing images.

save()

Saves this image, as necessary, to an image file and a text file. It can then be reconstructed by calling from_text_file() with the returned path+name+ext.

Returns:

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

set_save_path(save_path: str)
set_val(image: str | ndarray | Image | RenderControlFigureRecord)
stretch_to_cell_dimensions(cell_dims: tuple[float, float, float, float])
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_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_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.

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.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

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)
classmethod VideoExtractor(src_video_dir_name_ext: str, dst_frames_dir: str, dst_example_frames_dir: str, frame_control: RenderControlVideoFrames)
classmethod VideoInspector(src_video_dir_name_ext: str)
classmethod VideoMerger(src_videos_path, src_videos_ext, dst_video_dir_name_ext)
classmethod VideoTransformer(src_video_dir_name_ext: str, dst_video_dir_name_ext: str, video_control: RenderControlVideo)
__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, crop_box)
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, font_scale, font_thickness, plot_horizontalalignment, plot_verticalalignment)
plot(crop_box=None)

Plot the annotation. assumes that desired plot is active.

point_is_in_crop_box(point, crop_box)
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()

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 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.

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

Generate a powerpoint slide. Once completed, it should be added to a powerpoint presentation.

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')
align_text(shape, alignment: PP_PARAGRAPH_ALIGNMENT)
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)
free_image_memory()
classmethod from_txt_file(file_path_name_ext: str, slide_control: RenderControlPowerpointSlide | None = None)
get_non_title_texts()
get_title_text()
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).

set_index(slide_index: int)
set_title(title: str | PowerpointText)
classmethod template_content_grid(nrows=2, ncols=2, slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide

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

Information-containing slide with a bulleted description on the left.

classmethod template_overview(slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide
classmethod template_planning(slide_control: RenderControlPowerpointSlide | None = None) PowerpointSlide
classmethod template_title(title: str, authors: str, slide_control: RenderControlPowerpointSlide) PowerpointSlide
to_txt_file(file_path_name_ext: str)

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] | None = None, 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] | None = None, 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.

append_tmp_path(append_dir: str)
classmethod append_tmp_path_all(append_dir: str)
clear_tmp_save()
classmethod clear_tmp_save_all()
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
get_val() str | None
has_dims()
has_val()
is_saved_to_file()
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_save_path(save_path: str)
set_val(val: str)