#%% Plotting EWR Flume Tests

# Alexander Rey, 2022

#%% Import
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import geopandas as gp
gp.options.use_pygeos = True
from shapely import geometry, ops

# Map Plotting
import cartopy.crs as ccrs
import contextily as ctx

# Interpolation
import scipy as sp
from scipy.interpolate import griddata

from scipy.interpolate import LinearNDInterpolator, interp1d

from dfm_tools.get_nc import get_netdata, get_ncmodeldata, plot_netmapdata
from dfm_tools.get_nc_helpers import get_timesfromnc, get_ncfilelist, get_hisstationlist, get_ncvardimlist, get_timesfromnc
import pathlib as pl

import datetime
#%% Read Model Log

# runLog = pd.read_excel("Y:/12828.101 English Wabigoon River/06_Models/00_Delft3D/ModelRuns.xlsx", "Sensitivity")
pth = pl.Path("//srv-ott3.baird.com/", "Projects", "12828.101 English Wabigoon River", "06_Models", "00_Delft3D", "ModelRuns.xlsx")
runLog = pd.read_excel(pth.as_posix(), "Sensitivity")

dataPath = "FlowFM_map.nc"

#%% Read in centerline shapefile
river_centerline = gp.read_file('//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/03_Data/02_Physical/16_Waterline/Centerline_for_Modelling_UTMZ15.shp')

river_centerlineExploded = river_centerline.explode(ignore_index=True)
river_centerlineExploded.reset_index(inplace=True)

tempMulti = river_centerlineExploded.iloc[[5,0,1,2,3,4,6,7,9], 4]
# Put the sub-line coordinates into a list of sublists
outcoords = [list(i.coords) for i in tempMulti]
# Flatten the list of sublists and use it to make a new line
river_centerline_merge = geometry.LineString([i for sublist in outcoords for i in sublist])
river_centerline_merge_gpd = gp.GeoSeries(river_centerline_merge)

river_centerline_merge_gpd2 =\
    gp.GeoDataFrame(geometry=gp.points_from_xy(
        river_centerline_merge.xy[0], river_centerline_merge.xy[1], crs="EPSG:32615"))

# Add distance along centerline
river_centerline_merge_gpd2['DistanceFromPrevious'] = river_centerline_merge_gpd2.distance(river_centerline_merge_gpd2.shift(1))
river_centerline_merge_gpd2['RiverKM'] = river_centerline_merge_gpd2['DistanceFromPrevious'].cumsum()
river_centerline_merge_gpd2.iloc[0, 1] = 0
river_centerline_merge_gpd2.iloc[0, 2] = 0

#%% Import Validation Data

# Read in combined dataset
obs_IN = pd.read_csv("//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/05_Analyses/02_Data Analysis/output/combined dataset-SGJ.csv")
# Add Datetime
obs_IN['DateTime'] = pd.to_datetime(obs_IN.Sampledate_x)

# Convert to geodataframe
obs_gdf = gp.GeoDataFrame(obs_IN, geometry=gp.points_from_xy(
                obs_IN.loc[:, 'Longitude'], obs_IN.loc[:, 'Latitude'], crs="EPSG:4326")).to_crs(crs="EPSG:32615")

# Add centerline and reset index
obs_gdf = gp.sjoin_nearest(river_centerline_merge_gpd2, obs_gdf, how='right', max_distance=250).reset_index()

# Sediment Hg GeoDataFrame where media is Sediment
obsMask = (((obs_gdf.Media_x == 'SED') | (obs_gdf.Media_x == 'SOIL')) &
           ((obs_gdf.Parameter == 'Mercury') | (obs_gdf.Parameter == 'Mercury (Hg) Total')
            | (obs_gdf.Parameter == 'Total Mercury') | (obs_gdf.Parameter == 'Mercury (Hg)')) &
            (obs_gdf.DateTime > datetime.datetime(2000, 1, 1)) & obs_gdf.RiverKM.notna())

obs_HgSed = obs_gdf.loc[obsMask, :]

# Adjust Units
obs_HgSed.loc[obs_HgSed.Unit == 'NG/G', 'Sample_NG/G'] = obs_HgSed.Samplevalue
obs_HgSed.loc[obs_HgSed.Unit == 'ng/g', 'Sample_NG/G'] = obs_HgSed.Samplevalue
obs_HgSed.loc[obs_HgSed.Unit == 'UG/G', 'Sample_NG/G'] = obs_HgSed.Samplevalue * 1000
obs_HgSed.loc[obs_HgSed.Unit == 'ug/g', 'Sample_NG/G'] = obs_HgSed.Samplevalue * 1000
obs_HgSed.loc[obs_HgSed.Unit == 'MG/KG', 'Sample_NG/G'] = obs_HgSed.Samplevalue * 0.001
obs_HgSed.loc[obs_HgSed.Unit == 'mg/kg', 'Sample_NG/G'] = obs_HgSed.Samplevalue * 0.001

# obs_HgSed.to_file('C:/Users/arey/files/Projects/Grassy Narrows/LocalData/HgSedDB2.geojson', driver="GeoJSON")

# Group sediment core data to take average/min/max
obs_HgSed_Avg = obs_HgSed.groupby(['Sitecode', 'DateTime']).agg({'Sample_NG/G': ['mean', 'min', 'max'],
                                                                'RiverKM': ['mean'],
                                                                'Longitude': ['mean'],
                                                                'Latitude': ['mean'],
                                                                'DateTime': ['mean']}).reset_index()
# Merge Index
obs_HgSed_Avg.columns = obs_HgSed_Avg.columns.map('|'.join).str.strip('|')

# Fix Names
obs_HgSed_Avg.rename(columns={"RiverKM|mean": "RiverKM", "Longitude|mean": "Longitude",
                              "Latitude|mean": "Latitude", "DateTime|mean": "DateTime"}, inplace=True)

# Create new GeoDataFrame
obs_HgSed_Avg = gp.GeoDataFrame(obs_HgSed_Avg, geometry=gp.points_from_xy(
                obs_HgSed_Avg.loc[:, 'Longitude'], obs_HgSed_Avg.loc[:, 'Latitude'], crs="EPSG:4326")).to_crs(crs="EPSG:32615")



# Water Hg GeoDataFrame where media is SurfaceWater (SW)
obsMask = (((obs_gdf.Media_x == 'SW')) &
           ((obs_gdf.Parameter == 'Mercury') | (obs_gdf.Parameter == 'Mercury (Hg)-Total')
            | (obs_gdf.Parameter == 'Total Mercury') | (obs_gdf.Parameter == 'Mercury (Hg)')) &
            (obs_gdf.DateTime > datetime.datetime(2000, 1, 1)) & obs_gdf.RiverKM.notna())

