from matplotlib.patches import Patch
from datetime import datetime
[docs]
def upsert_handle(handles: list[Patch], new_handle: Patch) -> None:
"""
Utility function that adds a new legend handle to the list of handles if it does not already exist.
Parameters:
handles (list[Patch]): The list of existing legend handles.
new_handle (Patch): The new legend handle to add.
"""
for handle in handles:
if handle.get_label() == new_handle.get_label():
return
handles.append(new_handle)
[docs]
def get_image_path(filename: str, filepath: str) -> str:
"""
Utility function that simply constructs the entire path for a given image filename.
If necessary, the function also adds the ending forwards slash to the filepath.
Parameters:
filename (str): The image filename.
filepath (str): The filepath where the image is located.
Returns:
str: The full path to the image.
"""
if filepath is None or filepath == "":
raise ValueError("No filepath provided.")
if filename is None or filename == "":
raise ValueError("No filename provided.")
filepath = validate_filepath(filepath)
return filepath + filename
[docs]
def validate_filepath(filepath: str) -> str:
"""
Utility function that validates the provided filepath.
Parameters:
filepath (str): The filepath to validate.
Returns:
str: The validated filepath, ensuring it ends with a forward slash.
"""
if filepath is None or filepath == "":
raise ValueError("No filepath provided.")
if not filepath.endswith("/"):
filepath += "/"
return filepath
[docs]
def build_save_path(filepath: str, extension: str) -> str:
"""
Utility function that constructs a save path for an image with a timestamp, ensuring the filepath ends with a forward slash.
Parameters:
filepath (str): The base filepath where the image will be saved.
extension (str): The file extension for the saved image (e.g., '.png', '.jpg').
Returns:
str: The constructed save path for the image.
"""
if filepath is None or filepath == "":
raise ValueError("No filepath provided.")
if not extension.startswith("."):
raise ValueError("Extension must start with a '.'")
filepath = validate_filepath(filepath)
return f"{filepath}{datetime.now().strftime('%Y%m%dT%H%M%S')}{extension}"