# -*- coding: utf-8 -*-
"""
@author: Vaclav Miklas
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd

nazvy = ('MGM100','MGM200','MGM350','MGM430','MGM500')

def func(x, a, b, c):
    return a*x**2 + b*x + c
popt = [0] * 10
pcov = [0] * 10
div = [0] * 5
V_BPvec = [0] * 5
LHV = 22 # MJ/Nm3

FuelInp = np.array([[152, 209, 267],    # MGM100
                     [275, 392, 507],   # MGM200
                     [477, 673, 878],   # MGM350
                     [608, 849, 1095] , # MGM430
                     [677, 972, 1260]]) # MGM500
    
ElecPower = np.array([[49, 74, 99],     # MGM100
                      [99, 150, 200],   # MGM200
                      [177, 266, 356],  # MGM350
                      [216, 324, 432],  # MGM430
                      [251, 376, 500]]) # MGM500

TherPower = np.array ([[81, 101, 120],  # MGM100
                      [128, 169, 208],  # MGM200
                      [211, 291, 370],  # MGM350
                      [284, 377, 470],  # MGM430
                      [279, 407, 525]]) # MGM500

V_BP = FuelInp/LHV*3.6
for i in range(5):
    div[i] = (np.max(V_BP[i])-np.min(V_BP[i]))/10
    V_BPvec[i] = np.linspace(np.min(V_BP[i])-div[i], np.max(V_BP[i])+div[i], 1000)
    plt.figure ()
    plt.rc('font', family='serif')
    
    plt.plot(V_BP[i], ElecPower[i], 'kx', label=u'Elektrický výkon', markersize=8)
    plt.plot(V_BP[i], TherPower[i], 'k+', label=u'Tepelný výkon', markersize=10)
    popt[2*i], pcov[2*i] = curve_fit(func, V_BP[i], ElecPower[i])
    popt[2*i+1], pcov[2*i+1] = curve_fit(func, V_BP[i], TherPower[i])
    plt.plot(V_BPvec[i], func(V_BPvec[i], *popt[2*i]), 'k-.', label=u'MNČ EV: ax$^2$ + bx + c')
    plt.plot(V_BPvec[i], func(V_BPvec[i], *popt[2*i+1]), 'k--', label=u'MNČ TV: ax$^2$ + bx + c')
    
    
    plt.xlabel(u'Průtok bioplynu [Nm$^3$/h]')
    plt.ylabel(u'Výkon [kW]')
    plt.title(u'Aproximace tepelného a elektrického výkonu KGJ '+nazvy[i])
    plt.legend()
    plt.axvspan(np.min(V_BP[i])-2*div[i],np.min(V_BP[i]),color=(1,0,0,0.05))
    plt.axvspan(np.min(V_BP[i]),np.max(V_BP[i]),color=(0,1,0,0.05))
    plt.axvspan(np.max(V_BP[i]),np.max(V_BP[i])+2*div[i],color=(1,0,0,0.05))
    # plt.show()
    plt.savefig(nazvy[i]+'.svg', dpi=1200, transparent=True)


index = []
for i in range(5): 
    index.append (nazvy[i]+': Elektrický výkon')
    index.append (nazvy[i]+': Tepelný výkon')
columns = ['a [–]','b [–]','c [–]', 'Min BP [Nm3/h]', 'Max BP [Nm3/h]']
df = pd.DataFrame(columns=columns,index=index)
for i in range (5):
    df.iat[2*i,3] = np.min(V_BP[i])
    df.iat[2*i,4] = np.max(V_BP[i])
    for j in range (len(popt[1])):
        df.iat[2*i,j] = popt [2*i][j]
        df.iat[2*i+1,j] = popt [2*i+1][j]
#df.iat[2,3] = df.iat[0,4]

sheet_name = 'Sheet1'
writer     = pd.ExcelWriter('KGJ.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheet_name)
writer.save()