obs_HgWater = obs_gdf.loc[obsMask, :]
# Adjust Units
obs_HgWater.loc[obs_HgWater.Unit == 'NG/L', 'Sample_NG/L'] = obs_HgWater.Samplevalue
obs_HgWater.loc[obs_HgWater.Unit == 'ng/L', 'Sample_NG/L'] = obs_HgWater.Samplevalue
obs_HgWater.loc[obs_HgWater.Unit == 'UG/L', 'Sample_NG/L'] = obs_HgWater.Samplevalue * 1000
obs_HgWater.loc[obs_HgWater.Unit == 'ug/L', 'Sample_NG/L'] = obs_HgWater.Samplevalue * 1000
obs_HgWater.loc[obs_HgWater.Unit == 'MG/L', 'Sample_NG/L'] = obs_HgWater.Samplevalue * 1000000
obs_HgWater.loc[obs_HgWater.Unit == 'mg/L', 'Sample_NG/L'] = obs_HgWater.Samplevalue * 1000000


# Import Sediment MeHg
# Sediment MeHg GeoDataFrame
obsMask = (((obs_gdf.Media_x == 'SED') | (obs_gdf.Media_x == 'SOIL')) &
           ((obs_gdf.Parameter == 'Methylmercury (as MeHg)') | (obs_gdf.Parameter == 'Methyl mercury')) &
            (obs_gdf.DateTime > datetime.datetime(2000, 1, 1)) & obs_gdf.RiverKM.notna())

obs_MeHgSed = obs_gdf.loc[obsMask, :]

# Adjust Units
obs_MeHgSed.loc[obs_MeHgSed.Unit == 'NG/G', 'Sample_NG/G'] = obs_MeHgSed.Samplevalue
obs_MeHgSed.loc[obs_MeHgSed.Unit == 'ng/g', 'Sample_NG/G'] = obs_MeHgSed.Samplevalue
obs_MeHgSed.loc[obs_MeHgSed.Unit == 'UG/G', 'Sample_NG/G'] = obs_MeHgSed.Samplevalue * 1000
obs_MeHgSed.loc[obs_MeHgSed.Unit == 'ug/g', 'Sample_NG/G'] = obs_MeHgSed.Samplevalue * 1000
obs_MeHgSed.loc[obs_MeHgSed.Unit == 'MG/KG', 'Sample_NG/G'] = obs_MeHgSed.Samplevalue * 0.001
obs_MeHgSed.loc[obs_MeHgSed.Unit == 'mg/kg', 'Sample_NG/G'] = obs_MeHgSed.Samplevalue * 0.001

# Group sediment core data to take average/min/max
obs_MeHgSed_Avg = obs_MeHgSed.groupby(['Sitecode', 'DateTime']).agg({'Sample_NG/G': ['mean', 'min', 'max'],
                                                                'RiverKM': ['mean'],
                                                                'Longitude': ['mean'],
                                                                'Latitude': ['mean'],
                                                                'DateTime': ['mean']}).reset_index()
# Merge Index
obs_MeHgSed_Avg.columns = obs_MeHgSed_Avg.columns.map('|'.join).str.strip('|')

# Fix Names
obs_MeHgSed_Avg.rename(columns={"RiverKM|mean": "RiverKM", "Longitude|mean": "Longitude",
                              "Latitude|mean": "Latitude", "DateTime|mean": "DateTime"}, inplace=True)

# Create new GeoDataFrame
obs_MeHgSed_Avg = gp.GeoDataFrame(obs_MeHgSed_Avg, geometry=gp.points_from_xy(
                obs_MeHgSed_Avg.loc[:, 'Longitude'], obs_MeHgSed_Avg.loc[:, 'Latitude'], crs="EPSG:4326")).to_crs(crs="EPSG:32615")




# MeHg in Water
obsMask = (((obs_gdf.Media_x == 'SW')) &
           ((obs_gdf.Parameter == 'Methylmercury (as MeHg)') | (obs_gdf.Parameter == 'Methyl mercury')) &
            (obs_gdf.DateTime > datetime.datetime(2000, 1, 1)) & obs_gdf.RiverKM.notna())

obs_MeHgWater = obs_gdf.loc[obsMask, :]
# Adjust Units
obs_MeHgWater.loc[obs_MeHgWater.Unit == 'NG/L', 'Sample_NG/L'] = obs_MeHgWater.Samplevalue
obs_MeHgWater.loc[obs_MeHgWater.Unit == 'ng/L', 'Sample_NG/L'] = obs_MeHgWater.Samplevalue
obs_MeHgWater.loc[obs_MeHgWater.Unit == 'UG/L', 'Sample_NG/L'] = obs_MeHgWater.Samplevalue * 1000
obs_MeHgWater.loc[obs_MeHgWater.Unit == 'ug/L', 'Sample_NG/L'] = obs_MeHgWater.Samplevalue * 1000
obs_MeHgWater.loc[obs_MeHgWater.Unit == 'MG/L', 'Sample_NG/L'] = obs_MeHgWater.Samplevalue * 1000000
obs_MeHgWater.loc[obs_MeHgWater.Unit == 'mg/L', 'Sample_NG/L'] = obs_MeHgWater.Samplevalue * 1000000

#%% Plot Observations
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(30, 15))

axes.set_xlim(494649, 513647)
axes.set_ylim(5514653, 5525256)

# Add basemap
mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckemxgtk51fgp19nybfmdcb1e/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'
ctx.add_basemap(axes, source=mapbox, crs='EPSG:26915')

obs_HgSed_Avg.plot(column='Sample_NG/G|mean', axes=axes, vmin=0, vmax=10000)

plt.show()

#%% Plot Profiles
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(7, 7))
obs_HgSed.plot.scatter('RiverKM', 'TopDepth_x', 12, 'Sample_NG/G', ax=axes, vmax=20000)

axes.invert_yaxis()
axes.set_xlabel('Distance Along River [m]')
axes.set_ylabel('Sample Depth [m]')
axes.set_xlim([0, 100000])

plt.show()

# fig.savefig("//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/05_Analyses/02_Data Analysis/Figures/HgDepthWide.png",
#             bbox_inches='tight', dpi=200)



#%% Interpolate Hg to grid

# Read in model points and roughness
bathy_xyz = pd.read_csv('C:/Users/arey/files/Projects/Grassy Narrows/LocalData/Bed_Level.xyz',
                        names=['x', 'y', 'z'], header=0, delim_whitespace=True)

rough_xyz = pd.read_csv('C:/Users/arey/files/Projects/Grassy Narrows/LocalData/Roughness.xyz',
                        names=['x', 'y', 'z'], header=0, delim_whitespace=True)

