# -*- coding: utf-8 -*-
"""
Created on Fri Oct  3 12:37:56 2025

@author: Moritz Romeike
"""

# ------------------------------------------------------------------------
# Programmcode 16 (Python): Lorenz-Kurve & Gini-Koeffizient
# ------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt

# Marktanteile der Lieferanten (in %)
lieferanten_anteile = np.array([
    12.5, 10.3, 9.8, 8.5, 7.6, 6.9, 6.5, 6.2, 5.8, 5.2,
    4.9, 4.6, 4.2, 3.9, 3.7, 3.5, 3.3, 3.1, 2.9, 2.7,
    2.5, 2.3, 2.1, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3,
    1.2, 1.1, 1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3,
    0.3, 0.3, 0.3, 0.2, 0.2, 0.2, 0.1, 0.1, 0.1, 0.1
], dtype=float)

def gini(x: np.ndarray) -> float:
    x = np.asarray(x, dtype=float)
    if np.any(x < 0): raise ValueError("Gini nur für nicht-negative Werte.")
    if np.all(x == 0): return 0.0
    x_sorted = np.sort(x)
    n = x_sorted.size
    return (2.0 * np.dot(np.arange(1, n + 1), x_sorted) / (n * x_sorted.sum())
            - (n + 1.0) / n)

gini_wert = gini(lieferanten_anteile)

# Lorenz-Kurve vorbereiten
werte = np.sort(lieferanten_anteile)
cum_werte_norm = np.cumsum(werte) / np.sum(werte)        # 0..1
cum_anzahl = np.arange(1, len(werte) + 1) / len(werte)   # 0..1
x_pct = cum_anzahl * 100
y_pct = cum_werte_norm * 100

# Plot


# ---- Plot ohne Subtitel, Gini-Wert im Plot --------------------------------
fig, ax = plt.subplots(figsize=(7.5, 6), constrained_layout=False)

# Haupttitel
fig.suptitle("Lorenz-Kurve zur Visualisierung der Lieferantenkonzentration",
             fontsize=14, y=0.975)

# Kurven
ax.plot(x_pct, y_pct, linewidth=2, label="Lorenz-Kurve")
ax.plot([0, 100], [0, 100], linestyle="--", label="Gleichverteilung (45°)")

ax.set_xlim(0, 100); ax.set_ylim(0, 100)
ax.set_xlabel("Kumulierte Anzahl der Lieferanten (%)")
ax.set_ylabel("Kumulierte Marktanteile (%)")
ax.grid(True, alpha=0.25)

# Gini-Wert abbilden in Grafik
ax.text(
    0.98, 0.05, f"Gini-Koeffizient: {gini_wert:.2f}",
    transform=ax.transAxes, ha="right", va="bottom", fontsize=11,
    bbox=dict(facecolor="white", alpha=0.75, edgecolor="none")
)

fig.tight_layout(rect=[0, 0, 1, 0.94])

plt.show()

# ------------------------------------------------------------------------
