losalamos.figures#

SVG and raster figure handling for export pipelines.

Provides classes for loading, manipulating, and exporting figures in SVG, PDF, PNG, and JPEG formats using Inkscape as the rendering backend.

Classes

Figure([name, alias])

Base class for figure objects.

FigureSVG([name, alias])

SVG figure with layer control and multi-format export.

class losalamos.figures.Figure(name='MyFig', alias='Fig')[source]#

Bases: DataSet

Base class for figure objects.

Extends DataSet with image utility methods for scaling, thumbnail generation, and format conversion.

load_data(file_data)[source]#

Load data from file.

Parameters:

file_data (str) – file path to data.

static scale_image(file_input, file_output, scale_factor, dpi=300)[source]#

Scale an image by a numerical factor while maintaining its original aspect ratio.

Parameters:
  • file_input (str) – Path to the source image file.

  • file_output (str) – Path where the scaled image will be saved.

  • scale_factor (float) – Multiplier for the image dimensions (e.g., 0.5 for half size).

  • dpi (int) – Resolution in dots per inch for the output file metadata. Default value = 300

Returns:

No value is returned.

Return type:

None

Note

The resizing process utilizes the Image.Resampling.LANCZOS filter to ensure high-quality downsampling or upsampling. The output is saved with a fixed quality compression of 95.

static make_thumbnail(file_input, file_output, size=(512, 512), figure_ratio=None, mode='crop', dpi=300, quality=85, background=(255, 255, 255))[source]#

Generate a lightweight JPEG thumbnail from an input image with resizing options.

Parameters:
  • file_input (str) – Path to the source image file.

  • file_output (str) – Path where the generated thumbnail will be saved.

  • size (tuple) – Target dimensions for the output image. Default value = (512, 512)

  • figure_ratio (tuple) – [optional] Aspect ratio used to calculate target height from width.

  • mode (str) – Resizing strategy, either crop to fill dimensions or fit to pad. Default value = crop

  • dpi (int) – Resolution in dots per inch for the output file. Default value = 300

  • quality (int) – JPEG compression quality from 1 to 100. Default value = 85

  • background (tuple) – RGB color used for padding when mode is fit. Default value = (255, 255, 255)

Returns:

No value is returned.

Return type:

None

Note

The function automatically converts non-compatible image modes to RGB to ensure JPEG compatibility. If figure_ratio is provided as (width, height), it overrides the height specified in the size parameter.

static image_to_jpeg(file_input, file_output, quality=95, dpi=300)[source]#

Convert an image file to JPEG format with specified quality and resolution.

Parameters:
  • file_input (str) – Path to the input image file.

  • file_output (str) – Path where the output JPEG will be saved.

  • quality (int) – Compression quality from 1 to 100. Default value = 95

  • dpi (int) – Resolution in dots per inch. Default value = 300

Returns:

None

Return type:

NoneType

class losalamos.figures.FigureSVG(name='MySVG', alias='SVG')[source]#

Bases: Figure

SVG figure with layer control and multi-format export.

Loads an Inkscape SVG file and exposes methods to manipulate layer visibility and export the drawing to SVG, PDF, PNG, or JPEG via Inkscape subprocess calls.

Parameters:
  • name (str) – Internal object name. Default value = MySVG

  • alias (str) – Short display alias. Default value = SVG

Note

All export methods (to_svg, to_pdf, to_image) operate on a temporary copy of the source file, leaving the original untouched.

Warning

Requires inkscape to be installed and available in the system PATH.

load_data(file_data)[source]#

Load and parse SVG XML data from a file path into the object instance.

Parameters:

file_data (str) – The file system path pointing to the source SVG data.

Returns:

No value is returned.

Return type:

None

Important

This method converts the input path to an absolute path and utilizes an etree.XMLParser with huge_tree enabled to handle large datasets. It populates the tree and data attributes before triggering an internal update call.

save()[source]#

Serializes the current XML tree and writes it to the local file system.

Returns:

Always returns None

Return type:

None

export(folder, filename, data_suffix=None)[source]#

Saves the current SVG data to a specific directory with an optional filename suffix.