# Loop through parameters
for i in range(0, 5):
    if i == 0:
        dataOUT  = obs_HgSed_Avg['Sample_NG/G|mean']
        dataOutx = obs_HgSed_Avg.geometry.x
        dataOuty = obs_HgSed_Avg.geometry.y
        dateFileName = 'HgSed_meanDB'
    elif i == 1:
        dataOUT  = obs_MeHgSed_Avg['Sample_NG/G|mean']
        dataOutx = obs_MeHgSed_Avg.geometry.x
        dataOuty = obs_MeHgSed_Avg.geometry.y
        dateFileName = 'MeHgSed_meanDB'
    elif i == 2:
        dataOUT  = obs_HgWater['Sample_NG/L']
        dataOutx = obs_HgWater.geometry.x
        dataOuty = obs_HgWater.geometry.y
        dateFileName = 'HgWater_allDB'
    elif i == 3:
        dataOUT  = obs_MeHgWater['Sample_NG/L']
        dataOutx = obs_MeHgWater.geometry.x
        dataOuty = obs_MeHgWater.geometry.y
        dateFileName = 'MeHgWater_allDB'
    elif i == 4:
        # Synthetic from Reed's Sheet
        dataOUT  = ((10 - 1) * np.exp(-0.08 * np.array(river_centerline_merge_gpd2.loc[:, 'RiverKM']) / 1000) + 1) * 1000
        dataOutx = river_centerline_merge_gpd2.geometry.x
        dataOuty = river_centerline_merge_gpd2.geometry.y
        dateFileName = 'ReedHgSed'

    gridInterp = griddata(np.array([dataOutx, dataOuty]).T, dataOUT, np.array([bathy_xyz.x, bathy_xyz.y]).T,
                                        method='nearest')

    gridInterpOut = np.vstack((bathy_xyz.x, bathy_xyz.y, gridInterp))
    gridInterpOut = np.transpose(gridInterpOut)

    # Set Wetlands to zero
    # Interpolate Roughness
    RoughInterp = sp.interpolate.griddata(np.transpose(np.array([rough_xyz.x, rough_xyz.y])), rough_xyz.z, np.transpose(np.array([bathy_xyz.x, bathy_xyz.y])),
                                        method='nearest')

    gridInterpOut[RoughInterp==0.05, 2] = 0

    np.savetxt('C:/Users/arey/files/Projects/Grassy Narrows/LocalData/' + dateFileName + '.xyz',
               gridInterpOut, delimiter=" ")



#%% Import using DFM Functions

modelPlot  = 27

## Degine import path
# file_nc_map = pl.Path(runLog['Run Location'][modelPlot], 'Water_Quality', 'output', 'deltashell_map.nc')
# file_nc_map = pl.Path("//ott-diomedes.baird.com/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_42_WAQ.dsproj_data/Water_Quality/output/deltashell_map.nc")
# file_nc_map = pl.Path("//ott-diomedes.baird.com/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_42B_WAQ_Coverage.dsproj_data/Water_Quality/output/deltashell_map.nc")
# file_nc_map = pl.Path("//ott-diomedes.baird.com/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_42C_WAQ_Coverage2.dsproj_data/Water_Quality/output/deltashell_map.nc")
#file_nc_map   = pl.Path("//ott-diomedes.baird.com/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_42E_WAQ_DIDO.dsproj_data/Water_Quality/output/deltashell_map.nc")
# file_nc_map = pl.Path("//ott-diomedes/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_43_OceanMesh5_B.dsproj_data/Water_Quality/output/deltashell_map.nc")
# file_nc_map = pl.Path("D:/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_43_OceanMesh5_D.dsproj_data/Water_Quality/output/deltashell_map.nc")
#file_nc_map = pl.Path("D:/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_43_OceanMesh5_E.dsproj_data/Water_Quality/output/deltashell_map.nc")
# file_nc_map = pl.Path("//oak-inundation/D/Projects/12828.101_EWR_Delft3FM/TR_42_WAQ/TR_44_OceanMesh5.dsproj_data/Water_Quality/output/deltashell_map.nc")

# file_nc_map = pl.Path("//oak-inundation/D/Projects/12828.101_EWR_Delft3FM/Flume/RiverFlumeHD50.dsproj_data/Water_Quality/output/deltashell_map.nc")
file_nc_map = pl.Path("//oak-inundation/D/Projects/12828.101_EWR_Delft3FM/Flume/RiverFlumeArg_Test2/deltashell_map.nc")


tSteps = get_timesfromnc(file_nc=file_nc_map, varname='time')

# Print file variables
A = get_ncvardimlist(file_nc_map.as_posix())
# print(A)

# Define extraction variables
dataVars = ['FrHgIM1',   'FrHgIM2',   'FrHgIM3',   'FrHgDOC', 'FrHgPOC',   'FrHgPHYT',   'FrHgDis',
            'FrHgIM1S1', 'FrHgIM2S1', 'FrHgIM3S1', 'FrHgDOCS1', 'FrHgPOCS1', 'FrHgPHYTS1', 'FrHgDisS1',
            'FrHgIM1S2', 'FrHgIM2S2', 'FrHgIM3S2', 'FrHgDOCS2', 'FrHgPOCS2', 'FrHgPHYTS2', 'FrHgDisS2',
            'FrMmIM1',   'FrMmIM2',   'FrMmIM3',   'FrMmDOC',   'FrMmPOC',   'FrMmPHYT',   'FrMmDis',
            'FrMmIM1S1', 'FrMmIM2S1', 'FrMmIM3S1', 'FrMmDOCS1', 'FrMmPOCS1', 'FrMmPHYTS1', 'FrMmDisS1',
            'FrMmIM1S2', 'FrMmIM2S2', 'FrMmIM3S2', 'FrMmDOCS2', 'FrMmPOCS2', 'FrMmPHYTS2', 'FrMmDisS2',
            'IM1', 'IM2', 'IM3', 'Hg', 'Mm', 'H0', 'POC1', 'POC2',
            'IM1S1', 'IM2S1', 'IM3S1', 'HgS1', 'MmS1', 'DetCS1', 'OOCS1',
            'IM1S2', 'IM2S2', 'IM3S2', 'HgS2', 'MmS2', 'DetCS2', 'OOCS2',
            'fResS1IM1',  'fSedIM1',  'fResS1IM2', 'fSedIM2',
            'fResS1DetC', 'fSedPOC1', 'fResS1OOC', 'fSedPOC2',
            'fSedDM', 'fResS1DM', 'fDigS1DM', 'fBurS1DM', 'fDigS2DM', 'fBurS2DM',
            'fSedHg', 'fResS1Hg', 'fSedMm', 'fResS1Mm',
            'HgHgS1O', 'MmMmS1O',
            'HgMmO', 'HgS1MmS1O', 'MmHgO', 'MmS1HgS1O',
            'fBurS1Hg', 'fDigS1Hg', 'fBurS1Mm', 'fDigS1Mm',
            'oPhoDeg', 'oPhoOxy', 'oPhoRed',
            'f_minPOC1', 'MnODCS1', 'Continuity',
            'volume', 'Depth']

# Define if sediment or water variable
# Read depth average for water and bottom layer for sediment
sedTerms = ['S1', 'S2', 'Sed', 'Res', 'Bur', 'Dig']

# Create Pandas Output Array
dataIN_x = get_ncmodeldata(file_nc=file_nc_map.as_posix(),
                         varname='mesh2d_face_x',
                         silent=True)
