# Dieses Programm lasse ich in
# ipython --pylab
# laufen.

import numpy as np
import matplotlib.pyplot as plt

# Daten aus Datei einlesen - erst einmal ohne separator
#tempData = np.loadtxt("HadCRUT3-odd.dat",unpack=True)
tempData = np.loadtxt("HadCRUT4-odd.dat",unpack=True)

# Achtung, nachher ist noch von Hand der Index eingefuegt, ab dem die
# Ausgleichsgerade bestimmt wird! Das aendert sich auch von Datensatz zu Datensatz!


# Jahre getrennt speichern:
years = tempData[0]
# Temperaturen J-D getrennt speichern:
temps = tempData[13]

# Jetzt die Glättung berechnen:

def slideAvg ( dataField, interval):
    # Hier den letzten Index des eingelesenen Feldes herausfinden:
    dflength = dataField.shape[0]
    # Intervall in Differenz plus minus umrechnen:
    diff = int ( 0.5*(interval-1) )
    # Ausgabeliste initialisieren:
    resultList = []
    #print diff
    for i in range(0, dflength - 2*diff):
        thisSum = 0
        for j in range(0,2*diff+1):
            thisSum += dataField[i+j]
        thisAvg = thisSum/(2*diff+1)
        resultList.append(thisAvg)
    resultArray = np.array(resultList)
    return resultArray

avgint = 25
avgtemps = slideAvg(temps, avgint)
indDiff = int ( 0.5*(avgint-1) )
avgyears = years[indDiff:-indDiff]

#avgString = u"Gemittelt über %d Jahre" % avgint
#plt.figtext(0.1,0.8, avgString)
#plt.figtext(0.2,0.75,avgString,size='large')
#plt.plot(avgyears,abweichungen, color='r', linewidth=2)

# Index 120 einfach durch Ablesen bestimmt - das entspricht dem Wert
# fuer das Jahr 1982:
fitYears = avgyears[120:]
fitTemps = avgtemps[120:]

a,b = np.polyfit(fitYears, fitTemps, 1)

fitX = np.array([1998,2012]);
fitY = np.array([a*1998+b, a*2012+b])

plt.plot(fitX,fitY, color='g', linewidth=2, linestyle='dashed')
plt.plot(years,temps, color=(0.7,0.7,1.0), linewidth=2)
plt.plot(avgyears,avgtemps, color='g', linewidth=2)

plt.figtext(0.2,0.75,"HadCRUT4",size='large')

plt.xlabel("Jahr")
plt.ylabel("Temperaturdifferenz in Grad Celsius")
plt.axis([1960,2013,-0.3, 0.8])
#plt.axhline(y=0, color=(0.5,0.5,0.5))

outFileName = "extrapolated-last-bit-HadCRUT4.png"
savefig(outFileName, dpi=80)




