Skip to content

base

Full name: tenets.viz.base

base

Base visualization module providing common functionality.

This module provides the base classes and utilities for all visualization components. It includes chart configuration, color management, and common visualization patterns used throughout the viz package.

Classes

ChartType

Bases: Enum

Supported chart types.

DisplayFormat

Bases: Enum

Supported display formats.

ChartConfigdataclass

Python
ChartConfig(type: ChartType, title: str = '', width: int = 800, height: int = 400, colors: Optional[List[str]] = None, theme: str = 'light', interactive: bool = True, show_legend: bool = True, show_grid: bool = True, animation: bool = True, responsive: bool = True, export_options: List[str] = (lambda: ['png', 'svg'])())

Configuration for chart generation.

ATTRIBUTEDESCRIPTION
type

Type of chart to generate

TYPE:ChartType

title

Chart title

TYPE:str

width

Chart width in pixels

TYPE:int

height

Chart height in pixels

TYPE:int

colors

Custom color palette

TYPE:Optional[List[str]]

theme

Visual theme (light, dark, etc.)

TYPE:str

interactive

Whether chart should be interactive

TYPE:bool

show_legend

Whether to show legend

TYPE:bool

show_grid

Whether to show grid lines

TYPE:bool

animation

Whether to animate chart

TYPE:bool

responsive

Whether chart should be responsive

TYPE:bool

export_options

Export format options

TYPE:List[str]

DisplayConfigdataclass

Python
DisplayConfig(use_colors: bool = True, use_unicode: bool = True, max_width: int = 120, max_rows: int = 50, truncate: bool = True, show_progress: bool = True, style: str = 'detailed')

Configuration for terminal display.

ATTRIBUTEDESCRIPTION
use_colors

Whether to use colors in terminal

TYPE:bool

use_unicode

Whether to use unicode characters

TYPE:bool

max_width

Maximum display width

TYPE:int

max_rows

Maximum rows to display

TYPE:int

truncate

Whether to truncate long text

TYPE:bool

show_progress

Whether to show progress indicators

TYPE:bool

style

Display style (compact, detailed, etc.)

TYPE:str

ColorPalette

Color palette management for visualizations.

Provides consistent color schemes across all visualizations with support for different themes and accessibility considerations.

Functions
get_paletteclassmethod
Python
get_palette(name: str = 'default') -> List[str]

Get a color palette by name.

PARAMETERDESCRIPTION
name

Palette name (default, monochrome, etc.)

TYPE:strDEFAULT:'default'

RETURNSDESCRIPTION
List[str]

List[str]: List of color hex codes

Source code in tenets/viz/base.py
Python
@classmethod
def get_palette(cls, name: str = "default") -> List[str]:
    """Get a color palette by name.

    Args:
        name: Palette name (default, monochrome, etc.)

    Returns:
        List[str]: List of color hex codes
    """
    palettes = {
        "default": cls.DEFAULT,
        "monochrome": cls.MONOCHROME,
        "severity": list(cls.SEVERITY.values()),
        "health": list(cls.HEALTH.values()),
    }
    return palettes.get(name.lower(), cls.DEFAULT)
get_colorclassmethod
Python
get_color(value: Any, category: str = 'default') -> str

Get a color for a specific value.

PARAMETERDESCRIPTION
value

Value to get color for

TYPE:Any

category

Category (severity, health, etc.)

TYPE:strDEFAULT:'default'

RETURNSDESCRIPTION
str

Color hex code

TYPE:str

Source code in tenets/viz/base.py
Python
@classmethod
def get_color(cls, value: Any, category: str = "default") -> str:
    """Get a color for a specific value.

    Args:
        value: Value to get color for
        category: Category (severity, health, etc.)

    Returns:
        str: Color hex code
    """
    if category == "severity":
        return cls.SEVERITY.get(str(value).lower(), cls.DEFAULT[0])
    elif category == "health":
        return cls.HEALTH.get(str(value).lower(), cls.DEFAULT[0])
    else:
        # Use default palette with modulo for cycling
        if isinstance(value, int):
            return cls.DEFAULT[value % len(cls.DEFAULT)]
        return cls.DEFAULT[0]