dataIN_y = get_ncmodeldata(file_nc=file_nc_map.as_posix(),
                         varname='mesh2d_face_y',
                         silent=True)

dataIN_gp = gp.GeoDataFrame(geometry=gp.points_from_xy(dataIN_x, dataIN_y, crs="EPSG:32615"))


# Extract variables
for vIDX, v in enumerate(dataVars):
    # Extract data from NetCDF file

    # If sediment variable read full 3d variable and then use the values from the bottom layer
    if any(s in v for s in sedTerms):
        dataIN = get_ncmodeldata(file_nc=file_nc_map.as_posix(),
                                 varname='mesh2d_' + v, timestep=len(tSteps) - 2,
                                 silent=True)  # ,  #mesh2d_agg_2d_

        dataIN_gp[v] = np.array(dataIN[0][5][:])

    # Else (Water) read 2d variable
    else:
        dataIN = get_ncmodeldata(file_nc=file_nc_map.as_posix(),
                                 varname='mesh2d_2d_' + v, timestep=len(tSteps) - 2,
                                 silent=True)  # ,  #mesh2d_agg_2d_

        dataIN_gp[v] = np.array(dataIN[0][:])

    # Add data to Pandas Array
    # For 2D Runs
    # dataIN_gp[v] = np.array(dataIN[0][0][:])

    # For 3D Runs
    # dataIN_gp[v] = np.array(dataIN[0][:])

    print(v)
#

#%% Create Dataframe along river centerline for plotting
dataOUT = gp.sjoin_nearest(river_centerline_merge_gpd2, dataIN_gp, how='left', max_distance=100)
dataOUT.set_index('RiverKM', inplace=True)

#%% Create Dataframe along Flume for plotting
dataOUT = dataIN_gp
dataOUT['RiverKM'] = dataIN_x
dataOUT.set_index('RiverKM', inplace=True)

#%% Read in river sections shapefile
river_sections_shp = 'C:/Users/arey/files/Projects/Grassy Narrows/GIS/RiverSegmentsModel.shp'
river_sections = gp.read_file(river_sections_shp)

river_sections_names = ['1_Dryden', '2_RugbyCreek', 'Eagle_River', 'Full_Domain']

#%% Sum data over area
# Identify 2d flux variables
fluxVars2d = ['fSedHg', 'fResS1Hg', 'fSedMm', 'fResS1Mm',
              'fBurS1Hg', 'fDigS1Hg', 'fBurS1Mm', 'fDigS1Mm',
              'HgS1MmS1O', 'MmS1HgS1O',
              'fSedDM', 'fResS1DM',
              'fDigS1DM', 'fBurS1DM', 'fDigS2DM', 'fBurS2DM']

# Create geoDataFrame for summing
dataSum_2d_gp = gp.GeoDataFrame(geometry=gp.points_from_xy(dataIN_x, dataIN_y, crs="EPSG:32615"))

# Area = Volumne / Depth
dataSum_2d_gp['Area'] = dataIN_gp['volume'] / dataIN_gp['Depth']

# Create dict for summing
dataSum_2d = dict()

# Loop through river sections shapefile
for rIDX, rSHP in enumerate(river_sections.geometry):
    # Create dict for summing
    dataSum_2d[river_sections_names[rIDX]] = dict()

    for vIDX, v in enumerate(fluxVars2d):
        # Change from g/day to ng/day
        dataSum_2d[river_sections_names[rIDX]][v] =  sum(dataIN_gp.loc[dataIN_gp.within(rSHP), v] *
                                                         dataSum_2d_gp.loc[dataIN_gp.within(rSHP), 'Area']) * 1e9

# Convert to Pandas DataFrame
dataSum_2d_pd = pd.DataFrame(dataSum_2d)
# dataSum_2d_pd.to_excel('C:/Users/arey/files/Projects/Grassy Narrows/Modelling/ModelOutput/GrassyNarrows_2dFluxes.xlsx')

#%% Sum data over water volumne

# Identify 3d flux variables
fluxVars3d = ['oPhoOxy', 'oPhoRed', 'oPhoDeg',
              'HgMmO', 'MmHgO']

# Create dict for summing
dataSum_3d = dict()
# Loop through river sections shapefile
for rIDX, rSHP in enumerate(river_sections.geometry):
    # Create dict for summing
    dataSum_3d[river_sections_names[rIDX]] = dict()

    for vIDX, v in enumerate(fluxVars3d):
        # Change from g/day to ng/day
        dataSum_3d[river_sections_names[rIDX]][v] = sum(dataIN_gp.loc[dataIN_gp.within(rSHP), v] /
                                                        dataIN_gp.loc[dataIN_gp.within(rSHP), 'volume'])* 1e9

# Convert to Pandas DataFrame
dataSum_3d_pd = pd.DataFrame(dataSum_3d)
# dataSum_3d_pd.to_excel('C:/Users/arey/files/Projects/Grassy Narrows/Modelling/ModelOutput/GrassyNarrows_3dFluxes.xlsx')

#%% Plot Partition Data

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 9))
fig.patch.set_facecolor('white')
fig.tight_layout(pad=3)
ax = axes.flat

#Hg Parition in Water
ax[0].set_title('Hg Fraction in Water')
ax[0].plot(dataOUT.index, dataOUT['FrHgIM1'], linewidth=3, label='IM1')
ax[0].plot(dataOUT.index, dataOUT['FrHgIM2'], linewidth=3, label='IM2')
ax[0].plot(dataOUT.index, dataOUT['FrHgIM3'], linewidth=3, label='IM3')
ax[0].plot(dataOUT.index, dataOUT['FrHgPOC'], linewidth=3, label='POC')
ax[0].plot(dataOUT.index, dataOUT['FrHgDOC'], linewidth=3, label='DOC')
ax[0].plot(dataOUT.index, dataOUT['FrHgPHYT'], linewidth=3, label='PHYT')
ax[0].plot(dataOUT.index, dataOUT['FrHgDis'], linewidth=3, label='Dissolved')

ax[0].legend()
ax[0].set_ylabel('Percentage Hg')
ax[0].set_xlabel('Distance Along River [m]')
ax[0].set_ylim([0, 1])


#Mm Parition in Water
ax[1].set_title('MeHg Fraction in Water')
ax[1].plot(dataOUT.index, dataOUT['FrMmIM1'], linewidth=3, label='IM1')
ax[1].plot(dataOUT.index, dataOUT['FrMmIM2'], linewidth=3, label='IM2')
ax[1].plot(dataOUT.index, dataOUT['FrMmIM3'], linewidth=3, label='IM3')
ax[1].plot(dataOUT.index, dataOUT['FrMmPOC'], linewidth=3, label='POC')
ax[1].plot(dataOUT.index, dataOUT['FrMmDOC'], linewidth=3, label='DOC')
ax[1].plot(dataOUT.index, dataOUT['FrMmPHYT'], linewidth=3, label='PHYT')
ax[1].plot(dataOUT.index, dataOUT['FrMmDis'], linewidth=3, label='Dissolved')

