#!/usr/bin/env python3
"""Jahresmittel, Abweichung vom Mittel 1961–1990, Trend und Schwankung aus den Monatsreihen des Datenpakets.
Aufruf:  python 02_auswertung.py ../monatlich/tas_global_monatlich.zip MIROC6
Ausgabe: je Lauf Trend 1979–2020 (Einheit je Jahrzehnt) und Standardabweichung der Jahresmittel um den linearen Trend.
Regeln (wie auf der Seite): nur volle Kalenderjahre; Läufe ohne volles Mittel 1961–1990 werden nicht verwendet.
Benötigt: python>=3.10, numpy, pandas.  Lizenz des Skripts: MIT."""
import sys,zipfile,io,numpy as np,pandas as pd
def lade(zip_pfad,modell):
    z=zipfile.ZipFile(zip_pfad);name=[n for n in z.namelist() if n.endswith('_%s.csv'%modell)][0]
    return pd.read_csv(io.BytesIO(z.read(name)),comment='#')
def jahresmittel(df,lauf):
    s=df[['jahr','monat',lauf]].dropna();g=s.groupby('jahr')[lauf];ok=g.count()==12
    return g.mean()[ok]
def anomalie(jm,a=1961,b=1990):
    ref=jm.loc[a:b]
    return None if len(ref)<(b-a+1) else jm-ref.mean()
def trend(jm,a=1979,b=2020):
    x=jm.loc[a:b]
    if len(x)<(b-a+1):return None,None
    c=np.polyfit(x.index.values,x.values,1);rest=x.values-np.polyval(c,x.index.values)
    return c[0]*10,rest.std(ddof=2)
if __name__=='__main__':
    if len(sys.argv)!=3:raise SystemExit(__doc__)
    df=lade(sys.argv[1],sys.argv[2])
    print('Lauf, Trend 1979–2020 je Jahrzehnt, Schwankung um den Trend')
    for lauf in [c for c in df.columns if c not in('jahr','monat')]:
        jm=jahresmittel(df,lauf)
        if anomalie(jm) is None:print(lauf,'keine volle Referenz 1961–1990');continue
        t,sd=trend(jm);print(lauf,'%.3f'%t if t is not None else '–','%.3f'%sd if sd is not None else '–')