Parameters:
  • folder (str) – The destination directory path

  • filename (str) – The base name of the output file

  • data_suffix (str) – [optional] An additional string appended to the filename

Returns:

Always returns None

Return type:

None

Note

This method temporarily overrides the internal file_data path to execute the save operation before restoring the original path.

hide_layer(label='frames')[source]#

Modifies the style attribute of a specific layer to make it invisible.

Parameters:

label (str) – The Inkscape label of the layer to hide. Default value = frames

Returns:

Always returns None

Return type:

None

hide_layers(labels)[source]#

Hide multiple layers based on a list of provided labels.

Parameters:

labels (list) – A list of layer labels to be hidden.

Returns:

None

Return type:

NoneType

show_layer(label='frames')[source]#

Modifies the style attribute of a specific layer to make it visible.

Parameters:

label (str) – The Inkscape label of the layer to display. Default value = frames

Returns:

Always returns None

Return type:

None

show_layers(labels, inclusive=True)[source]#

Show specified layers and optionally hide all others.

Parameters:
  • labels (list) – A list of layer labels to be made visible.

  • inclusive (bool) – Determines if other layers stay visible or are hidden. Default value = True

Returns:

None

Return type:

NoneType

Note

If inclusive is set to True, the specified layers are made visible without affecting others. If False, the method performs a “show only” operation by hiding any layer not present in the labels list.

get_layers()[source]#

Return a dictionary of top-level Inkscape layers indexed by their label.

Returns:

Dictionary mapping layer labels to lxml Elements

Return type:

dict[str, etree.Element]

Note

Only <g> elements that are direct children of the root <svg> element and have inkscape:groupmode=”layer” are considered.

get_layers_labels()[source]#

Return the list of layers labels

get_property(element, key)[source]#

Get a visual or geometric property from an SVG element.

Searches the element’s style attribute first, then falls back to bare XML attributes.

Parameters:
  • element (etree.Element) – The lxml SVG element to read.

  • key (str) – Property name (e.g. 'fill', 'width', 'opacity').

Returns:

The property value, or None if not found in either location.

Return type:

str or None

See also

set_property()

get_text(element)[source]#

Get the text content of a SVG text element.

Reads from the first <tspan> descendant if present, since Inkscape stores the actual string there rather than directly on the <text> node. Falls back to the element’s own text if no tspan is found.

Parameters:

element (etree.Element) – The lxml SVG text element to read.

Returns:

The text content, or an empty string if none is found.

Return type:

str

See also

set_text()

get_text_lines(element)[source]#

Return all text lines from a multi-line SVG text element.

Each <tspan sodipodi:role='line'> is treated as one line.

Parameters:

element (etree.Element) – The lxml SVG text element to read.

Returns:

List of strings, one per tspan.

Return type:

list[str]

set_page_opacity(opacity=1.0)[source]#

Set the Inkscape page background opacity.

Parameters:

opacity (float) – Opacity value in range [0.0, 1.0] (1=opaque)

set_page_color(color='#ffffff')[source]#

Set the Inkscape page background color.

Parameters:

color (str) – Hex color string (e.g. ‘#ffffff’)

get_layer_elements(label, drawable_only=True)[source]#

Return drawable SVG elements from a layer, indexed by element ID.

Parameters:
  • label – Inkscape layer label

  • drawable_only – Exclude non-drawable tags (image, defs, etc.)

Returns:

dict[str, dict]

set_property(element, key, value)[source]#

Set a visual or geometric property on an SVG element.

Searches for the key in the element’s style attribute first, then in bare XML attributes. Writes to whichever location already holds the key, falling back to the style string if the key is not found in either. If the key exists in both locations, the bare attribute is removed and the style string is kept as the single source of truth.

Parameters:
  • element (etree.Element) – The lxml SVG element to modify.

  • key (str) – Property name (e.g. 'fill', 'width', 'opacity').

  • value (str) – New value to assign.

Returns:

None

Return type:

NoneType

Note

Mutations are applied in place on the lxml tree. A subsequent call to save() or export() will persist the changes to disk.

Warning

When the same property exists in both the style string and as a bare XML attribute, the bare attribute is silently removed to resolve the ambiguity. This normalisation is intentional but changes the element structure beyond the requested property.

set_color(element, fill=None, stroke=None)[source]#

Set fill and/or stroke color of an SVG element.

Parameters:
  • element – lxml SVG element

  • fill – Fill color (e.g. ‘#00ff00’) or None

  • stroke – Stroke color or None

set_font(element, font_family, variant=None)[source]#

Set the font family on a text element and all its <tspan> descendants.

Updates both font-family and -inkscape-font-specification to keep Inkscape’s internal font state consistent with the rendered output. The method iterates over the element itself and all child nodes, applying changes only to <text> and <tspan> tags.

Parameters:
  • element (etree.Element) – The lxml SVG text element to modify.

  • font_family (str) – Target font family name (e.g. 'Arial', 'Georgia').

  • variant (str or None) – Font variant to apply (e.g. 'Normal', 'Bold', 'Italic'). If None, the variant is read from the existing -inkscape-font-specification of each node and preserved individually, so mixed variants within the same text element are handled correctly. Default value = None

Returns:

None

Return type:

NoneType

Note

When variant is None and no -inkscape-font-specification is present on a node, the variant defaults to 'Normal'.

See also

set_property(), _extract_variant()

set_text(element, content)[source]#

Set the text content of a SVG text element.

Writes to the first <tspan> descendant if present, since Inkscape stores the actual string there rather than directly on the <text> node. Falls back to writing on the element itself if no tspan is found.

Parameters:
  • element (etree.Element) – The lxml SVG text element to modify.

  • content (str) – The new text string.

Returns:

None

Return type:

NoneType

set_font_layers(font_family, variant=None, layers=None)[source]#

Set the font family on all text elements across specified layers.

Scans every specified layer in the document and applies set_font() to each <text> element found, preserving individual node variants unless variant is explicitly provided.

Parameters:
  • font_family (str) – Target font family name (e.g. 'Arial', 'Georgia').

  • variant (str or None) – Font variant to apply (e.g. 'Normal', 'Bold', 'Italic'). If None, the existing variant of each node is preserved. Default value = None

  • layers (list[str] or None) – List of layer labels to process. If None, all layers in the document are scanned. Default value = None

Returns:

None

Return type:

NoneType

rename_layer(label, new_label)[source]#

Rename an Inkscape layer by updating its label attribute.

Parameters:
  • label (str) – Current label of the layer to rename.

  • new_label (str) – New label to assign to the layer.

Returns:

None

Return type:

NoneType

Raises:

ValueError – If no layer with the given label is found.

Note

Only the inkscape:label attribute is updated. The element id attribute is left unchanged as it may be referenced elsewhere in the document.

rename_element_id(old_id, new_id)[source]#

Rename an element ID and update all references to it within the document.

Updates the id attribute on the target element and scans the entire SVG tree for cross-references (clip-path, mask, xlink:href, href) that point to the old ID, replacing them with the new one.

Parameters:
  • old_id (str) – Current ID of the element to rename.

  • new_id (str) – New ID to assign.

Returns:

None

Return type:

NoneType

Raises:

ValueError – If no element with old_id is found in the document.

Note

This method is required when changing the target of the crop_id parameter in to_image(), to_pdf(), and to_svg(), since Inkscape’s --export-id flag resolves elements by their id attribute.

Warning

ID uniqueness is not enforced by this method. Passing a new_id that already exists in the document will produce duplicate IDs, which is invalid SVG and may cause undefined behaviour in Inkscape and browsers.

rename_element_label(old_label, new_label, tag=None)[source]#

Rename an element’s inkscape:label attribute within the document.

Searches the entire SVG tree for the first element whose inkscape:label matches old_label and updates it to new_label. Optionally restricts the search to a specific SVG tag name.

Parameters:
  • old_label (str) – Current inkscape:label value to find.

  • new_label (str) – New label value to assign.

  • tag (str or None) – [optional] Local tag name to restrict the search (e.g. 'g', 'rect', 'text'). If None, all element types are searched. Default value = None

Returns:

None

Return type:

NoneType

Raises:

ValueError – If no element with the given old_label is found.

Note

Unlike rename_layer(), which operates only on top-level layer <g> elements, this method searches the entire document tree and works on any element type.

embed(file, layer, group, overwrite=False)[source]#

Embed an external SVG file as a new group, creating the target layer if it does not already exist.

The entire content of file is wrapped in a single <g id=group> (itself wrapping a nested <svg> that preserves the source’s own viewBox/width/height, keeping its <defs> self-contained and immune to id collisions), then appended to the named layer. If the layer does not exist, it is created as an empty Inkscape layer first. If a group with the given id already exists anywhere in the document, the call raises unless overwrite=True.

Parameters:
  • file (str or pathlib.Path) – Path to the external SVG file to embed (e.g. a matplotlib-exported plot).

  • layer (str) – Label of the layer to embed into. Created if absent.

  • group (str) – id to assign to the embedded group. Used on re-runs to find and replace this same group.

  • overwrite (bool) – If False (default), raises when a group with this id already exists, to avoid silently clobbering existing content. Set True to replace it in place.

Returns:

None

Return type:

NoneType

Raises:
  • FileNotFoundError – If file does not exist.

  • ValueError – If group already exists and overwrite=False.

Note

This only updates the in-memory tree. Call save() to persist changes to disk.

to_image(file_output=None, dpi=300, crop_id=None, hide_layers=None, show_layers=None, show_inclusive=True, to_jpeg=False, remove_png=True)[source]#

Export the current drawing as an image file, optionally adjusting layers and format.

Parameters:
  • file_output (str or pathlib.Path) – [optional] The destination path for the exported image. If None, it defaults to the source file name.

  • dpi (int) – Dots per inch for the export resolution. Default value = 300

  • crop_id (str) – [optional] The specific object ID to crop instead of the whole page.

  • hide_layers (list) – [optional] List of layer labels to set to hidden before export.

  • show_layers (list) – [optional] List of layer labels to set to visible before export.

  • show_inclusive (bool) – Whether to show layers inclusively when using show_layers. Default value = True

  • to_jpeg (bool) – Convert the final output from PNG to JPEG format. Default value = False

  • remove_png (bool) – Delete the intermediate PNG file if to_jpeg is True. Default value = True

Returns:

The path to the generated image file.

Return type:

pathlib.Path

Warning

This method requires inkscape to be installed and available in the system PATH.

Note

The method modifies layer visibility before export based on the provided labels. It saves the current state of the drawing to disk before calling Inkscape via a subprocess to perform the rendering.

to_pdf(file_output=None, crop_id=None, hide_layers=None, show_layers=None, show_inclusive=True)[source]#

Export the current drawing as a PDF file.

This method uses a two-stage vector export pipeline when crop_id is provided:

original.svg

-> temporary cropped svg -> final pdf

This approach preserves SVG clipping semantics more reliably than direct PDF export from Inkscape.

Parameters:
  • file_output (str or pathlib.Path) – [optional] Destination PDF path.

  • crop_id (str) – [optional] Object ID used for cropping/export.

  • hide_layers (list) – [optional] List of layer labels to hide.

  • show_layers (list) – [optional] List of layer labels to show.

  • show_inclusive (bool) – Whether show_layers should act inclusively.

Returns:

Path to generated PDF file.

Return type:

pathlib.Path

Warning

Requires inkscape available in system PATH.

to_svg(file_output=None, crop_id=None, hide_layers=None, show_layers=None, show_inclusive=True)[source]#

Export the current drawing as an SVG file.

Parameters:
  • file_output (str or pathlib.Path) – [optional] Destination SVG path. Defaults to the source file name.

  • crop_id (str) – [optional] Object ID to crop the export to.

  • hide_layers (list) – [optional] List of layer labels to hide before export.

  • show_layers (list) – [optional] List of layer labels to show before export.

  • show_inclusive (bool) – Whether to show layers inclusively. Default value = True

Returns:

Path to the generated SVG file.

Return type:

pathlib.Path

Raises:

FileExistsError – If file_output resolves to the same path as the source file.

Warning

This method requires inkscape to be installed and available in the system PATH.