ax[1].legend()
ax[1].set_ylabel('Percentage MeHg')
ax[1].set_xlabel('Distance Along River [m]')
ax[1].set_ylim([0, 1])

#Hg Parition in S1
ax[2].set_title('Hg Fraction in Sediment')
ax[2].plot(dataOUT.index, dataOUT['FrHgIM1S1'], linewidth=3, label='IM1')
ax[2].plot(dataOUT.index, dataOUT['FrHgIM2S1'], linewidth=3, label='IM2')
ax[2].plot(dataOUT.index, dataOUT['FrHgIM3S1'], linewidth=3, label='IM3')
ax[2].plot(dataOUT.index, dataOUT['FrHgPOCS1'], linewidth=3, label='POC')
ax[2].plot(dataOUT.index, dataOUT['FrHgDOCS1'], linewidth=3, label='DOC')
ax[2].plot(dataOUT.index, dataOUT['FrHgPHYTS1'], linewidth=3, label='PHYT')
ax[2].plot(dataOUT.index, dataOUT['FrHgDisS1'], linewidth=3, label='Dissolved')

ax[2].legend()
ax[2].set_ylabel('Percentage Hg')
ax[2].set_xlabel('Distance Along River [m]')
ax[2].set_ylim([0, 1])

#Mm Parition in S1
ax[3].set_title('MeHg Fraction in Sediment')
ax[3].plot(dataOUT.index, dataOUT['FrMmIM1S1'], linewidth=3, label='IM1')
ax[3].plot(dataOUT.index, dataOUT['FrMmIM2S1'], linewidth=3, label='IM2')
ax[3].plot(dataOUT.index, dataOUT['FrMmIM3S1'], linewidth=3, label='IM3')
ax[3].plot(dataOUT.index, dataOUT['FrMmPOCS1'], linewidth=3, label='POC')
ax[3].plot(dataOUT.index, dataOUT['FrMmDOCS1'], linewidth=3, label='DOC')
ax[3].plot(dataOUT.index, dataOUT['FrMmPHYTS1'], linewidth=3, label='PHYT')
ax[3].plot(dataOUT.index, dataOUT['FrMmDisS1'], linewidth=3, label='Dissolved')

ax[3].legend()
ax[3].set_ylabel('Percentage MeHg')
ax[3].set_xlabel('Distance Along River [m]')
ax[3].set_ylim([0, 1])
plt.show()

# fig.savefig('//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/12_WAQ/FullDomainFigures/Partitioning.png',
#              bbox_inches='tight', dpi=200)


#%% Plot Total Data

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 9))
fig.patch.set_facecolor('white')
fig.tight_layout(pad=3)
ax = axes.flat

#Hg in Water
ax[0].set_title('Hg in Water')
ax[0].plot(dataOUT.index, dataOUT['Hg'] * 1000000, linewidth=3, label='Hg')
ax[0].scatter(obs_HgWater.RiverKM, obs_HgWater['Sample_NG/L'], 5, label='Hg Obs', color='k')
ax[0].set_xlim([0, 100000])
ax[0].set_ylim([0, 100])

ax[0].legend()
ax[0].set_ylabel('Hg [ng/L]')
ax[0].set_xlabel('Distance Along River [m]')


# MeHg in Water
ax[1].set_title('MeHg in Water')
ax[1].plot(dataOUT.index, dataOUT['Mm'] * 1000000, linewidth=3, label='MeHg')
ax[1].scatter(obs_MeHgWater.RiverKM, obs_MeHgWater['Sample_NG/L'], 5, label='Hg Obs', color='k')
ax[1].set_xlim([0, 100000])
ax[1].set_ylim([0, 3])

ax[1].legend()
ax[1].set_ylabel('MeHg [ng/L]')
ax[1].set_xlabel('Distance Along River [m]')

#Hg in Sediment
ax[2].set_title('Hg in Sediment')
ax[2].plot(dataOUT.index, dataOUT['HgS1'] * 1*10 ** 9 / (dataOUT['IM1S1'] + dataOUT['IM2S1'] + dataOUT['IM3S1'] + dataOUT['DetCS1'] + dataOUT['OOCS1']),
           linewidth=3, label='HgS1')
ax[2].scatter(obs_HgSed_Avg.RiverKM, obs_HgSed_Avg['Sample_NG/G|mean'], 5, label='Hg Obs', color='k')
ax[2].set_xlim([0, 100000])
ax[2].set_ylim([0, 20000])

ax[2].legend()
ax[2].set_ylabel('HgS1 [ng/g]')
ax[2].set_xlabel('Distance Along River [m]')


# MeHg in Sediment
ax[3].set_title('MeHg in Sediment')
ax[3].plot(dataOUT.index, dataOUT['MmS1'] * 1*10 ** 9 / (dataOUT['IM1S1'] + dataOUT['IM2S1'] + dataOUT['IM3S1'] + dataOUT['DetCS1'] + dataOUT['OOCS1']),
           linewidth=3, label='MeHgS1')
ax[3].scatter(obs_MeHgSed_Avg.RiverKM, obs_MeHgSed_Avg['Sample_NG/G|mean'], 5, label='MeHg Obs', color='k')
ax[3].set_ylim([0, 60])
ax[3].set_xlim([0, 100000])

ax[3].legend()
ax[3].set_ylabel('MeHg [ng/g]')
ax[3].set_xlabel('Distance Along River [m]')

# ax[3].set_title('Continuity')
# ax[3].plot(dataOUT.index, dataOUT['Continuity'],
#            linewidth=3, label='Continuity')
# ax[3].set_ylim([0, 1])
#
# ax[3].legend()
# ax[3].set_ylabel('Continuity [-]')
# ax[3].set_xlabel('Distance Along Flume [m]')
# ax[3].set_ylim([0, 2])

plt.show()

# fig.savefig('//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/12_WAQ/FullDomainFigures/HgTotals.png',
#              bbox_inches='tight', dpi=200)

#%% Plot POC total Data

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 9))
fig.patch.set_facecolor('white')
fig.tight_layout(pad=3)
ax = axes.flat

# POC1 in Water
ax[0].set_title('POC1 (Fast) in Water')
ax[0].plot(dataOUT.index, dataOUT['POC1'], linewidth=3, label='POC1')

ax[0].legend()
ax[0].set_ylabel('POC1 [g/m3]')
ax[0].set_xlabel('Distance Along River [m]')
ax[0].set_ylim([0, 1])
ax[0].set_xlim([0, 100000])

# POC2 in Water
ax[1].set_title('POC2 (Slow) in Water')
ax[1].plot(dataOUT.index, dataOUT['POC2'], linewidth=3, label='POC2')

ax[1].legend()
ax[1].set_ylabel('POC2 [g/m3]')
ax[1].set_xlabel('Distance Along River [m]')
ax[1].set_ylim([0, 1])
ax[1].set_xlim([0, 100000])


