# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_modelling.mybifacialvf.ipynb (unless otherwise specified).

__all__ = ['CHAMBERY', 'rename_cols', 'format_output_as_pvfactor', 'run_bifacialvf_simulation']

# Cell
from ..imports import *
from ..utils.tmy import read_tmy
import bifacialvf
import pvlib

# Cell
CHAMBERY = {'Name':'Chambery', 'Latitude': 45.637001, 'Longitude': 5.881, 'Elevation': 235.0, 'TZ':-1.0}

# Cell
def rename_cols(df: DataFrame, cols: list=['dni', 'dhi', 'zenith', 'azimuth', 'elevation']):
    "Rename to upper case dni and ghi cols"
    assert set(cols).issubset(df.columns.str.lower()), 'Missing columns on df'
    if not set(['DNI', 'DHI']).issubset(df.columns):
        tmy3 = (df[cols]
                .rename(columns={'dni':'DNI', 'dhi':'DHI'}))
        return tmy3
    else: return df

# Cell
def format_output_as_pvfactor(res: DataFrame, cuts: int):
    "Formats output from bifacialvf as pvfactor's one"
    front_cols = [f'No_{i+1}_RowFrontGTI' for i in range(cuts)]
    back_cols = [f'No_{i+1}_RowBackGTI' for i in range(cuts)]
    aux = pd.DataFrame(index=res.index)
    aux['qinc_front'] = res[front_cols].mean(axis=1)
    aux['qinc_back'] = res[back_cols].mean(axis=1)
    aux[back_cols] = res[back_cols]
    aux =  aux.rename(columns=dict(zip(back_cols,[f'qinc_back_{i}' for i in range(cuts-1, -1, -1)] )))
    return aux[['qinc_front', 'qinc_back']+[f'qinc_back_{i}' for i in range(cuts)]]

# Cell
def run_bifacialvf_simulation(data: DataFrame,
                          pvarray_parameters:dict={'rtr':8.,  'cellRows': 7, 'albedo':0.4},
                          gps_data:dict=CHAMBERY):
    "Run bifacialvf on data, with pvarray_parameters at location"
    outfile = 'output.csv'
    pvarray_parameters.update({'sam_header':False})
    bifacialvf.simulate_inner(rename_cols(data), gps_data, outfile, **pvarray_parameters)
    return (pd.read_csv(outfile, header=2, index_col='date', parse_dates=True)
            .pipe(format_output_as_pvfactor, cuts=pvarray_parameters['cellRows']))