"""
TimeSeriesPatternIdentifier
Generated by Eden via recursive self-improvement
2025-10-28 01:03:58.748746
"""

class TimeSeriesPatternIdentifier:
    """
    A class to analyze time series data and identify patterns/trends.
    
    Methods:
        __init__(self): Initializes the pattern identifier with empty lists.
        add_data_point(self, timestamp, value): Adds a new data point to the series.
        detect_patterns(self): Identifies recurring patterns or trends in the data.
        check_anomaly(self): Checks for anomalies based on historical patterns.
    """

    def __init__(self):
        self.time_points = []  # List of timestamps
        self.data_values = []   # Corresponding values at each timestamp

    def add_data_point(self, timestamp, value):
        """
        Adds a new data point to the time series.
        
        Args:
            timestamp: The time at which the measurement was taken.
            value: The measured value at that timestamp.
        """
        self.time_points.append(timestamp)
        self.data_values.append(value)

    def detect_patterns(self):
        """
        Identifies recurring patterns or trends in the data.
        
        Returns:
            A dictionary with 'trend' (increasing, decreasing, stable) and
            'patterns' (recurrent values or intervals).
        """
        # Simple trend detection based on moving average
        window_size = 5
        trends = []
        for i in range(len(self.data_values)):
            if i >= window_size:
                avg = sum(self.data_values[i-window_size:i]) / window_size
                current_val = self.data_values[i]
                if current_val > avg * 1.05:
                    trends.append('up')
                elif current_val < avg * 0.95:
                    trends.append('down')
                else:
                    trends.append('stable')
            else:
                trends.append(None)
        
        # Pattern detection (simplified example)
        patterns = {}
        for i in range(len(trends)):
            if trends[i] is not None:
                if trends[i-1] == trends[i]:
                    if trends[i] in patterns:
                        patterns[trends[i]] += 1
                    else:
                        patterns[trends[i]] = 1
        
        return {
            'trend': 'up' if sum(trends[-window_size:]) > window_size/2 else 
                     'down' if sum(trends[-window_size:]) < window_size/2 else 'stable',
            'patterns': patterns
        }

    def check_anomaly(self, threshold=0.95):
        """
        Checks for anomalies based on historical data.
        
        Args:
            threshold: The threshold to determine anomaly (default 0.95).
            
        Returns:
            A dictionary with True/False indicating if current point is an anomaly.
        """
        # Simple Z-score based anomaly detection
        import numpy as np
        
        z_scores = []
        for i in range(len(self.data_values)):
            if i >= 1:  # Skip first element
                mean = np.mean(self.data_values[:i])
                std = np.std(self.data_values[:i])
                z_score = (self.data_values[i] - mean) / std
                z_scores.append(abs(z_score))
            else:
                z_scores.append(0)
        
        last_z = z_scores[-1] if len(z_scores) > 0 else 0
        is_anomaly = last_z > threshold
        
        return {'is_anomaly': is_anomaly, 'z_score': last_z}

    def display_identified_patterns(self):
        """
        Prints the identified patterns and anomalies.
        """
        print("Identified Patterns:")
        patterns = self.detect_patterns()
        for trend in ['up', 'down', 'stable']:
            if trend in patterns['patterns']:
                print(f"{trend.capitalize()}: {patterns['patterns'][trend]} occurrences")
        
        anomaly_check = self.check_anomaly()
        print("\nAnomaly Check:")
        print(f"Last point is anomaly: {anomaly_check['is_anomaly']}")
        print(f"Z-score: {anomaly_check['z_score']}\n")

# Example usage
if __name__ == "__main__":
    # Initialize the pattern identifier
    ts = TimeSeriesPatternIdentifier()
    
    # Add some sample data points (timestamp, value)
    ts.add_data_point(1, 10)
    ts.add_data_point(2, 15)
    ts.add_data_point(3, 20)
    ts.add_data_point(4, 25)
    ts.add_data_point(5, 30)
    ts.add_data_point(6, 28)
    ts.add_data_point(7, 27)
    ts.add_data_point(8, 29)
    ts.add_data_point(9, 31)
    ts.add_data_point(10, 25)
    
    # Analyze patterns
    ts.display_identified_patterns()