import numpy as np
import xarray as xr
import pandas as pd
from salishsea_tools import viz_tools, places, visualisations
from matplotlib import pyplot as plt, dates
from datetime import datetime, timedelta
from calendar import month_name
from scipy.io import loadmat
from tqdm.notebook import tqdm
from salishsea_tools import nc_tools
from dask.diagnostics import ProgressBar
import cmocean
from scipy.stats import sem
import scipy.stats as stats
%matplotlib inline
plt.rcParams.update({'font.size': 12, 'axes.titlesize': 'medium'})
#years, months, data
monthly_array_temp_slice = np.zeros([14,12,50,50])
# Load monthly averages
mask = xr.open_dataset('/data/eolson/results/MEOPAR/NEMO-forcing-new/grid/mesh_mask201702.nc')
slc = {'y': slice(450,500), 'x': slice(250,300)}
e3t, tmask = [mask[var].isel(z=slice(None, 27),**slc).values for var in ('e3t_0', 'tmask')]
years, variables = range(2007, 2021), ['votemper']
# Temporary list dict
data = {}
# Permanent aggregate dict
aggregates = {var: {} for var in variables}
monthlydat = {var: {} for var in variables}
# Loop through years
for year in [2007,2008,2009,2010,2011,2012,2016,2017,2018,2019,2020]:
# Initialize lists
for var in variables: data[var] = []
# Load monthly averages
for month in range(1, 13):
datestr = f'{year}{month:02d}'
prefix = f'/data/sallen/results/MEOPAR/v201905r/SalishSea_1m_{datestr}_{datestr}'
# Load grazing variables
with xr.open_dataset(prefix + '_grid_T.nc') as ds:
q = ds.votemper.isel(deptht=0, **slc).values
q2 = q[0,:,:]
monthly_array_temp_slice[year-2007,month-1,:,:] = q2 #year2007 is index 0 along 1st dimension
for var in ['votemper']:
data[var].append(ds.votemper.isel(deptht=0, **slc).values)
# Concatenate months
for var in variables: aggregates[var][year] = np.concatenate(data[var]).mean(axis=0)
# Loop through years for wrap years
for year in [2013,2014,2015]:
# Initialize lists
for var in variables: data[var] = []
# Load monthly averages
for month in range(1, 13):
datestr = f'{year}{month:02d}'
prefix = f'/data/sallen/results/MEOPAR/v201905r_wrap/SalishSea_1m_{datestr}_{datestr}'
# Load grazing variables
with xr.open_dataset(prefix + '_grid_T.nc') as ds:
q = ds.votemper.isel(deptht=0, **slc).values
q2 = q[0,:,:]
monthly_array_temp_slice[year-2007,month-1,:,:] = q2 #year2007 is index 0 along 1st dimension
for var in ['votemper']:
data[var].append(ds.votemper.isel(deptht=0, **slc).values)
# Concatenate months
for var in variables: aggregates[var][year] = np.concatenate(data[var]).mean(axis=0)
monthly_array_temp_slice[monthly_array_temp_slice == 0 ] = np.nan
monthly_array_temp_slicemean = \
np.nanmean(np.nanmean(monthly_array_temp_slice, axis = 2),axis = 2)
print(np.shape(monthly_array_temp_slicemean))
(14, 12)
#plot monthly means for all years
fig, ax = plt.subplots(figsize=(15, 5))
bbox = {'boxstyle': 'round', 'facecolor': 'w', 'alpha': 0.9}
cmap = plt.get_cmap('tab10')
palette = [cmap(0), cmap(0.2), 'k', cmap(0.1), cmap(0.3)]
xticks=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov',"Dec"]
for i in range(0,7):
ax.plot(xticks, monthly_array_temp_slicemean[i,:],label=2007+i)
ax.set_title('Central SoG Mesozooplankton Seasonal Cycle',fontsize=18)
ax.legend(frameon=False)
ax.set_ylim(0,25)
ax.set_ylabel('\u03bcmol N')
for i in range(7,14):
ax.plot(xticks, monthly_array_temp_slicemean[i,:],linestyle='--',label=2007+i)
ax.set_title('Surface Temperature',fontsize=18)
ax.legend(frameon=False,bbox_to_anchor=(1, 1))
ax.set_ylim(4,22)
ax.set_ylabel('Degrees C')
plt.axhline(y=12, color='grey', linestyle='-.')
## Coldest years = 2008, 2010, 2011, 2012
NPGO_C=(((+monthly_array_temp_slicemean[1,:]+\
monthly_array_temp_slicemean[3,:]+\
monthly_array_temp_slicemean[4,:]+monthly_array_temp_slicemean[5,:])/4))
## Warmest years = 2015, 2018, 2019, 2020
NPGO_W=(((monthly_array_temp_slicemean[8,:]+\
monthly_array_temp_slicemean[11,:]+monthly_array_temp_slicemean[12,:]+\
monthly_array_temp_slicemean[13,:])/4)) #
## Plot the coldest and warmest years only; Supp Fig. S5
fig, ax = plt.subplots(figsize=(14, 2))
bbox = {'boxstyle': 'round', 'facecolor': 'w', 'alpha': 0.9}
cmap = plt.get_cmap('tab10')
palette = [cmap(0), cmap(0.2), 'k', cmap(0.1), cmap(0.3)]
xticks=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov',"Dec"]
ax.plot(xticks, monthly_array_temp_slicemean[1,:],color='b',linestyle='-',label='2008')
ax.plot(xticks, monthly_array_temp_slicemean[3,:],color='b',linestyle='--',label='2010')
ax.plot(xticks, monthly_array_temp_slicemean[4,:],color='b',linestyle='-.',label='2011')
ax.plot(xticks, monthly_array_temp_slicemean[5,:],color='b',linestyle=':',label='2012')
ax.plot(xticks, monthly_array_temp_slicemean[8,:],color='r',linestyle='-',label='2015')
ax.plot(xticks, monthly_array_temp_slicemean[11,:],color='r',linestyle='--',label='2018')
ax.plot(xticks, monthly_array_temp_slicemean[12,:],color='r',linestyle='-.',label='2019')
ax.plot(xticks, monthly_array_temp_slicemean[13,:],color='r',linestyle=':',label='2020')
ax.set_title('Surface Temperature',fontsize=14)
ax.legend(frameon=False,loc='center left', bbox_to_anchor=(1, 0.5),fontsize=10)
ax.set_ylim(0,22)
ax.set_ylabel('Degrees C')
ax.xaxis.set_tick_params(labelsize=12)
ax.yaxis.set_tick_params(labelsize=12)
ax.set_xticklabels([])
[Text(0, 0, ''), Text(1, 0, ''), Text(2, 0, ''), Text(3, 0, ''), Text(4, 0, ''), Text(5, 0, ''), Text(6, 0, ''), Text(7, 0, ''), Text(8, 0, ''), Text(9, 0, ''), Text(10, 0, ''), Text(11, 0, '')]
NPGO_W_years=[monthly_array_temp_slicemean[8,:],monthly_array_temp_slicemean[11,:],monthly_array_temp_slicemean[12,:],monthly_array_temp_slicemean[13,:]]
sem(NPGO_W_years)
array([0.10085818, 0.4890846 , 0.37887922, 0.15664109, 0.40595597, 0.20241134, 0.40119105, 0.67801848, 0.50271186, 0.33871933, 0.18173575, 0.33064517])
NPGO_W_SEM=[0.10085818, 0.4890846 , 0.37887922, 0.15664109, 0.40595597,
0.20241134, 0.40119105, 0.67801848, 0.50271186, 0.33871933,
0.18173575, 0.33064517]
NPGO_C_years=[monthly_array_temp_slicemean[1,:],
monthly_array_temp_slicemean[3,:],
monthly_array_temp_slicemean[4,:],monthly_array_temp_slicemean[5,:]]
sem(NPGO_C_years)
array([0.21721438, 0.33888804, 0.33143871, 0.15566903, 0.06565611, 0.28891357, 0.22434856, 0.30571173, 0.24001654, 0.23185627, 0.14982848, 0.25240781])
NPGO_C_SEM=[0.21721438, 0.33888804, 0.33143871, 0.15566903, 0.06565611,
0.28891357, 0.22434856, 0.30571173, 0.24001654, 0.23185627,
0.14982848, 0.25240781]
## Preliminary Figure 4a
fig, ax = plt.subplots(figsize=(15, 3))
bbox = {'boxstyle': 'round', 'facecolor': 'w', 'alpha': 0.9}
cmap = plt.get_cmap('tab10')
palette = [cmap(0), cmap(0.2), 'k', cmap(0.1), cmap(0.3)]
xticks=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov',"Dec"]
border = 0.25
ax.errorbar(xticks, NPGO_C, yerr= NPGO_C_SEM, capsize=3,label='NPGO+ coldest',linewidth=2)
ax.errorbar(xticks, NPGO_W,yerr= NPGO_W_SEM, capsize=3,linestyle='--',label='NPGO- warmest',color='r',linewidth=2)
ax.set_title('Sea Surface Temperature',fontsize=18)
ax.legend(frameon=False,fontsize=14)
ax.set_ylim(0,25)
ax.set_ylabel('Degrees C',fontsize=14)
ax.xaxis.set_tick_params(labelsize=14)
ax.yaxis.set_tick_params(labelsize=14)
ax.set_xticklabels([])
a=2
b=5
c=5
d=8
ax.text(-.4, 20, '(a)', fontsize=15, color='k')
#plt.fill([a, a, b, b], [0, 25, 25, 0], color = 'lightgreen', alpha = 0.1)
#plt.fill([c, c, d, d], [0, 25, 25, 0], color = 'wheat', alpha = 0.2)
#plt.savefig('Fig3a_SST.png', bbox_inches='tight',dpi=1000,transparent=False)
Text(-0.4, 20, '(a)')
Spring_C=(((monthly_array_temp_slicemean[(1,3,4,5),2]+
monthly_array_temp_slicemean[(1,3,4,5),3]+monthly_array_temp_slicemean[(1,3,4,5),4]))/3) #
Spring_W=(((monthly_array_temp_slicemean[(8,11,12,13),2]+
monthly_array_temp_slicemean[(8,11,12,13),3]+monthly_array_temp_slicemean[(8,11,12,13),4]))/3) #
Summer_C=(((monthly_array_temp_slicemean[(1,3,4,5),5]+
monthly_array_temp_slicemean[(1,3,4,5),6]+monthly_array_temp_slicemean[(1,3,4,5),7]))/3) #
Spring_W
array([11.72465165, 11.13348375, 10.47916834, 10.70108273])
Summer_W=(((monthly_array_temp_slicemean[(8,11,12,13),5]+
monthly_array_temp_slicemean[(8,11,12,13),6]+monthly_array_temp_slicemean[(8,11,12,13),7]))/3) #
Summer_W
array([17.94220457, 19.22289418, 19.45471819, 18.36878465])
## Preliminary figure 4a
def color_boxplot(data, color, pos=[0], ax=None):
ax = ax or plt.gca()
bp = ax.boxplot(data, patch_artist=True, showmeans=False, positions=pos,widths=0.4)
for item in ['boxes']:
plt.setp(bp[item], color=color)
for item in ['whiskers', 'fliers', 'medians', 'caps']:
plt.setp(bp[item], color='k')
data1 = [Spring_C]
data2 = [Spring_W]
data3 = [Summer_C]
data4 = [Summer_W]
fig, ax = plt.subplots(figsize=(3,3))
bp1 = color_boxplot(data1, 'royalblue', [1])
bp2 = color_boxplot(data2, 'r', [1.5])
bp3 = color_boxplot(data3, 'royalblue', [2.5])
bp4 = color_boxplot(data4, 'r', [3])
#ax.autoscale()
ax.set(xticks=[1.25,2.75], xticklabels=['Spring','Summer'])
ax.set_ylim(8,20)
ax.set_ylabel('Degrees C', fontsize=14)
ax.xaxis.set_tick_params(labelsize=14)
ax.yaxis.set_tick_params(labelsize=14)
#ax.legend([bp1["boxes"], bp2["boxes"], ['A', 'B'], loc='upper right')
#plt.savefig('Fig3a_SSTboxplots.png', bbox_inches='tight',dpi=1000,transparent=True)
plt.show()
stats.ttest_ind(a=Spring_C, b=Spring_W, equal_var=True)
Ttest_indResult(statistic=-3.8497070052027342, pvalue=0.00846285561469824)
stats.ttest_ind(a=Summer_C, b=Summer_W, equal_var=True)
Ttest_indResult(statistic=-2.2041881462513184, pvalue=0.06969892841658737)