# -*- coding: utf-8 -*-
"""
Created on Fri Oct  3 12:39:27 2025

@author: Moritz Romeike
"""

# ------------------------------------------------------------------------
# Programmcode 17 (Python): Herfindahl-Hirschman-Index (HHI) & Visualisierung
# ------------------------------------------------------------------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Marktanteile der Lieferanten (in Prozent, wie im R-Beispiel)
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)

# HHI-Berechnung mit Prozentangaben sum(Anteil^2))
hhi = float(np.sum(lieferanten_anteile ** 2))
print(f"Herfindahl-Hirschman-Index (HHI, Prozent-Skala 0..10.000): {hhi:.2f}")  # ~ 858.56

# (Optional) HHI auf 0..1 Skala:
hhi_0_1 = float(np.sum((lieferanten_anteile/100.0) ** 2))  # ~ 0.085856
# print(f"HHI (0..1-Skala): {hhi_0_1:.6f}")

# DataFrame für Plot: nach Marktanteil sortieren + kumulieren
df = (
    pd.DataFrame({"Lieferant": np.arange(1, len(lieferanten_anteile)+1),
                  "Marktanteil": lieferanten_anteile})
      .sort_values("Marktanteil", ascending=False, ignore_index=True)
)
df["Kumulierte_Anteile"] = df["Marktanteil"].cumsum()

# Visualisierung: kumulierte Marktanteile (Barplot)
plt.figure(figsize=(10,5))
plt.bar(df.index + 1, df["Kumulierte_Anteile"])
plt.title("Kumulierte Marktanteile der Lieferanten")
plt.suptitle(f"HHI-Wert: {hhi:.2f}", y=0.98, fontsize=10)
plt.xlabel("Lieferanten (nummeriert nach Marktanteil)")
plt.ylabel("Kumulierte Marktanteile (%)")
plt.tight_layout()
# plt.savefig("kumulierte_marktanteile_hhi.png", dpi=150)
plt.show()
# ------------------------------------------------------------------------