interpolate_colorclassmethod
Python
interpolate_color(value: float, min_val: float = 0, max_val: float = 100, start_color: str = '#10b981', end_color: str = '#ef4444') -> str

Interpolate color based on value.

PARAMETERDESCRIPTION
value

Value to interpolate

TYPE:float

min_val

Minimum value

TYPE:floatDEFAULT:0

max_val

Maximum value

TYPE:floatDEFAULT:100

start_color

Color for minimum value

TYPE:strDEFAULT:'#10b981'

end_color

Color for maximum value

TYPE:strDEFAULT:'#ef4444'

RETURNSDESCRIPTION
str

Interpolated color hex code

TYPE:str

Source code in tenets/viz/base.py
Python
@classmethod
def interpolate_color(
    cls,
    value: float,
    min_val: float = 0,
    max_val: float = 100,
    start_color: str = "#10b981",
    end_color: str = "#ef4444",
) -> str:
    """Interpolate color based on value.

    Args:
        value: Value to interpolate
        min_val: Minimum value
        max_val: Maximum value
        start_color: Color for minimum value
        end_color: Color for maximum value

    Returns:
        str: Interpolated color hex code
    """
    # Normalize value
    if max_val == min_val:
        ratio = 0.5
    else:
        ratio = (value - min_val) / (max_val - min_val)
        ratio = max(0, min(1, ratio))

    # Parse colors
    start_rgb = cls._hex_to_rgb(start_color)
    end_rgb = cls._hex_to_rgb(end_color)

    # Interpolate
    r = int(start_rgb[0] + (end_rgb[0] - start_rgb[0]) * ratio)
    g = int(start_rgb[1] + (end_rgb[1] - start_rgb[1]) * ratio)
    b = int(start_rgb[2] + (end_rgb[2] - start_rgb[2]) * ratio)

    return f"#{r:02x}{g:02x}{b:02x}"

BaseVisualizer

Python
BaseVisualizer(chart_config: Optional[ChartConfig] = None, display_config: Optional[DisplayConfig] = None)

Base class for all visualizers.

Provides common functionality for creating visualizations including chart generation, color management, and data formatting.

ATTRIBUTEDESCRIPTION
logger

Logger instance

chart_config

Default chart configuration

display_config

Default display configuration

color_palette

Color palette to use

Initialize base visualizer.

PARAMETERDESCRIPTION
chart_config

Chart configuration

TYPE:Optional[ChartConfig]DEFAULT:None

display_config

Display configuration

TYPE:Optional[DisplayConfig]DEFAULT:None

Source code in tenets/viz/base.py
Python
def __init__(
    self,
    chart_config: Optional[ChartConfig] = None,
    display_config: Optional[DisplayConfig] = None,
):
    """Initialize base visualizer.

    Args:
        chart_config: Chart configuration
        display_config: Display configuration
    """
    self.logger = get_logger(self.__class__.__name__)
    self.chart_config = chart_config or ChartConfig(type=ChartType.BAR)
    self.display_config = display_config or DisplayConfig()
    self.color_palette = ColorPalette.get_palette("default")
Functions
create_chart
Python
create_chart(chart_type: ChartType, data: Dict[str, Any], config: Optional[ChartConfig] = None) -> Dict[str, Any]

Create a chart configuration.

PARAMETERDESCRIPTION
chart_type

Type of chart

TYPE:ChartType

data

Chart data

TYPE:Dict[str, Any]

config

Optional chart configuration

TYPE:Optional[ChartConfig]DEFAULT:None

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: Chart configuration for rendering