#DetC in sediment
ax[2].set_title('DetC (Fast) in Sediment')
ax[2].plot(dataOUT.index, dataOUT['DetCS1']
           / (dataOUT['IM1S1'] + dataOUT['IM2S1'] + dataOUT['IM3S1'] + dataOUT['DetCS1'] + dataOUT['OOCS1']),
            linewidth=3, label='DetCS1')

ax[2].legend()
ax[2].set_ylabel('DetCS1 [g/g]')
ax[2].set_xlabel('Distance Along River [m]')
ax[2].set_ylim([0, 0.02])
ax[2].set_xlim([0, 100000])


# OOC in Sediment
ax[3].set_title('OOC (Slow) in Sediment')
ax[3].plot(dataOUT.index, dataOUT['OOCS1']
           / (dataOUT['IM1S1'] + dataOUT['IM2S1'] + dataOUT['IM3S1'] + dataOUT['DetCS1'] + dataOUT['OOCS1']),
           linewidth=3, label='OOCS1')

ax[3].legend()
ax[3].set_ylabel('OOCS1 [g/g]')
ax[3].set_xlabel('Distance Along River [m]')
ax[3].set_ylim([0, 0.02])
ax[3].set_xlim([0, 100000])

plt.show()
# fig.savefig('//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/12_WAQ/FullDomainFigures/POCTotals.png',
#              bbox_inches='tight', dpi=200)


#%% More Total Data

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 9))
fig.patch.set_facecolor('white')
fig.tight_layout(pad=3)
ax = axes.flat

#H0 in Water
ax[0].set_title('Hg(0) in Water')
ax[0].plot(dataOUT.index, dataOUT['H0']* 1000000, linewidth=3, label='Hg(0)')

ax[0].legend()
ax[0].set_ylabel('Hg(0) [ng/L]')
ax[0].set_xlabel('Distance Along River [m]')
ax[0].set_ylim([0, 0.35])
ax[0].set_xlim([0, 100000])


# IM1 in Water
ax[1].set_title('IM1 (Sand) in Water')
ax[1].plot(dataOUT.index, dataOUT['IM1'], linewidth=3, label='IM1')
ax[1].legend()
ax[1].set_ylabel('IM1 [g/m3]')
ax[1].set_xlabel('Distance Along River [m]')
ax[1].set_ylim([0, 20])
ax[1].set_xlim([0, 100000])

# IM2 in Water
ax[2].set_title('IM2 (Silt) in Water')
ax[2].plot(dataOUT.index, dataOUT['IM2'], linewidth=3, label='IM2')

ax[2].legend()
ax[2].set_ylabel('IM2 [g/m3]')
ax[2].set_xlabel('Distance Along Flume [m]')
ax[2].set_ylim([0, 10])
ax[2].set_xlim([0, 100000])

# IM3 in Water
ax[3].set_title('IM3 (Woodchips) in Water')
ax[3].plot(dataOUT.index, dataOUT['IM3'], linewidth=3, label='IM3 (Woodchips)')

ax[3].legend()
ax[3].set_ylabel('IM3 [g/m3]')
ax[3].set_xlabel('Distance Along River [m]')
# ax[3].set_ylim([0, 0.02])
ax[3].set_xlim([0, 100000])

plt.show()

# fig.savefig('//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/12_WAQ/FullDomainFigures/InorganicTotals.png',
#              bbox_inches='tight', dpi=200)

#%% Plot Fluxes

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 9))
fig.patch.set_facecolor('white')
fig.tight_layout(pad=3)
ax = axes.flat

# IM1 Sediment Flux
ax[0].set_title('IM1 (Sand) Resuspension Flux')
ax[0].plot(dataOUT.index, dataOUT['fResS1IM1'], linewidth=3, label='IM1 Resuspension')
ax[0].plot(dataOUT.index, dataOUT['fSedIM1'], linewidth=3, label='IM1 Sedimentation')
ax[0].set_ylim([0, 200])
ax[0].set_xlim([0, 100000])

ax[0].legend()
ax[0].set_ylabel('IM1 (Sand) Sedimentation and Resuspension [g/m2/d]')
ax[0].set_xlabel('Distance Along River [m]')

# POC Sediment Flux
ax[1].set_title('POC Resuspension Flux')
ax[1].plot(dataOUT.index, dataOUT['fResS1DetC'], linewidth=3, label='DetC Resuspension')
ax[1].plot(dataOUT.index, dataOUT['fResS1OOC'], linewidth=3, label='OOC Resuspension')
ax[1].plot(dataOUT.index, dataOUT['fSedPOC1'], linewidth=3, label='POC1 (Fast) Sedimentation')
ax[1].plot(dataOUT.index, dataOUT['fSedPOC2'], linewidth=3, label='POC2 (Slow) Sedimentation')
ax[1].set_ylim([0, 2])
ax[1].set_xlim([0, 100000])

ax[1].legend()
ax[1].set_ylabel('POC Sedimentation and Resuspension [g/m2/d]')
ax[1].set_xlabel('Distance Along River [m]')

# Hg Sediment Flux
ax[2].set_title('Hg Resuspension Flux')
ax[2].plot(dataOUT.index, dataOUT['fResS1Hg'], linewidth=3, label='Hg Resuspension')
ax[2].plot(dataOUT.index, dataOUT['fSedHg'], linewidth=3, label='Hg Sedimentation')
ax[2].set_ylim([0, 0.002])
ax[2].set_xlim([0, 100000])

ax[2].legend()
ax[2].set_ylabel('Hg Sedimentation and Resuspension [g/m2/d]')
ax[2].set_xlabel('Distance Along River [m]')

# Mm Sediment Flux
ax[3].set_title('MeHg Resuspension Flux')
ax[3].plot(dataOUT.index, dataOUT['fResS1Mm'], linewidth=3, label='MeHg Resuspension')
ax[3].plot(dataOUT.index, dataOUT['fSedMm'], linewidth=3, label='MeHg Sedimentation')

ax[3].legend()
ax[3].set_ylabel('MeHg Sedimentation and Resuspension [g/m2/d]')
ax[3].set_xlabel('Distance Along River [m]')
ax[3].set_xlim([0, 100000])
ax[3].set_ylim([0, 0.0001])
plt.show()

# fig.savefig('C:/Users/arey/files/Projects/Grassy Narrows/Modelling/ProcessFigures/HgFluxes.png',
#              bbox_inches='tight', dpi=200)
# fig.savefig('//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/12_WAQ/FullDomainFigures/HgFluxes.png',
#              bbox_inches='tight', dpi=200)

#%% Plot More Fluxes

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 9))
fig.patch.set_facecolor('white')
fig.tight_layout(pad=4)
ax = axes.flat

# Methylation Flux
ax[0].set_title('Methylation Flux in Water')
ax[0].plot(dataOUT.index, dataOUT['HgMmO'], linewidth=3, label='Mehtylation')
ax[0].plot(dataOUT.index, dataOUT['MmHgO'], linewidth=3, label='Demehtylation')

