Skip to content

Commit

Permalink
Incorporate review suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
sbrus89 committed Nov 11, 2022
1 parent 389bfb1 commit f358cd2
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 49 deletions.
27 changes: 11 additions & 16 deletions mpas_analysis/default.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -2160,9 +2160,8 @@ normArgsDifference = {'vmin': -0.2, 'vmax': 0.2}
# colorbarTicksDifference = numpy.linspace(-0.2, 0.2, 9)

[climatologyMapWaves]
## options related to plotting climatology maps of Temperature and Salinity
## fields at various levels, including the sea floor against control model
## results and WOA climatological data
## options related to plotting climatology maps of wave fields
## ERA5 climatological data

# comparison grid(s) ('latlon', 'antarctic', 'arctic') on which to plot analysis
comparisonGrids = ['latlon']
Expand All @@ -2171,22 +2170,20 @@ comparisonGrids = ['latlon']
# Nov, Dec, JFM, AMJ, JAS, OND, ANN)
seasons = ['ANN','JFM','JAS']

# a list of fields top plot for each transect. All supported fields are listed
# below
fieldList = ['significantWaveHeight', 'peakWaveFrequency']
# a list of fields to plot.
fieldList = ['significantWaveHeight', 'peakWavePeriod']

# make a tables of mean melt rates and melt fluxes for individual ice shelves?
# make a tables of mean wave heights in specified regions
makeTables = False

# list of regions in mean wave height tables
regionGroups = ['Arctic Sea Ice Regions']

obsStartYear = 1950
obsEndYear = 1978
obsStartYear = 1959
obsEndYear = 2021

[climatologyMapWavesSignificantWaveHeight]
## options related to plotting climatology maps of potential temperature
## at various levels, including the sea floor against control model results
## and WOA18 climatological data
## options related to plotting climatology maps of significant wave height

# colormap for model/observations
colormapNameResult = viridis
Expand All @@ -2210,10 +2207,8 @@ normArgsDifference = {'vmin': -5., 'vmax': 5.}
# place the ticks automatically by default
# colorbarTicksDifference = numpy.linspace(-5., 5., 9)

[climatologyMapWavesPeakWaveFrequency]
## options related to plotting climatology maps of potential temperature
## at various levels, including the sea floor against control model results
## and WOA18 climatological data
[climatologyMapWavesPeakWavePeriod]
## options related to plotting climatology maps of peak wave frequency

# colormap for model/observations
colormapNameResult = plasma
Expand Down
101 changes: 68 additions & 33 deletions mpas_analysis/ocean/climatology_map_waves.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from mpas_analysis.shared.io import write_netcdf

from mpas_analysis.shared.climatology import RemapMpasClimatologySubtask, \
RemapObservedClimatologySubtask, get_antarctic_stereographic_projection
RemapObservedClimatologySubtask
from mpas_analysis.shared.climatology.climatology import \
get_masked_mpas_climatology_file_name

Expand All @@ -35,7 +35,6 @@

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime


Expand Down Expand Up @@ -76,8 +75,9 @@ def __init__(self, config, mpasClimatologyTask, regionMasksTask,
'mpas': 'timeMonthly_avg_significantWaveHeight',
'units': r'm',
'titleName': 'Significant Wave Height',
'era5' : 'swh'},
{'prefix': 'peakWaveFrequency',
'era5' : 'swh',
'ss_cci': 'swh_mean'},
{'prefix': 'peakWavePeriod',
'mpas': 'timeMonthly_avg_peakWaveFrequency',
'units': r's',
'titleName': 'Peak Wave Period',
Expand All @@ -97,26 +97,27 @@ def __init__(self, config, mpasClimatologyTask, regionMasksTask,
sectionName = self.taskName

# read in what seasons we want to plot
seasons = config.getExpression(sectionName, 'seasons')
seasons = config.getexpression(sectionName, 'seasons')

regionGroups = config.getExpression(sectionName, 'regionGroups')
regionGroups = config.getexpression(sectionName, 'regionGroups')

if len(seasons) == 0:
raise ValueError('config section {} does not contain valid list '
'of seasons'.format(sectionName))

comparisonGridNames = config.getExpression(sectionName,
comparisonGridNames = config.getexpression(sectionName,
'comparisonGrids')

if len(comparisonGridNames) == 0:
raise ValueError('config section {} does not contain valid list '
'of comparison grids'.format(sectionName))

fieldList = config.getExpression(sectionName, 'fieldList')
fieldList = config.getexpression(sectionName, 'fieldList')
fieldsRequested = [field for field in fields if field['prefix'] in fieldList]

variableListMpas = [field['mpas'] for field in fieldsRequested]
variableListObs = [field['era5'] for field in fieldsRequested]
#variableListObs = [field['ss_cci'] for field in fieldsRequested]

climStartYear = config.getint(sectionName, 'obsStartYear')
climEndYear = config.getint(sectionName, 'obsEndYear')
Expand All @@ -126,7 +127,7 @@ def __init__(self, config, mpasClimatologyTask, regionMasksTask,

if makeTables:
#for regionGroup in regionGroups:
fieldListTable = config.getExpression(sectionName, 'fieldList')
fieldListTable = config.getexpression(sectionName, 'fieldList')
fieldListTable.append('iceFraction')
fieldsTable = [field for field in fields if field['prefix'] in fieldListTable]
for season in seasons:
Expand All @@ -142,7 +143,6 @@ def __init__(self, config, mpasClimatologyTask, regionMasksTask,

# the variableList variables will be added to
# mpasClimatologyTask along with the seasons.
#remapClimatologySubtask = RemapMpasClimatologySubtask(
remapClimatologySubtask = RemapMpasWavesClimatology(
mpasClimatologyTask=mpasClimatologyTask,
parentTask=self,
Expand All @@ -155,7 +155,8 @@ def __init__(self, config, mpasClimatologyTask, regionMasksTask,
if controlConfig is None:
observationsDirectory = build_obs_path(
config, 'ocean', '{}Subdirectory'.format('wave'))
obsFileName = "{}/ERA5_1950_1978_new.nc".format(observationsDirectory)
obsFileName = "{}/ERA5_Monthly_1959-2021.nc".format(observationsDirectory)
#obsFileName = "{}/SS_CCI_1991_2018.nc".format(observationsDirectory)

remapObservationsSubtask = RemapObservedWaveClimatology(
parentTask=self, seasons=seasons, fileName=obsFileName,
Expand All @@ -179,6 +180,7 @@ def __init__(self, config, mpasClimatologyTask, regionMasksTask,
refTitleLabel = "Observations (ERA 5) {:04d}-{:04d}".format(
climStartYear, climEndYear)
refFieldName = field['era5']
#refFieldName = field['ss_cci']
diffTitleLabel = None

else:
Expand Down Expand Up @@ -210,16 +212,14 @@ def __init__(self, config, mpasClimatologyTask, regionMasksTask,
subtask.set_plot_info(
outFileLabel=outFileLabel,
fieldNameInTitle=field['titleName'],
mpasFieldName=field['mpas'],
mpasFieldName=field['prefix'],
refFieldName=refFieldName,
refTitleLabel=refTitleLabel,
diffTitleLabel=diffTitleLabel,
unitsLabel=field['units'],
imageCaption=field['titleName'],
#galleryGroup=field['titleName'],
galleryGroup='waves',
groupSubtitle=None,
#groupLink='{}Waves'.format(fieldPrefix),
groupLink='waves',
galleryName=field['titleName'],
configSectionName=configSectionName)
Expand Down Expand Up @@ -252,11 +252,42 @@ def setup_and_check(self): # {{{


class RemapMpasWavesClimatology(RemapMpasClimatologySubtask): # {{{

"""
A subtask for reading and remapping wave climatology
"""
# Authors
# -------
# Steven Brus, Xylar Asay-Davis

def customize_masked_climatology(self, climatology, season): # {{{
"""
Convert peak freqency to peak period
The descriptor for the observation grid
Parameters
----------
climatology : ``xarray.Dataset`` object
the climatology data set
season : str
The name of the season to be masked
Returns
-------
climatology : ``xarray.Dataset`` object
the modified climatology data set
"""
# Authors
# -------
# Steven Brus
# Xylar Asay-Davis


climatology['timeMonthly_avg_peakWaveFrequency'] = 1.0/climatology['timeMonthly_avg_peakWaveFrequency']
if 'timeMonthly_avg_peakWaveFrequency' in climatology:
climatology['peakWavePeriod'] = 1.0/climatology['timeMonthly_avg_peakWaveFrequency']

if 'timeMonthly_avg_significantWaveHeight' in climatology:
climatology['significantWaveHeight'] = climatology['timeMonthly_avg_significantWaveHeight']

return climatology

Expand All @@ -271,6 +302,7 @@ class RemapObservedWaveClimatology(RemapObservedClimatologySubtask): # {{{
# Authors
# -------
# Steven Brus, Xylar Asay-Davis

def __init__(self, parentTask, seasons, fileName, outFilePrefix,
variableList,
comparisonGridNames=['latlon'],
Expand Down Expand Up @@ -339,8 +371,8 @@ def get_observation_descriptor(self, fileName): # {{{
# create a descriptor of the observation grid using the lat/lon
# coordinates
obsDescriptor = LatLonGridDescriptor.read(fileName=fileName,
latVarName='lat',
lonVarName='lon')
latVarName='latitude',
lonVarName='longitude')
return obsDescriptor # }}}

def build_observational_dataset(self, fileName): # {{{
Expand Down Expand Up @@ -368,9 +400,7 @@ def build_observational_dataset(self, fileName): # {{{
timeStart = datetime.datetime(year=climStartYear, month=1, day=1)
timeEnd = datetime.datetime(year=climEndYear, month=12, day=31)

dsObs = xr.open_dataset(fileName, decode_times=False)
units, reference_date = dsObs.time.attrs['units'].split('since')
dsObs['time'] = pd.date_range(start=reference_date, periods=dsObs.sizes['time'], freq='MS')
dsObs = xr.open_dataset(fileName)
dsObs = dsObs.rename({'time': 'Time'})
dsObs = dsObs.sel(Time=slice(timeStart, timeEnd))
dsObs.coords['month'] = dsObs['Time.month']
Expand All @@ -384,6 +414,13 @@ def build_observational_dataset(self, fileName): # {{{


class WavesTableSubtask(AnalysisTask):
"""
A subtask for creating wave region tables
"""
# Authors
# -------
# Steven Brus, Xylar Asay-Davis

def __init__(self, parentTask, mpasClimatologyTask, controlConfig,
regionMasksTask, season, fields, subtaskName=None): # {{{
"""
Expand Down Expand Up @@ -457,7 +494,7 @@ def run_task(self): # {{{
config = self.config

sectionName = self.taskName
#regionsInTable = config.getExpression(sectionName,
#regionsInTable = config.getexpression(sectionName,
# 'regionsInTable')
#if len(regionsInTable) == 0:
# return
Expand Down Expand Up @@ -572,28 +609,30 @@ def run_task(self): # {{{

for field in self.fields:

prefix = field['prefix']
mpas = field['mpas']

if field['mpas'] == 'timeMonthly_avg_iceFraction':
continue

tableFileName = '{}/wavesTable_{}_{}.csv'.format(outDirectory,
field['prefix'],
prefix,
self.season)

with open(tableFileName, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldNames)

writer.writeheader()
for index, regionName in enumerate(regionNames):
if field['mpas'] == 'timeMonthly_avg_peakWaveFrequency':
var = 1.0/ds[field['mpas']][index].values
else:
var = ds[field['mpas']][index].values
var = ds[mpas][index].values
if mpas == 'timeMonthly_avg_peakWaveFrequency':
var = 1.0/var
row = {'Region': regionName,
'Area': '{}'.format(ds.area[index].values),
mainRunName: '{}'.format(var)}
if dsControl is not None:
row[controlRunName] = \
'{}'.format(dsControl[field['mpas']][index].values)
'{}'.format(dsControl[mpas][index].values)
writer.writerow(row)

##### Histograms #####
Expand All @@ -603,11 +642,7 @@ def run_task(self): # {{{
startYear = int(config.get('climatology','startYear'))
endYear = int(config.get('climatology','endYear'))

seasonMonths = {'ANN':[1,2,3,4,5,6,7,8,9,10,11,12],
'JFM':[1,2,3],
'JAS':[7,8,9]}

months = seasonMonths[self.season]
months = constants.monthDictionary[self.season]

filePrefix = baseDirectory+'/'+runSubdirectory+'/'+mainRunName+'.mpaso.waveOutput.'
files = []
Expand Down

0 comments on commit f358cd2

Please sign in to comment.