# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernel_info:
#     name: python38-azureml
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] slideshow={"slide_type": "slide"}
# # D2E2F: ForSea meeting
# (2021-04-29)
#
# ### 1) Utveckla simuleringsmodell med Machine Learning
# ### 2) Använda simuleringsmodell för att optimera thrustrar 
#
# ### 3) Analysarbete
# #### a) Långtidsanalys: dagar/veckor/månader/år
# #### b) Förbättring med "Smart Eco-shipping"
# #### c) Korttidsanalys: farygsdynamik under resa
#
# ### 4) PhD Chalmers paper
# ### 5) "Förstå" datan
# ![](figures/I_want_to_understand.png)

# + gather={"logged": 1618500219438} slideshow={"slide_type": "skip"}
# #%load imports.py
# %matplotlib inline
# %load_ext autoreload
# %autoreload 2

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)
plt.style.use('presentation')

#import seaborn as sns
import os
from collections import OrderedDict

from IPython.display import display

pd.options.display.max_rows = 999
pd.options.display.max_columns = 999
pd.set_option("display.max_columns", None)

import folium
import plotly.express as px
import plotly.graph_objects as go

import sys
import os
sys.path.append('../')
from src.visualization import visualize, animate
sys.path.append('../src/models/pipelines/longterm/scripts/prepdata/trip')
import prepare_dataset, trips, trip_id
sys.path.append('../src/models/pipelines/longterm/scripts/prepdata/clean_statistics')
import clean_statistics


import scipy.integrate
import seaborn as sns

# + gather={"logged": 1618500116933}
experiments_path = '../notebooks/pipelines/longterm'
experiment = 'steps'
experiment_path = os.path.join(experiments_path, experiment)
file_path = os.path.join(experiment_path, 'id.parquet')
df = trip_id.load_output_pandas(path=file_path)
# -

df.head()

# ## Plot trips

# + gather={"logged": 1618500118189}
visualize.plot_trips(df=df, width=1400, height=800, zoom_start=14, color_key='trip_direction')
# -

# ## Varför åker man inte raka vägen?

# ## Trip statistics

file_path = os.path.join(experiment_path,'id_statistics_clean.parquet')
df_stat = clean_statistics.load_output_as_pandas_dataframe(path=file_path)

df_stat.head()

fig = px.scatter(df_stat, x='start_time',y='P', color='trip_direction', width=1500, height=600, 
                color_discrete_sequence=['red','green'])
fig.show()

# ## Analyzing trips

fig = px.line(df, x='trip_time', y='sog', color='trip_no', width=1500, height=800)
fig.show()

# ![](animations/trip_101.gif "101")

# + [markdown] slideshow={"slide_type": "skip"}
# ## Look at one trip

# + slideshow={"slide_type": "skip"}
trips = df.groupby(by='trip_no')
trip_no = 129
trip = trips.get_group(trip_no)

# + slideshow={"slide_type": "slide"}
visualize.plot_map(df=trip, width=1400, height=800, zoom_start=14, color_key='trip_direction')
# -

trip[[f'sin_pm{i}' for i in range(1,5)]].isnull().any()

trip[['cog','heading','sog']].isnull().any()

animate.widget(trip=trip)

# ## Is there a more optimal thruster operation?

# ![](https://memegenerator.net/img/images/15921176.jpg)

# ## Thruster positions?

# Annas definition:
#
#     Thruster 1 – NV
#     Thruster 2 – SV
#     Thruster 3 – NE
#     Thruster 4 - SE
#

# +
df_no_reverse = df.groupby('trip_no').filter(lambda x : x.iloc[0]['reversing']==0)
groups = df_no_reverse.groupby('trip_no')
trip_no_reverse =groups.get_group(list(groups.groups.keys())[0])
trip_ = animate.normalize_power(trip=trip_no_reverse)
row = trip_.iloc[500].copy()




fig,ax=plt.subplots()
fig.set_size_inches(6,6)
animate.plot_thrusters(ax=ax, row=row, positions=['NV', 'SV', 'NE', 'SE'])
ax.set_title(f'reversing:{row["reversing"]}, trip_direction: {row["trip_direction"]}');
# -

animate.widget(trip=trip, positions=['NV', 'SV', 'NE', 'SE'])

# ## Transverse force for thrusters during one trip

sin_keys = ['sin_pm%i' % n for n in range(1,5)]
cos_keys = ['cos_pm%i' % n for n in range(1,5)]
power_keys = ['power_em_thruster_%i' % n for n in range(1,5)]
columns = sin_keys + cos_keys + power_keys

g = sns.PairGrid(trip[sin_keys])
g.map_upper(sns.scatterplot)
#g.map_lower(sns.kdeplot)
g.map_diag(sns.kdeplot, lw=3, legend=False);

# ## Compare mean power for many trips

df_mean =  df.groupby('trip_no').mean()

g = sns.PairGrid(df_mean[power_keys + ['reversing']])
g.map_upper(sns.scatterplot)
#g.map_lower(sns.kdeplot)
g.map_diag(sns.kdeplot, lw=3, legend=False);

# +
df_no_reverse = df.groupby('trip_no').filter(lambda x : x.iloc[0]['reversing']==1)
groups = df_no_reverse.groupby('trip_no')
trip_no_reverse =groups.get_group(list(groups.groups.keys())[0])
trip_ = animate.normalize_power(trip=trip_no_reverse)
row = trip_.iloc[500].copy()

fig,ax=plt.subplots()
fig.set_size_inches(6,6)
animate.plot_thrusters(ax=ax, row=row)
ax.set_title(f'reversing:{row["reversing"]}, trip_direction: {row["trip_direction"]}');

# +
df_no_reverse = df.groupby('trip_no').filter(lambda x : x.iloc[0]['reversing']==0)
groups = df_no_reverse.groupby('trip_no')
trip_no_reverse =groups.get_group(list(groups.groups.keys())[0])
trip_ = animate.normalize_power(trip=trip_no_reverse)
row = trip_.iloc[500].copy()

fig,ax=plt.subplots()
fig.set_size_inches(6,6)
animate.plot_thrusters(ax=ax, row=row)
ax.set_title(f'reversing:{row["reversing"]}, trip_direction: {row["trip_direction"]}');
# -

# ## Fartygsdata?
# ![](https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/20190531_Fersea_Tycho_Brahe_Helsingor_0120_%2847981263576%29.jpg/335px-20190531_Fersea_Tycho_Brahe_Helsingor_0120_%2847981263576%29.jpg)
# * GA?
# * Max effekt på thrustrar?

# ## Nästa möte...

StarcoderdataJupyterScriptsDedupFiltered