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¶
ChartConfigdataclass
¶
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.
ATTRIBUTE | DESCRIPTION |
---|---|
type | Type of chart to generate TYPE: |
title | Chart title TYPE: |
width | Chart width in pixels TYPE: |
height | Chart height in pixels TYPE: |
colors | Custom color palette |
theme | Visual theme (light, dark, etc.) TYPE: |
interactive | Whether chart should be interactive TYPE: |
show_legend | Whether to show legend TYPE: |
show_grid | Whether to show grid lines TYPE: |
animation | Whether to animate chart TYPE: |
responsive | Whether chart should be responsive TYPE: |
export_options | Export format options |
DisplayConfigdataclass
¶
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.
ATTRIBUTE | DESCRIPTION |
---|---|
use_colors | Whether to use colors in terminal TYPE: |
use_unicode | Whether to use unicode characters TYPE: |
max_width | Maximum display width TYPE: |
max_rows | Maximum rows to display TYPE: |
truncate | Whether to truncate long text TYPE: |
show_progress | Whether to show progress indicators TYPE: |
style | Display style (compact, detailed, etc.) TYPE: |
ColorPalette¶
Color palette management for visualizations.
Provides consistent color schemes across all visualizations with support for different themes and accessibility considerations.
Functions¶
get_paletteclassmethod
¶
Get a color palette by name.
PARAMETER | DESCRIPTION |
---|---|
name | Palette name (default, monochrome, etc.) TYPE: |
RETURNS | DESCRIPTION |
---|---|
List[str] | List[str]: List of color hex codes |
Source code in tenets/viz/base.py
@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
¶
Get a color for a specific value.
PARAMETER | DESCRIPTION |
---|---|
value | Value to get color for TYPE: |
category | Category (severity, health, etc.) TYPE: |
RETURNS | DESCRIPTION |
---|---|
str | Color hex code TYPE: |
Source code in tenets/viz/base.py
@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
¶
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.
PARAMETER | DESCRIPTION |
---|---|
value | Value to interpolate TYPE: |
min_val | Minimum value TYPE: |
max_val | Maximum value TYPE: |
start_color | Color for minimum value TYPE: |
end_color | Color for maximum value TYPE: |
RETURNS | DESCRIPTION |
---|---|
str | Interpolated color hex code TYPE: |
Source code in tenets/viz/base.py
@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¶
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.
ATTRIBUTE | DESCRIPTION |
---|---|
logger | Logger instance |
chart_config | Default chart configuration |
display_config | Default display configuration |
color_palette | Color palette to use |
Initialize base visualizer.
PARAMETER | DESCRIPTION |
---|---|
chart_config | Chart configuration TYPE: |
display_config | Display configuration TYPE: |
Source code in tenets/viz/base.py
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¶
create_chart(chart_type: ChartType, data: Dict[str, Any], config: Optional[ChartConfig] = None) -> Dict[str, Any]
Create a chart configuration.
PARAMETER | DESCRIPTION |
---|---|
chart_type | Type of chart TYPE: |
data | Chart data |
config | Optional chart configuration TYPE: |
RETURNS | DESCRIPTION |
---|---|
Dict[str, Any] | Dict[str, Any]: Chart configuration for rendering |
Source code in tenets/viz/base.py
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¶
format_number(value: Union[int, float], precision: int = 2, use_thousands: bool = True) -> str
Format a number for display.
PARAMETER | DESCRIPTION |
---|---|
value | Number to format |
precision | Decimal precision TYPE: |
use_thousands | Use thousands separator TYPE: |
RETURNS | DESCRIPTION |
---|---|
str | Formatted number TYPE: |
Source code in tenets/viz/base.py
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¶
Format a value as percentage.
PARAMETER | DESCRIPTION |
---|---|
value | Value (0-1 or 0-100 depending on context) TYPE: |
precision | Decimal precision TYPE: |
include_sign | Include + sign for positive values TYPE: |
RETURNS | DESCRIPTION |
---|---|
str | Formatted percentage TYPE: |
Source code in tenets/viz/base.py
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¶
Export chart configuration to file.
PARAMETER | DESCRIPTION |
---|---|
chart_config | Chart configuration |
output_path | Output file path TYPE: |
format | Export format (json, html, etc.) TYPE: |
RETURNS | DESCRIPTION |
---|---|
Path | Path to exported file TYPE: |
Source code in tenets/viz/base.py
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