#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Paying extra for better wind nearshore

Using a sample of wind power projects in Vietnam investment cost,
assess how much more expensive is installed capacity nearshore vs. onshore.

Created on Tue Jan 19 11:40:05 2021

@author: haduong@centre-cired.fr

"""

import random
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import mannwhitneyu, ks_2samp
import statsmodels.api as sm

from windprojects import data


def info(*s):
    """Control output verbosity by commenting/uncommenting."""
#    print(s)


# %% Take the sample.

data = data.loc[data['capacity'] >= 5]    # Drop small projects <5MW
data.dropna(subset=['Location type'], inplace=True)
data.dropna(subset=['investment'], inplace=True)

# %% Define the variable of interest.

data['technology cost'] = data['investment'] / data['capacity']

# %% Display tables, optional.

info("Whole sample", data.describe())

onshore = data.loc[data['Location type'] == 'Onshore']
info("Onshore", onshore.describe())

nearshore = data.loc[data['Location type'] == 'Intertidal']
info("Nearshore", nearshore.describe())

offshore = data.loc[data['Location type'] == 'Offshore']
info("Offshore", offshore.describe())

# %% Print the quantiles and the variation of median.

print()
print('Onshore USD/kWv quartiles:')
print(onshore['technology cost'].quantile([0.25, 0.5, 0.75]))

print()
print('Nearshore USD/kWv quartiles:')
print(nearshore['technology cost'].quantile([0.25, 0.5, 0.75]))

x = onshore['technology cost'].median()
y = nearshore['technology cost'].median()
print()
print('Variation of median', int(100*(y-x)/x), '%')

print()
print(mannwhitneyu(onshore['technology cost'], nearshore['technology cost']))
print(ks_2samp(onshore['technology cost'], nearshore['technology cost']))

# %% Compare the slope of the ordinary regressions.

y = onshore['investment']
x = onshore['capacity']
model = sm.OLS(y, x).fit()
info('Onshore, no intercept', model.summary())
slope_onshore = model.params

y = nearshore['investment']
x = nearshore['capacity']
model = sm.OLS(y, x).fit()
info('nearshore, no intercept', model.summary())
slope_nearshore = model.params

slope_variation = (slope_nearshore - slope_onshore)/slope_onshore
print()
print('Onshore slope', slope_onshore)
print('Nearshore slope', slope_nearshore)
print('Variation of slope', int(100*(slope_variation)), '%')

# %% Compare the cost of a random an nearshore MW / random onshore MW.

size = 30000
onshore_sample = random.choices(onshore['technology cost'],
                                weights=onshore['capacity'],
                                k=size)
nearshore_sample = random.choices(nearshore['technology cost'],
                                  weights=nearshore['capacity'],
                                  k=size,
                                  )
ratio = [(i - j) / j for i, j in zip(nearshore_sample, onshore_sample)]
dist_variation = pd.Series(ratio)
info(dist_variation.describe())

print()
print('Average variation', int(100*dist_variation.mean()), '%')
print('Quartiles:')
print(dist_variation.quantile([0.25, 0.75]))


# %% Plot the sample in capacity/investment plane, marking for station type.

fig1 = plt.figure()
ax = fig1.add_axes([0, 0, 1, 1])
ax.scatter(offshore['capacity'], offshore['investment'],
           marker='o', label='Offshore')
ax.scatter(nearshore['capacity'], nearshore['investment'],
           marker='*', label='Nearshore')
ax.scatter(onshore['capacity'], onshore['investment'],
           marker='.', label='Onshore')
ax.set_title('Vietnam wind power projects')
ax.set_xlabel('Capacity (MWp)')
ax.set_ylabel('Investment cost (million USD)')
ax.set_xscale('log')
ax.set_yscale('log')
xtks = [30, 50, 100, 300, 500, 1000]
ax.set_xticks(xtks)
ax.set_xticklabels(xtks)
ytks = [50, 100, 500, 1000, 2000]
ax.set_yticks(ytks)
ax.set_yticklabels(ytks)
ax.set_ylim(10, 2000)
ax.legend(frameon=False)
fig1.savefig('figure1', bbox_inches="tight")
plt.show()

# %% Plot quantiles of capacity, investment, technology cost,. By station type.

fig2, (ax0, ax1, ax2) = plt.subplots(3, 1, figsize=(8, 12))
ax0.boxplot((onshore['technology cost'],
             nearshore['technology cost'],
             offshore['technology cost']),
            labels=['Onshore', 'Nearshore', 'Offshore'])
ax0.set_ylabel('Technology cost (M$/MW)')
ax1.boxplot((onshore['capacity'],
             nearshore['capacity'],
             offshore['capacity']),
            labels=['Onshore', 'Nearshore', 'Offshore'])
ax1.set_ylabel('Capacity (MW)')
ax2.boxplot((onshore['investment'],
             nearshore['investment'],
             offshore['investment']),
            labels=['Onshore', 'Nearshore', 'Offshore'])
ax2.set_ylabel('investment (M$)')
ax2.set_yscale('log')
ax2.set_yticklabels(ytks)
ax2.set_ylim(10, 2000)
fig2.savefig('figure2', bbox_inches="tight")
plt.show()