ax[0].legend()
ax[0].set_ylabel('Methylation Flux in Water [g/m3/d]')
ax[0].set_xlabel('Distance Along River [m]')

# Methylation Flux in Sediment
ax[1].set_title('Methylation Flux in Sediment')
ax[1].plot(dataOUT.index, dataOUT['HgS1MmS1O'] * 1000000,
           linewidth=3, label='Mehtylation')
ax[1].plot(dataOUT.index, dataOUT['MmS1HgS1O'] * 1000000,
           linewidth=3, label='Demehtylation')

ax[1].legend()
ax[1].set_ylabel('Methylation Flux in Sediment [ug/m2/d]')
ax[1].set_xlabel('Distance Along River [m]')

# Hg Diffusion Flux
# ax[2].set_title('Diffusion Flux')
# ax[2].plot(dataOUT.index, dataOUT['HgHgS1O'], linewidth=3, label='Hg Diffusion')
# ax[2].plot(dataOUT.index, dataOUT['MmMmS1O'], linewidth=3, label='MeHg Diffusion')
#
# ax[2].legend()
# ax[2].set_ylabel('Diffusion [g/m2/d]')
# ax[2].set_xlabel('Distance Along River [m]')

# POC Degradation Flux
ax[2].set_title('POC Degradation Flux in Water')
ax[2].plot(dataOUT.index, dataOUT['f_minPOC1'], linewidth=3, label='POC Degradation Water')
ax[2].legend()
ax[2].set_ylabel('POC Degradation [g/m3/d]')
ax[2].set_xlabel('Distance Along River [m]')


# POC Degradation Flux
ax[3].set_title('POC Degradation Flux in Sediment')
ax[3].plot(dataOUT.index, dataOUT['MnODCS1']
            / (dataOUT['DetCS1'] + dataOUT['OOCS1']),
           linewidth=3, label='POC Degradation Sediment')

ax[3].legend()
ax[3].set_ylabel('POC Degradation [g/gPOC/d')
ax[3].set_xlabel('Distance Along River [m]')

plt.show()

# fig.savefig('C:/Users/arey/files/Projects/Grassy Narrows/Modelling/ProcessFigures/POCFluxes.png',
#              bbox_inches='tight', dpi=200)
# fig.savefig('//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/12_WAQ/FullDomainFigures/POCFluxes.png',
#              bbox_inches='tight', dpi=200)

#%% Photo Fluxes

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 9))
fig.patch.set_facecolor('white')
fig.tight_layout(pad=4)
ax = axes.flat

# Diffusion Flux
ax[0].set_title('Diffusion Flux')
ax[0].plot(dataOUT.index, dataOUT['HgHgS1O'], linewidth=3, label='Hg Diffusion')
ax[0].plot(dataOUT.index, dataOUT['MmMmS1O'], linewidth=3, label='MeHg Diffusion')

ax[0].legend()
ax[0].set_ylabel('Diffusion [g/m2/d]')
ax[0].set_xlabel('Distance Along Flume [m]')

# Photo Oxidation Flux
ax[1].set_title('Photo Oxidation Flux')
ax[1].plot(dataOUT.index, dataOUT['oPhoOxy'], linewidth=3, label='Photo Oxidation Flux')

ax[1].legend()
ax[1].set_ylabel('Photo Oxidation Flux [g/m3/d]')
ax[1].set_xlabel('Distance Along Flume [m]')


# Photo Degradation Flux
ax[2].set_title('Photo Degradation Flux')
ax[2].plot(dataOUT.index, dataOUT['oPhoDeg'], linewidth=3, label='Photo Degradation Flux')

ax[2].legend()
ax[2].set_ylabel('Photo Degradation Flux [g/m3/d]')
ax[2].set_xlabel('Distance Along Flume [m]')


# Photo Reduction Flux
ax[3].set_title('Photo Reduction Flux')
ax[3].plot(dataOUT.index, dataOUT['oPhoRed'], linewidth=3, label='Photo Reduction Flux')

ax[3].legend()
ax[3].set_ylabel('Photo Reduction Flux [g/m3/d]')
ax[3].set_xlabel('Distance Along Flume [m]')

plt.show()

# fig.savefig('C:/Users/arey/files/Projects/Grassy Narrows/Modelling/ProcessFigures/H0Fluxes.png',
#              bbox_inches='tight', dpi=200)

#%% Make summary table
dataTableOut = dict()

#Hg Parition in Water
dataTableOut['Hg:IM1 Fraction'] = dataOUT['FrHgIM1'].mean()
dataTableOut['Hg:IM2 Fraction'] = dataOUT['FrHgIM2'].mean()
dataTableOut['Hg:IM3 Fraction'] = dataOUT['FrHgIM3'].mean()
dataTableOut['Hg:POC Fraction'] = dataOUT['FrHgPOC'].mean()
dataTableOut['Hg:DOC Fraction'] = dataOUT['FrHgDOC'].mean()
dataTableOut['Hg:Phyt Fraction'] = dataOUT['FrHgPHYT'].mean()
dataTableOut['Hg:Dissolved Fraction'] = dataOUT['FrHgDis'].mean()

#MeHg Parition in Water
dataTableOut['MeHg:IM1 Fraction'] = dataOUT['FrMmIM1'].mean()
dataTableOut['MeHg:IM2 Fraction'] = dataOUT['FrMmIM2'].mean()
dataTableOut['MeHg:IM3 Fraction'] = dataOUT['FrMmIM3'].mean()
dataTableOut['MeHg:POC Fraction'] = dataOUT['FrMmPOC'].mean()
dataTableOut['MeHg:DOC Fraction'] = dataOUT['FrMmDOC'].mean()
dataTableOut['MeHg:Phyt Fraction'] = dataOUT['FrMmPHYT'].mean()
dataTableOut['MeHg:Dissolved Fraction'] = dataOUT['FrMmDis'].mean()

#Hg Parition in S1
dataTableOut['Hg:IM1 Fraction S1'] = dataOUT['FrHgIM1S1'].mean()
dataTableOut['Hg:IM2 Fraction S1'] = dataOUT['FrHgIM2S1'].mean()
dataTableOut['Hg:IM3 Fraction S1'] = dataOUT['FrHgIM3S1'].mean()
dataTableOut['Hg:POC Fraction S1'] = dataOUT['FrHgPOCS1'].mean()
dataTableOut['Hg:DOC Fraction S1'] = dataOUT['FrHgDOCS1'].mean()
dataTableOut['Hg:Phyt Fraction S1'] = dataOUT['FrHgPHYTS1'].mean()
dataTableOut['Hg:Dissolved Fraction S1'] = dataOUT['FrHgDisS1'].mean()

