# -*- coding: utf-8 -*-
"""
Created on Fri Oct  3 12:34:36 2025

@author: Moritz Romeike
"""

# ------------------------------------------------------------------------
# Programmcode 13 (Python): nur matplotlib / Scatterplot der Produktion von Diode 01
# ------------------------------------------------------------------------

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Für Reproduzierbarkeit
np.random.seed(123)

# Simulierter Datensatz für Diode 01
dioden_data_single = pd.DataFrame({
    "Zeitpunkt": np.arange(1, 51),
    "Produktion": np.random.normal(loc=50000, scale=2000, size=50)
})

# Nach x sortieren (LOWESS erwartet sortiertes x)
dioden_data_single = dioden_data_single.sort_values("Zeitpunkt").reset_index(drop=True)
x = dioden_data_single["Zeitpunkt"].to_numpy()
y = dioden_data_single["Produktion"].to_numpy()

# Versuche LOESS/LOWESS; bei fehlendem statsmodels -> Savitzky-Golay-Fallback
try:
    from statsmodels.nonparametric.smoothers_lowess import lowess
    # frac ~ ggplot2 span (Anteil der Punkte für lokale Regression)
    span = 0.20  # 0.2–0.4 liefert oft schöne, nicht zu glatte Kurven
    y_smooth = lowess(y, x, frac=span, it=0, return_sorted=False)
    label = f"LOESS (span={span})"
except Exception:
    # Fallback: Savitzky–Golay (benötigt scipy). Falls scipy fehlt, nimm moving average.
    try:
        from scipy.signal import savgol_filter
        # Fenster muss ungerade sein und < Anzahl Punkte
        window = 11 if len(y) >= 11 else (len(y) // 2) * 2 + 1
        poly = 3 if window >= 5 else 2
        y_smooth = savgol_filter(y, window_length=window, polyorder=poly)
        label = f"Savitzky–Golay (w={window}, p={poly})"
    except Exception:
        # Minimaler Fallback: zentriertes gleitendes Mittel
        window = 5
        y_smooth = pd.Series(y).rolling(window=window, center=True).mean().interpolate().to_numpy()
        label = f"Geglättet (MA {window})"

# Plot
plt.figure(figsize=(9,5.2))
plt.scatter(x, y, s=50, alpha=0.7, label="Produktion", color="blue")
plt.plot(x, y_smooth, linewidth=2, color="red", label=label)

plt.title("Scatterplot der Produktion von Diode 01")
plt.xlabel("Zeitpunkt")
plt.ylabel("Anzahl produzierter Dioden")
plt.legend()
plt.tight_layout()
plt.show()
# ------------------------------------------------------------------------
