|
| 1 | +"""TrendTracker - Encapsulated trend tracking for live profiling metrics. |
| 2 | +
|
| 3 | +This module provides trend tracking functionality for profiling metrics, |
| 4 | +calculating direction indicators (up/down/stable) and managing associated |
| 5 | +visual attributes like colors. |
| 6 | +""" |
| 7 | + |
| 8 | +import curses |
| 9 | +from typing import Dict, Literal, Any |
| 10 | + |
| 11 | +TrendDirection = Literal["up", "down", "stable"] |
| 12 | + |
| 13 | + |
| 14 | +class TrendTracker: |
| 15 | + """ |
| 16 | + Tracks metric trends over time and provides visual indicators. |
| 17 | +
|
| 18 | + This class encapsulates all logic for: |
| 19 | + - Tracking previous values of metrics |
| 20 | + - Calculating trend directions (up/down/stable) |
| 21 | + - Determining visual attributes (colors) for trends |
| 22 | + - Managing enable/disable state |
| 23 | +
|
| 24 | + Example: |
| 25 | + tracker = TrendTracker(colors_dict) |
| 26 | + tracker.update("func1", "nsamples", 10) |
| 27 | + trend = tracker.get_trend("func1", "nsamples") |
| 28 | + color = tracker.get_color("func1", "nsamples") |
| 29 | + """ |
| 30 | + |
| 31 | + # Threshold for determining if a value has changed significantly |
| 32 | + CHANGE_THRESHOLD = 0.001 |
| 33 | + |
| 34 | + def __init__(self, colors: Dict[str, int], enabled: bool = True): |
| 35 | + """ |
| 36 | + Initialize the trend tracker. |
| 37 | +
|
| 38 | + Args: |
| 39 | + colors: Dictionary containing color attributes including |
| 40 | + 'trend_up', 'trend_down', 'trend_stable' |
| 41 | + enabled: Whether trend tracking is initially enabled |
| 42 | + """ |
| 43 | + self._previous_values: Dict[Any, Dict[str, float]] = {} |
| 44 | + self._enabled = enabled |
| 45 | + self._colors = colors |
| 46 | + |
| 47 | + @property |
| 48 | + def enabled(self) -> bool: |
| 49 | + """Whether trend tracking is enabled.""" |
| 50 | + return self._enabled |
| 51 | + |
| 52 | + def toggle(self) -> bool: |
| 53 | + """ |
| 54 | + Toggle trend tracking on/off. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + New enabled state |
| 58 | + """ |
| 59 | + self._enabled = not self._enabled |
| 60 | + return self._enabled |
| 61 | + |
| 62 | + def set_enabled(self, enabled: bool) -> None: |
| 63 | + """Set trend tracking enabled state.""" |
| 64 | + self._enabled = enabled |
| 65 | + |
| 66 | + def update(self, key: Any, metric: str, value: float) -> TrendDirection: |
| 67 | + """ |
| 68 | + Update a metric value and calculate its trend. |
| 69 | +
|
| 70 | + Args: |
| 71 | + key: Identifier for the entity (e.g., function) |
| 72 | + metric: Name of the metric (e.g., 'nsamples', 'tottime') |
| 73 | + value: Current value of the metric |
| 74 | +
|
| 75 | + Returns: |
| 76 | + Trend direction: 'up', 'down', or 'stable' |
| 77 | + """ |
| 78 | + # Initialize storage for this key if needed |
| 79 | + if key not in self._previous_values: |
| 80 | + self._previous_values[key] = {} |
| 81 | + |
| 82 | + # Get previous value, defaulting to current if not tracked yet |
| 83 | + prev_value = self._previous_values[key].get(metric, value) |
| 84 | + |
| 85 | + # Calculate trend |
| 86 | + if value > prev_value + self.CHANGE_THRESHOLD: |
| 87 | + trend = "up" |
| 88 | + elif value < prev_value - self.CHANGE_THRESHOLD: |
| 89 | + trend = "down" |
| 90 | + else: |
| 91 | + trend = "stable" |
| 92 | + |
| 93 | + # Update previous value for next iteration |
| 94 | + self._previous_values[key][metric] = value |
| 95 | + |
| 96 | + return trend |
| 97 | + |
| 98 | + def get_trend(self, key: Any, metric: str) -> TrendDirection: |
| 99 | + """ |
| 100 | + Get the current trend for a metric without updating. |
| 101 | +
|
| 102 | + Args: |
| 103 | + key: Identifier for the entity |
| 104 | + metric: Name of the metric |
| 105 | +
|
| 106 | + Returns: |
| 107 | + Trend direction, or 'stable' if not tracked |
| 108 | + """ |
| 109 | + # This would require storing trends separately, which we don't do |
| 110 | + # For now, return stable if not found |
| 111 | + return "stable" |
| 112 | + |
| 113 | + def get_color(self, trend: TrendDirection) -> int: |
| 114 | + """ |
| 115 | + Get the color attribute for a trend direction. |
| 116 | +
|
| 117 | + Args: |
| 118 | + trend: The trend direction |
| 119 | +
|
| 120 | + Returns: |
| 121 | + Curses color attribute (or A_NORMAL if disabled) |
| 122 | + """ |
| 123 | + if not self._enabled: |
| 124 | + return curses.A_NORMAL |
| 125 | + |
| 126 | + if trend == "up": |
| 127 | + return self._colors.get("trend_up", curses.A_BOLD) |
| 128 | + elif trend == "down": |
| 129 | + return self._colors.get("trend_down", curses.A_BOLD) |
| 130 | + else: # stable |
| 131 | + return self._colors.get("trend_stable", curses.A_NORMAL) |
| 132 | + |
| 133 | + def update_metrics(self, key: Any, metrics: Dict[str, float]) -> Dict[str, TrendDirection]: |
| 134 | + """ |
| 135 | + Update multiple metrics at once and get their trends. |
| 136 | +
|
| 137 | + Args: |
| 138 | + key: Identifier for the entity |
| 139 | + metrics: Dictionary of metric_name -> value |
| 140 | +
|
| 141 | + Returns: |
| 142 | + Dictionary of metric_name -> trend_direction |
| 143 | + """ |
| 144 | + trends = {} |
| 145 | + for metric, value in metrics.items(): |
| 146 | + trends[metric] = self.update(key, metric, value) |
| 147 | + return trends |
| 148 | + |
| 149 | + def clear(self) -> None: |
| 150 | + """Clear all tracked values (useful on stats reset).""" |
| 151 | + self._previous_values.clear() |
| 152 | + |
| 153 | + def __repr__(self) -> str: |
| 154 | + """String representation for debugging.""" |
| 155 | + status = "enabled" if self._enabled else "disabled" |
| 156 | + tracked = len(self._previous_values) |
| 157 | + return f"TrendTracker({status}, tracking {tracked} entities)" |
0 commit comments