#MeHg Parition in S1
dataTableOut['MeHg:IM1 Fraction S1'] = dataOUT['FrMmIM1S1'].mean()
dataTableOut['MeHg:IM2 Fraction S1'] = dataOUT['FrMmIM2S1'].mean()
dataTableOut['MeHg:IM3 Fraction S1'] = dataOUT['FrMmIM3S1'].mean()
dataTableOut['MeHg:POC Fraction S1'] = dataOUT['FrMmPOCS1'].mean()
dataTableOut['MeHg:DOC Fraction S1'] = dataOUT['FrMmDOCS1'].mean()
dataTableOut['MeHg:Phyt Fraction S1'] = dataOUT['FrMmPHYT'].mean()
dataTableOut['MeHg:Dissolved Fraction S1'] = dataOUT['FrMmDisS1'].mean()

#Hg in Water
dataTableOut['Hg in Water [ng/L]'] = dataOUT['Hg'].mean() * 1000000

# Mm in Water
dataTableOut['MeHg in Water [ng/L]'] = dataOUT['Mm'].mean() * 1000000

#Hg in Sediment
dataTableOut['Hg in Sediment [ng/g]'] = dataOUT['HgS1'].mean() * 1*10 ** 9 /\
                                     (dataOUT['IM1S1'].mean() + dataOUT['IM2S1'].mean() + dataOUT['IM3S1'].mean() +
                                      dataOUT['DetCS1'].mean() + dataOUT['OOCS1'].mean())

# Mm in Sediment
dataTableOut['MeHg in Sediment [ng/g]'] = dataOUT['MmS1'].mean() * 1*10 ** 9 /\
                                     (dataOUT['IM1S1'].mean() + dataOUT['IM2S1'].mean() + dataOUT['IM3S1'].mean() +
                                      dataOUT['DetCS1'].mean() + dataOUT['OOCS1'].mean())

# Hg(0) in Water
dataTableOut['Hg(0) in Water [ng/L]'] = dataOUT['H0'].mean() * 1000000

# IM1 in Water
ax[1].set_title('IM1 (Sand) in Water')
dataTableOut['IM1 (Sand) in Water [g/m3]'] = dataOUT['IM1'].mean()

# IM2 in Water
dataTableOut['IM2 (Silt) in Water [g/m3]'] = dataOUT['IM2'].mean()

# IM3 in Water
dataTableOut['IM3 (Woodchips) in Water [g/m3]'] = dataOUT['IM3'].mean()

# POC1 in Water
dataTableOut['POC1 (Fast) in Water [g/m3]'] = dataOUT['POC1'].mean()

# POC2 in Water
dataTableOut['POC1 (Slow) in Water [g/m3]'] = dataOUT['POC2'].mean()

#DetC in sediment
dataTableOut['DetC (Fast) in Sediment [g/g]'] = dataOUT['DetCS1'].mean() /\
                                     (dataOUT['IM1S1'].mean() + dataOUT['IM2S1'].mean() + dataOUT['IM3S1'].mean() +
                                      dataOUT['DetCS1'].mean() + dataOUT['OOCS1'].mean())

# OOC in Sediment
dataTableOut['OOC (Slow) in Sediment [g/g]'] = dataOUT['OOCS1'].mean() /\
                                     (dataOUT['IM1S1'].mean() + dataOUT['IM2S1'].mean() + dataOUT['IM3S1'].mean() +
                                      dataOUT['DetCS1'].mean() + dataOUT['OOCS1'].mean())


# IM1 Resuspension
dataTableOut['IM1 (Sand) Resuspension Flux [g/m2/d]'] = dataOUT['fResS1IM1'].mean()

# IM1 Sedimentation
dataTableOut['IM1 (Sand) Sedimentation Flux [g/m2/d]'] = dataOUT['fSedIM1'].mean()

# DetC Resuspension
dataTableOut['DetC Resuspension Flux [g/m2/d]'] = dataOUT['fResS1DetC'].mean()

# OOC Resuspension
dataTableOut['OOC Resuspension Flux [g/m2/d]'] = dataOUT['fResS1OOC'].mean()

# POC1 Sedimentation
dataTableOut['POC1 (Fast) Sedimentation [g/m2/d]'] = dataOUT['fSedPOC1'].mean()

# POC2 Sedimentation
dataTableOut['POC2 (Slow) Sedimentation [g/m2/d]'] = dataOUT['fSedPOC2'].mean()

# Hg Resuspension
dataTableOut['Hg Resuspension Flux [g/m2/d]'] = dataOUT['fResS1Hg'].mean()

# Hg Sedimentation
dataTableOut['Hg Sedimentation Flux [g/m2/d]'] = dataOUT['fSedHg'].mean()

# MeHg Resuspension
dataTableOut['MeHg Resuspension Flux [g/m2/d]'] = dataOUT['fResS1Mm'].mean()

# MeHg Sedimentation
dataTableOut['MeHg Sedimentation Flux [g/m2/d]'] = dataOUT['fSedMm'].mean()


# Methylation Flux in Water
dataTableOut['Methylation Flux in Water [g/m3/d]'] = dataOUT['HgMmO'].mean()

# Demehtylation Flux in Water
dataTableOut['Demehtylation Flux in Water [g/m3/d]'] = dataOUT['MmHgO'].mean()

# Methylation Flux in Sediment
dataTableOut['Methylation Flux in Sediment [g/gHg/d]'] = dataOUT['HgS1MmS1O'].mean() / dataOUT['HgS1'].mean()

# Demehtylation Flux in Sediment
dataTableOut['Demehtylation Flux in Sediment [g/gMm/d]'] = dataOUT['MmS1HgS1O'].mean() / dataOUT['MmS1'].mean()


# POC Degradation Flux in Water
dataTableOut['POC Degradation Flux in Water [g/m3/d]'] = dataOUT['f_minPOC1'].mean()

# POC Degradation Flux in Sediment
dataTableOut['Demehtylation Flux in Water [g/gPOC/d]'] = dataOUT['MnODCS1'].mean() /\
                                                       (dataOUT['DetCS1'].mean() + dataOUT['OOCS1'].mean())


# Hg Diffusion Flux
dataTableOut['Hg Diffusion [g/m2/d]'] = dataOUT['HgHgS1O'].mean()

# MeHg Diffusion Flux
dataTableOut['MeHg Diffusion [g/m2/d]'] = dataOUT['MmMmS1O'].mean()

# Photo Oxidation Flux
dataTableOut['Hg Diffusion [g/m3/d]'] = dataOUT['oPhoOxy'].mean()

# Photo Degradation Flux
dataTableOut['MeHg Diffusion [g/m3/d]'] = dataOUT['oPhoDeg'].mean()

# Photo Reduction Flux
dataTableOut['Hg Diffusion [g/m3/d]'] = dataOUT['oPhoRed'].mean()

#%% Save Data Table as Excel
dataTableOut_df = pd.DataFrame(data=dataTableOut, index=[0])
dataTableOut_df = (dataTableOut_df.T)

dataTableOut_df.to_excel('C:/Users/arey/files/Projects/Grassy Narrows/Modelling/ModelOutputs_Sept26.xlsx')