# model

# import packages
import numpy as np
import pandas as pd
from pystoned import uCNLS
from pystoned.constant import CET_MULT, FUN_COST, RTS_CRS


# load data
df = pd.read_excel("Data_2012_2018.xls")

# input: KOPEX
y = df["KOPEX"]
y = np.asmatrix(y).T

# outputs (incl. bad output)
x1 = df['Energia']
x1 = np.asmatrix(x1).T
x2 = df['Verkkopituus']
x2 = np.asmatrix(x2).T
x3 = df['Käyttäjämäärä']
x3 = np.asmatrix(x3).T
x4 = -df['NKA']/1000
x4 = np.asmatrix(x4).T
x = np.concatenate((x1, x2, x3, x4), axis=1)

# bad output
b = df['KAH']
b = np.asmatrix(b).T

# contextual Variable: z
z1 = df['L/K suhde']
z1 = np.asmatrix(z1).T
z2 = df['häviösähköprosentti']
z2 = np.asmatrix(z2).T
z = np.concatenate((z1, z2), axis=1)


# define and solve the basic CNLS model
res = uCNLS.uCNLS(y, x, b, z, cet = CET_MULT, fun = FUN_COST, rts = RTS_CRS)
res.optimize()

# store the results
writer = pd.ExcelWriter('CNLS_tulokset_2012_2018.xlsx', engine='xlsxwriter')
pd.DataFrame(res.get_beta()).to_excel(writer, sheet_name='beta')
pd.DataFrame(res.get_delta()).to_excel(writer, sheet_name='delta')
pd.DataFrame(res.get_lamda()).to_excel(writer, sheet_name='lamda')
pd.DataFrame(res.get_residual()).to_excel(writer, sheet_name='residual')

writer.save()