Source code in tenets/viz/base.py
Python
def create_chart(
    self, chart_type: ChartType, data: Dict[str, Any], config: Optional[ChartConfig] = None
) -> Dict[str, Any]:
    """Create a chart configuration.

    Args:
        chart_type: Type of chart
        data: Chart data
        config: Optional chart configuration

    Returns:
        Dict[str, Any]: Chart configuration for rendering
    """
    config = config or self.chart_config
    config.type = chart_type

    # Route to specific chart creator
    creators = {
        ChartType.BAR: self._create_bar_chart,
        ChartType.HORIZONTAL_BAR: self._create_horizontal_bar_chart,
        ChartType.LINE: self._create_line_chart,
        ChartType.PIE: self._create_pie_chart,
        ChartType.SCATTER: self._create_scatter_chart,
        ChartType.RADAR: self._create_radar_chart,
        ChartType.GAUGE: self._create_gauge_chart,
        ChartType.HEATMAP: self._create_heatmap,
        ChartType.TREEMAP: self._create_treemap,
        ChartType.NETWORK: self._create_network_graph,
        ChartType.BUBBLE: self._create_bubble_chart,
    }

    creator = creators.get(chart_type, self._create_bar_chart)
    return creator(data, config)
format_number
Python
format_number(value: Union[int, float], precision: int = 2, use_thousands: bool = True) -> str

Format a number for display.

PARAMETERDESCRIPTION
value

Number to format

TYPE:Union[int, float]

precision

Decimal precision

TYPE:intDEFAULT:2

use_thousands

Use thousands separator

TYPE:boolDEFAULT:True

RETURNSDESCRIPTION
str

Formatted number

TYPE:str

Source code in tenets/viz/base.py
Python
def format_number(
    self, value: Union[int, float], precision: int = 2, use_thousands: bool = True
) -> str:
    """Format a number for display.

    Args:
        value: Number to format
        precision: Decimal precision
        use_thousands: Use thousands separator

    Returns:
        str: Formatted number
    """
    if isinstance(value, float):
        formatted = f"{value:.{precision}f}"
    else:
        formatted = str(value)

    if use_thousands and abs(value) >= 1000:
        parts = formatted.split(".")
        parts[0] = f"{int(parts[0]):,}"
        formatted = ".".join(parts) if len(parts) > 1 else parts[0]

    return formatted
format_percentage
Python
format_percentage(value: float, precision: int = 1, include_sign: bool = False) -> str

Format a value as percentage.

PARAMETERDESCRIPTION
value

Value (0-1 or 0-100 depending on context)

TYPE:float

precision

Decimal precision

TYPE:intDEFAULT:1

include_sign

Include + sign for positive values

TYPE:boolDEFAULT:False

RETURNSDESCRIPTION
str

Formatted percentage

TYPE:str

Source code in tenets/viz/base.py
Python
def format_percentage(
    self, value: float, precision: int = 1, include_sign: bool = False
) -> str:
    """Format a value as percentage.

    Args:
        value: Value (0-1 or 0-100 depending on context)
        precision: Decimal precision
        include_sign: Include + sign for positive values

    Returns:
        str: Formatted percentage
    """
    # Assume 0-1 range if value <= 1
    if -1 <= value <= 1:
        percentage = value * 100
    else:
        percentage = value

    formatted = f"{percentage:.{precision}f}%"

    if include_sign and percentage > 0:
        formatted = f"+{formatted}"

    return formatted
export_chart
Python
export_chart(chart_config: Dict[str, Any], output_path: Path, format: str = 'json') -> Path

Export chart configuration to file.

PARAMETERDESCRIPTION
chart_config

Chart configuration

TYPE:Dict[str, Any]

output_path

Output file path

TYPE:Path

format

Export format (json, html, etc.)

TYPE:strDEFAULT:'json'

RETURNSDESCRIPTION
Path

Path to exported file

TYPE:Path

Source code in tenets/viz/base.py
Python
def export_chart(
    self, chart_config: Dict[str, Any], output_path: Path, format: str = "json"
) -> Path:
    """Export chart configuration to file.

    Args:
        chart_config: Chart configuration
        output_path: Output file path
        format: Export format (json, html, etc.)

    Returns:
        Path: Path to exported file
    """
    if format == "json":
        with open(output_path, "w") as f:
            json.dump(chart_config, f, indent=2)
    elif format == "html":
        # Generate standalone HTML with chart
        html = self._generate_standalone_html(chart_config)
        with open(output_path, "w") as f:
            f.write(html)
    else:
        raise ValueError(f"Unsupported export format: {format}")

    self.logger.debug(f"Exported chart to {output_path}")
    return output_path

Functions