# Model output (part 1)

  1. Potemra

April 2022


In this notebook we will have a look at various model output. These include forecast models run operationally (typically daily), reanalysis (run in “hindcast”), and climate models.

1. Wave forecast: compare to point

In this first example we will have a look at output from a region wave model that is run in forecast mode. This model (SWAN) is run operationally by PacIOOS every day and provides a several day forecast of wave height, period and direction. PacIOOS runs different domains, and here we will look at the Oahu grid.

We will compare the model to data measured in situ by a near-shore wave buoy. Some questions we can ask:

  1. how well does the model do at compared to this buoy?

  2. how “representative” is this point to other points?

1A. Wave model

The wave model is the Simulating WAves Nearshore (SWAN) regional wave model for Oahu. The results can be obtained from the PacIOOS THREDDS server:

https://pae-paha.pacioos.hawaii.edu/thredds/catalog.html

Wave Model Output –> SWAN Oahu Regional Wave Model –> Best Time Series –> OPeNDAP

https://pae-paha.pacioos.hawaii.edu/thredds/dodsC/swan_oahu/SWAN_Oahu_Regional_Wave_Model_best.ncd

1B. Buoy data

We will use data from the Waimea buoy (106). The Coastal Data Information Program (CDIP) at Scripps maintains an archive of all the US buoy. The Waimea page is

https://cdip.ucsd.edu/themes/cdip?d2=p70&u2=s:106:v:parameter

and the data are at Data –> Realtime –> OPeNDAP

http://thredds.cdip.ucsd.edu/thredds/dodsC/cdip/realtime/106p1_rt.nc

1C. Read in needed packages

[1]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import netCDF4 as nc
import pandas as pd
import cartopy.crs as ccrs
import cartopy.feature as cf
import matplotlib.ticker as mticker
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

1D. Access data from the model (mod_) and buoy (obs_)

[2]:
URL1 = 'https://pae-paha.pacioos.hawaii.edu/thredds/dodsC/swan_oahu/SWAN_Oahu_Regional_Wave_Model_best.ncd'
mod = nc.Dataset(URL1)

URL2 = 'http://thredds.cdip.ucsd.edu/thredds/dodsC/cdip/realtime/106p1_rt.nc'
obs = nc.Dataset(URL2)
[3]:
mod
[3]:
<class 'netCDF4._netCDF4.Dataset'>
root group (NETCDF3_CLASSIC data model, file format DAP2):
    title: Simulating WAves Nearshore (SWAN) Regional Wave Model: Oahu
    _CoordSysBuilder: ucar.nc2.dataset.conv.CF1Convention
    Conventions: CF-1.6, ACDD-1.3
    cdm_data_type: Grid
    featureType: GRID
    location: Proto fmrc:SWAN_Oahu_Regional_Wave_Model
    id: swan_oahu
    naming_authority: org.pacioos
    metadata_link: http://pacioos.org/metadata/swan_oahu.html
    ISO_Topic_Categories: oceans
    summary: Simulating WAves Nearshore (SWAN) regional wave model 7-day output with a 5-day hourly forecast for the Hawaiian island of Oahu at approximately 500-m resolution. This high-resolution model is utilized to capture shallow water effects and nearshore coastal dynamics such as refracting, shoaling, and smaller scale shadowing. It is run directly after the Hawaii regional WaveWatch III (WW3) wave model (ww3_hawaii) has completed. Please note that some of the nested model setup is still in the testing and validation phase. While considerable effort has been made to implement all model components in a thorough, correct, and accurate manner, numerous sources of error are possible. As such, please use these data with the caution appropriate for any ocean related activity.
    keywords: Earth Science Services > Models > Ocean General Circulation Models (OGCM)/Regional Ocean Models, Earth Science Services > Models > Weather Research/Forecast Models, Earth Science > Oceans > Ocean Waves > Significant Wave Height, Earth Science > Oceans > Ocean Waves > Wave Period, Earth Science > Oceans > Ocean Waves > Wave Speed/Direction
    keywords_vocabulary: GCMD Science Keywords
    platform: Models/Analyses > > Operational Models
    platform_vocabulary: GCMD Platform Keywords
    instrument: Not Applicable > Not Applicable
    instrument_vocabulary: GCMD Instrument Keywords
    locations: Continent > North America > United States Of America > Hawaii, Ocean > Pacific Ocean > Central Pacific Ocean > Hawaiian Islands > Oahu
    locations_vocabulary: GCMD Location Keywords
    standard_name_vocabulary: CF Standard Name Table v39
    history: 2010-06-20T00:00:00Z New dataset. ;
FMRC Best Dataset
    comment: Model runs produced by Kwok Fai Cheung (cheung@hawaii.edu).
    geospatial_lat_min: 21.2
    geospatial_lat_max: 21.75
    geospatial_lon_min: 201.65
    geospatial_lon_max: 202.4
    geospatial_vertical_min: 0.0
    geospatial_vertical_max: 0.0
    geospatial_bounds: POLYGON ((21.2 -158.35, 21.75 -158.35, 21.75 -157.6, 21.2 -157.6, 21.2 -158.35))
    geospatial_bounds_crs: EPSG:4326
    time_coverage_start: 2010-06-20T21:00:00Z
    geospatial_lat_units: degrees_north
    geospatial_lat_resolution: 0.005
    geospatial_lon_units: degrees_east
    geospatial_lon_resolution: 0.005
    geospatial_vertical_units: meters
    geospatial_vertical_positive: up
    geospatial_vertical_resolution: 0.0
    time_coverage_resolution: PT1H
    creator_name: Kwok Fai Cheung
    creator_institution: University of Hawaii at Manoa
    creator_email: cheung@hawaii.edu
    creator_url: http://www.soest.hawaii.edu/ore/people/faculty/kwok-fai-cheung/
    creator_type: person
    date_created: 2010-06-20
    date_issued: 2010-06-20
    date_modified: 2010-06-20
    date_metadata_modified: 2021-03-30
    institution: Pacific Islands Ocean Observing System (PacIOOS)
    project: Pacific Islands Ocean Observing System (PacIOOS)
    program: Pacific Islands Ocean Observing System (PacIOOS)
    publisher_name: Pacific Islands Ocean Observing System (PacIOOS)
    publisher_institution: Pacific Islands Ocean Observing System (PacIOOS)
    publisher_email: info@pacioos.org
    publisher_url: http://pacioos.org
    publisher_type: institution
    license: The data may be used and redistributed for free but is not intended for legal use, since it may contain inaccuracies. Neither the data Contributor, University of Hawaii, PacIOOS, NOAA, State of Hawaii nor the United States Government, nor any of their employees or contractors, makes any warranty, express or implied, including warranties of merchantability and fitness for a particular purpose, or assumes any legal liability for the accuracy, completeness, or usefulness, of this information.
    acknowledgement: The Pacific Islands Ocean Observing System (PacIOOS) is funded through the National Oceanic and Atmospheric Administration (NOAA) as a Regional Association within the U.S. Integrated Ocean Observing System (IOOS). PacIOOS is coordinated by the University of Hawaii School of Ocean and Earth Science and Technology (SOEST).
    source: Simulating WAves Nearshore (SWAN) numerical wave model
    references: http://swanmodel.sourceforge.net
    dimensions(sizes): lat(111), lon(151), time(102444), z(1)
    variables(dimensions): float32 lon(lon), float32 lat(lat), float32 z(z), float64 time(time), float64 time_run(time), float64 time_offset(time), float32 shgt(time, z, lat, lon), float32 mper(time, z, lat, lon), float32 mdir(time, z, lat, lon), float32 pper(time, z, lat, lon), float32 pdir(time, z, lat, lon)
    groups:
[4]:
# The model produces output every three hours, so there are many
#   time-steps (60,000+); here we just access the last "N" times
#   pick N to be small otherwise it will take too long.
N = 300
mod_lat = mod.variables['lat'][:]
mod_lon = mod.variables['lon'][:]
mod_wh = mod.variables['shgt'][-N:,0,:,:]
[5]:
mod_wh
[5]:
masked_array(
  data=[[[1.351050853729248, 1.3357657194137573, 1.3327603340148926,
          ..., 1.7873039245605469, 1.7893667221069336,
          1.7927649021148682],
         [1.3318458795547485, 1.2879561185836792, 1.2845357656478882,
          ..., 1.7901439666748047, 1.793721318244934, 1.800035834312439],
         [1.3177064657211304, 1.274865746498108, 1.2713428735733032,
          ..., 1.7975949048995972, 1.8013821840286255,
          1.8078221082687378],
         ...,
         [1.9511690139770508, 1.9431959390640259, 1.9427067041397095,
          ..., 2.0886600017547607, 2.090512275695801,
          2.0922482013702393],
         [1.9654664993286133, 1.9568660259246826, 1.9565374851226807,
          ..., 2.0914394855499268, 2.092505693435669, 2.093332052230835],
         [1.9798824787139893, 1.9781328439712524, 1.9776954650878906,
          ..., 2.0950167179107666, 2.094867467880249,
          2.0946197509765625]],

        [[1.3643198013305664, 1.3497061729431152, 1.347102403640747,
          ..., 1.8163127899169922, 1.8179750442504883,
          1.8214795589447021],
         [1.3461463451385498, 1.3053652048110962, 1.3024336099624634,
          ..., 1.8179699182510376, 1.821352243423462,
          1.8294016122817993],
         [1.3321623802185059, 1.2921589612960815, 1.2891743183135986,
          ..., 1.8257774114608765, 1.8294875621795654,
          1.8378543853759766],
         ...,
         [1.979655385017395, 1.9709292650222778, 1.9704817533493042,
          ..., 2.114550828933716, 2.117007255554199, 2.119734764099121],
         [1.9946399927139282, 1.985304594039917, 1.9848694801330566,
          ..., 2.11686635017395, 2.118612766265869, 2.120375156402588],
         [2.0101981163024902, 2.0086588859558105, 2.0083069801330566,
          ..., 2.1211705207824707, 2.121316432952881,
          2.1211984157562256]],

        [[1.3827342987060547, 1.3714733123779297, 1.3698766231536865,
          ..., 1.8657747507095337, 1.8685499429702759,
          1.8740381002426147],
         [1.3633393049240112, 1.327771782875061, 1.3256763219833374,
          ..., 1.8664660453796387, 1.871466040611267,
          1.8821134567260742],
         [1.3487313985824585, 1.3142592906951904, 1.3121436834335327,
          ..., 1.8744068145751953, 1.879747986793518,
          1.8907387256622314],
         ...,
         [2.0053579807281494, 1.9972167015075684, 1.9966634511947632,
          ..., 2.141815185546875, 2.144284725189209, 2.147538185119629],
         [2.0215187072753906, 2.0122568607330322, 2.0117645263671875,
          ..., 2.144653081893921, 2.1464157104492188,
          2.1484103202819824],
         [2.038499355316162, 2.0370256900787354, 2.0365748405456543,
          ..., 2.1503498554229736, 2.1503589153289795,
          2.1494829654693604]],

        ...,

        [[1.6496316194534302, 1.6370973587036133, 1.632502794265747,
          ..., 2.045832633972168, 2.0470118522644043, 2.048595905303955],
         [1.643060564994812, 1.6189792156219482, 1.6144431829452515,
          ..., 2.0447726249694824, 2.0479116439819336,
          2.0556180477142334],
         [1.635499358177185, 1.610595941543579, 1.6053919792175293, ...,
          2.0510730743408203, 2.0549747943878174, 2.063138246536255],
         ...,
         [2.0078325271606445, 2.002007007598877, 1.999865174293518, ...,
          2.2481918334960938, 2.2513341903686523, 2.256078004837036],
         [2.017827033996582, 2.010340929031372, 2.008474826812744, ...,
          2.2499284744262695, 2.252647638320923, 2.2567577362060547],
         [2.0318922996520996, 2.0296473503112793, 2.0270767211914062,
          ..., 2.2540040016174316, 2.255553722381592, 2.257620096206665]],

        [[1.6194523572921753, 1.6073695421218872, 1.60322105884552, ...,
          2.0424206256866455, 2.04472279548645, 2.0477654933929443],
         [1.6120063066482544, 1.5880928039550781, 1.5837395191192627,
          ..., 2.0409302711486816, 2.0450844764709473,
          2.0535428524017334],
         [1.6044926643371582, 1.5803260803222656, 1.5752310752868652,
          ..., 2.0469298362731934, 2.051487922668457,
          2.0598621368408203],
         ...,
         [2.0201117992401123, 2.013551712036133, 2.0117642879486084,
          ..., 2.2202236652374268, 2.2231976985931396,
          2.2279763221740723],
         [2.0297937393188477, 2.021921157836914, 2.0204873085021973,
          ..., 2.2218453884124756, 2.2245094776153564,
          2.228686809539795],
         [2.044382333755493, 2.042509078979492, 2.0403592586517334, ...,
          2.2262277603149414, 2.227635145187378, 2.2295455932617188]],

        [[1.613073468208313, 1.599169373512268, 1.5950123071670532, ...,
          2.0382518768310547, 2.0422585010528564, 2.0479815006256104],
         [1.5961247682571411, 1.5590028762817383, 1.5546085834503174,
          ..., 2.0349550247192383, 2.0419723987579346,
          2.0537612438201904],
         [1.5860539674758911, 1.5477544069290161, 1.5428388118743896,
          ..., 2.0410354137420654, 2.048450469970703, 2.060070753097534],
         ...,
         [2.0148165225982666, 2.007227897644043, 2.0052309036254883,
          ..., 2.2185444831848145, 2.222581148147583, 2.2279212474823],
         [2.025925397872925, 2.0174670219421387, 2.0157556533813477,
          ..., 2.220338821411133, 2.2239863872528076,
          2.2286596298217773],
         [2.0432798862457275, 2.0412964820861816, 2.0390005111694336,
          ..., 2.226106882095337, 2.2277987003326416, 2.229557991027832]]],
  mask=[[[False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         ...,
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False]],

        [[False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         ...,
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False]],

        [[False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         ...,
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False]],

        ...,

        [[False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         ...,
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False]],

        [[False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         ...,
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False]],

        [[False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         ...,
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False],
         [False, False, False, ..., False, False, False]]],
  fill_value=nan,
  dtype=float32)
[6]:
obs
[6]:
<class 'netCDF4._netCDF4.Dataset'>
root group (NETCDF3_CLASSIC data model, file format DAP2):
    naming_authority: edu.ucsd.cdip
    keywords_vocabulary: Global Change Master Directory (GCMD) Earth Science Keywords
    date_created: 2022-04-23T00:00:44Z
    date_issued: 2022-04-23T00:00:44Z
    date_modified: 2022-04-23T00:00:44Z
    creator_name: Coastal Data Information Program, SIO/UCSD
    creator_url: http://cdip.ucsd.edu
    creator_email: www@cdip.ucsd.edu
    publisher_name: Coastal Data Information Program, SIO/UCSD
    publisher_url: http://cdip.ucsd.edu
    publisher_email: www@cdip.ucsd.edu
    institution: Scripps Institution of Oceanography, University of California San Diego
    project: Coastal Data Information Program (CDIP)
    processing_level: QA/QC information available at http://cdip.ucsd.edu/documentation
    standard_name_vocabulary: CF Standard Name Table (v29, 08 July 2015)
    Conventions: ACDD-1.3, CF-1.6
    license: These data may be redistributed and used without restriction.
    cdm_data_type: Station
    featureType: timeSeries
    ncei_template_version: NCEI_NetCDF_TimeSeries_Orthogonal_Template_v2.0
    references: http://cdip.ucsd.edu/documentation
    uuid: B23CA873-67BD-4E14-9C09-3E55375C8FE5
    title: Directional wave and sea surface temperature measurements collected in situ by Datawell DWR-M3 directional buoy located near WAIMEA BAY, HI from 2022/01/20 23:00:00 to 2022/04/22 23:56:40.
    summary: Directional wave and sea surface temperature measurements collected in situ by Datawell DWR-M3 directional buoy located near WAIMEA BAY, HI from 2022/01/20 23:00:00 to 2022/04/22 23:56:40. A total of 4418 wave samples were analyzed for this site, where the water depth is approximately 200 meters.
    keywords: EARTH SCIENCE, OCEANS, OCEAN WAVES, GRAVITY WAVES, WIND WAVES, SIGNIFICANT WAVE HEIGHT, WAVE FREQUENCY, WAVE PERIOD, WAVE SPECTRA, OCEAN TEMPERATURE, SEA SURFACE TEMPERATURE, WATER TEMPERATURE, OCEAN, PACIFIC OCEAN, CENTRAL PACIFIC OCEAN
    cdip_station_id: 106
    wmo_id: 51201
    id: CDIP_106p1_20220120-20220422
    history: 2022-04-23T00:00:45Z: dataset created; multiple updates - last run program, arguments: process_dw_realtime v2.1, is70513_202204230000 If date_modified is after date_created, contact CDIP for details of changes.
    comment: This dataset contains data as acquired in real-time, the QC performed upon it is not as complete as for historic CDIP datasets. All values are decoded directly from the instruments in accordance with the manufacturers documentation EXCEPT for those with the attribute :additional_processing which describes further data handling performed by CDIP.
    acknowledgment: CDIP is primarily supported by the U.S. Army Corps of Engineers (USACE). Station partner: PACIOOS ; Field operator: PACIOOS/UH
    metadata_link: http://cdip.ucsd.edu/metadata/106p1
    contributor_name: PACIOOS/UH, PACIOOS/USACE, CDIP
    contributor_role: station operation, station funding, data management
    geospatial_lat_min: 21.667038
    geospatial_lat_max: 21.673782
    geospatial_lat_units: degrees_north
    geospatial_lat_resolution: 1e-04
    geospatial_lon_min: -158.12152
    geospatial_lon_max: -158.11426
    geospatial_lon_units: degrees_east
    geospatial_lon_resolution: 1e-04
    geospatial_vertical_min: 0.0
    geospatial_vertical_max: 0.0
    geospatial_vertical_units: meters
    geospatial_vertical_origin: sea surface
    geospatial_vertical_positive: up
    geospatial_vertical_resolution: 1.0
    time_coverage_start: 2022-01-20T23:00:00Z
    time_coverage_end: 2022-04-22T23:56:40Z
    time_coverage_duration: P092DT00H57M
    time_coverage_resolution: PT30M
    source: insitu observations
    platform: metaPlatform
    instrument: metaInstrumentation
    DODS.strlen: 0
    DODS.dimName: metaStationNameLength
    dimensions(sizes): dwrTime(4418), gpsTime(4418), maxStrlen64(64), metaBoundsCount(2), sourceCount(4421), sstTime(4418), waveFrequency(64), waveTime(4418)
    variables(dimensions): |S1 sourceFilename(sourceCount, maxStrlen64), int32 waveTime(waveTime), int32 waveTimeBounds(waveTime, metaBoundsCount), int8 waveFlagPrimary(waveTime), int8 waveFlagSecondary(waveTime), float32 waveHs(waveTime), float32 waveTp(waveTime), float32 waveTa(waveTime), float32 waveDp(waveTime), float32 wavePeakPSD(waveTime), float32 waveTz(waveTime), int32 waveSourceIndex(waveTime), float32 waveFrequency(waveFrequency), float32 waveFrequencyBounds(waveFrequency, metaBoundsCount), int8 waveFrequencyFlagPrimary(waveFrequency), int8 waveFrequencyFlagSecondary(waveFrequency), float32 waveBandwidth(waveFrequency), int32 sstTime(sstTime), int32 sstTimeBounds(sstTime, metaBoundsCount), int8 sstFlagPrimary(sstTime), int8 sstFlagSecondary(sstTime), float32 sstSeaSurfaceTemperature(sstTime), int32 sstSourceIndex(sstTime), float32 sstReferenceTemp(sstTime), int32 gpsTime(gpsTime), int32 gpsTimeBounds(gpsTime, metaBoundsCount), int8 gpsStatusFlags(gpsTime), float32 gpsLatitude(gpsTime), float32 gpsLongitude(gpsTime), int32 gpsSourceIndex(gpsTime), int32 dwrTime(dwrTime), int32 dwrTimeBounds(dwrTime, metaBoundsCount), int32 dwrSourceIndex(dwrTime), int32 dwrBatteryLevel(dwrTime), float32 dwrZAccelerometerOffset(dwrTime), float32 dwrXAccelerometerOffset(dwrTime), float32 dwrYAccelerometerOffset(dwrTime), float32 dwrOrientation(dwrTime), float32 dwrInclination(dwrTime), int32 dwrBatteryWeeksOfLife(dwrTime), |S1 metaStationName(maxStrlen64), |S1 metaPlatform(maxStrlen64), |S1 metaInstrumentation(maxStrlen64), float32 metaDeployLatitude(), float32 metaDeployLongitude(), float32 metaWaterDepth(), float32 metaDeclination(), |S1 metaGridMapping(maxStrlen64), float32 waveEnergyDensity(waveTime, waveFrequency), float32 waveMeanDirection(waveTime, waveFrequency), float32 waveA1Value(waveTime, waveFrequency), float32 waveB1Value(waveTime, waveFrequency), float32 waveA2Value(waveTime, waveFrequency), float32 waveB2Value(waveTime, waveFrequency), float32 waveCheckFactor(waveTime, waveFrequency), float32 waveSpread(waveTime, waveFrequency), float32 waveM2Value(waveTime, waveFrequency), float32 waveN2Value(waveTime, waveFrequency)
    groups:
[7]:
obs_wh = obs.variables['waveHs'][:]
[8]:
# like before, we convert time to DateTime

time_convert = nc.num2date(mod.variables['time'][-N:],
                           mod.variables['time'].units,
                          only_use_cftime_datetimes=False)
mod_time = pd.to_datetime(time_convert)

time_convert = nc.num2date(obs.variables['waveTime'],
                           obs.variables['waveTime'].units,
                          only_use_cftime_datetimes=False)
obs_time = pd.to_datetime(time_convert)

1E. Compare at a point closest to the buoy

[9]:
buoy_lat = 21.6705
buoy_lon = -158.1171

J = np.argmin(np.abs( mod_lat - buoy_lat ) )
I = np.argmin(np.abs( (mod_lon-360.0) - buoy_lon) )
[12]:
mod_lat[J],mod_lon[I]-360
[12]:
(21.67, -158.11500549316406)
[13]:
fig = plt.subplots(figsize=(12,8))
plt.plot(obs_time,obs_wh,label='buoy')
plt.plot(mod_time,mod_wh[:,J,I],label='model')
plt.legend()
plt.grid()
plt.title('Wave height at Waimea');
../_images/notebooks_0422_Modeling_18_0.png
[15]:
# plot the final forecast time
plt.figure(figsize=(10,10))

ax = plt.axes(projection = ccrs.PlateCarree())

land_50m = cf.NaturalEarthFeature('physical', 'land', '10m',
                                        edgecolor='face',
                                        facecolor=cf.COLORS['land'])
ax.add_feature(land_50m, edgecolor='gray')

ax.set_extent([-158.4, -157.6, 21.2, 21.8], crs=ccrs.PlateCarree())

gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=2, color='gray', alpha = 0.25, linestyle='--')

# labels on bottom and left axes
gl.xlabels_top = False
gl.ylabels_right = False

# define the label style
gl.xlabel_style = {'size': 15, 'color': 'black'}
gl.ylabel_style = {'size': 15, 'color': 'black'}

# now we define exactly which ones to label and spruce up the labels
gl.xlocator = mticker.FixedLocator([-158.4, -158.2, -158.0, -157.8, -157.6])
#gl.ylocator = mticker.FixedLocator([21.2, 21.4, 21.6, 21.8])
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER

plt.contourf(mod_lon,mod_lat,mod_wh[-1,:,:],cmap=cm.jet,
             transform=ccrs.PlateCarree())
plt.plot(buoy_lon,buoy_lat,'k*')
#plt.colorbar(shrink=0.5);
plt.colorbar()
[15]:
<matplotlib.colorbar.Colorbar at 0x7f59fc2d7b80>
../_images/notebooks_0422_Modeling_19_1.png

2. Investigating model output: future warming

In this example we will have a look at output from a coupled climate model to investigate, in a simple way, projected warming. Here we can compare future temperatures to present from two different IPCC scenarios, RCP-4.5 and RCP-8.5. We will use a single model (just because it is faster, but it is not necessarily the best thing to do scientifically speaking). We will also, again for the sake of speed, estimate the change by taking the mean from the last year of the simluation and comparing it to the mean of the first year.

But first… introduction to functions

Most languages, python included, make use of functions. These are separate code blocks that perform some specific task. It helps to write/use a function if you want to perform the same task over and over again (write once, use many).

The syntax for a python function is it starts with a definition line (def), the function name, any arguments that will get passed to the function, and then finally a colon (:). All the function code then gets properly and consistently indented, and the function ends with a return statement. These functions are then “called” just like any other external function/package.

For example, let’s define a function to add two numbers together (simple…, yes). We’ll call this function “sum2num” (always a good idea to use a name that, as far as you know, is unique so as not to confuse it with external functions). The function will take two numbers (a and b) as input, and then return the sum.

def sum2num(a,b):
   c = a + b
   return c

The first line is our function definition, and it includes the name of the function and the arguments passed to it. The subsequent lines are indented, and it ends with a return.

[21]:
# my function to add two numbers together
#  the function takes two number as input
#  the fuction returns a single number
def sum2num(a,b):
    c = a + b
    return c
[17]:
# now lets try it out
x = 4
y = 5
z = sum2num(x,y)
print(z)
9
[18]:
print(sum2num(10,5))
15

This is a very simple example, and it might be easier to just add numbers rather than write a function. In our scripts, we can think about things we do repeatedly, and maybe we want to put them into a function. For example, we continually convert time using num2date, or we use the same map-plotting code block a lot.

Climate model output

The APDRC (http://apdrc.soest.hawaii.edu) hosts a variety of climate model output from the CMIP-5 set of experiments. Here we will look at the output from the GFDL model, and let’s use the RCP-4.5 and RCP-8.5 experiments. We will access the surface temperature, tas.

2A. Read in needed packages

[22]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import netCDF4 as nc
import pandas as pd
import cartopy.crs as ccrs
import cartopy.feature as cf
import matplotlib.ticker as mticker
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

2B. Access data from the model

[23]:
URL1 = 'http://apdrc.soest.hawaii.edu:80/dods/public_data/CMIP5/rcp45/tas/GFDL-CM3_r1i1p1'
tas_r45 = nc.Dataset(URL1)

URL2 = 'http://apdrc.soest.hawaii.edu:80/dods/public_data/CMIP5/rcp85/tas/GFDL-CM3_r1i1p1'
tas_r85 = nc.Dataset(URL2)

2C. Extract lat/lon/time from model(s)

[24]:
lat_r45 = tas_r45.variables['lat'][:]
lon_r45 = tas_r45.variables['lon'][:]

lat_r85 = tas_r85.variables['lat'][:]
lon_r85 = tas_r85.variables['lon'][:]

2D. Extract the first 12 months and last 12 months from each

[25]:
tas1_r45 = tas_r45.variables['tas'][0:12,:,:]
tas2_r45 = tas_r45.variables['tas'][-12:,:,:]
tas1_r85 = tas_r85.variables['tas'][0:12,:,:]
tas2_r85 = tas_r85.variables['tas'][-12:,:,:]
[26]:
print(tas1_r45.shape,tas2_r45.shape,tas1_r85.shape,tas2_r85.shape)
(12, 90, 144) (12, 90, 144) (12, 90, 144) (12, 90, 144)

2E. Compute the difference between the last year mean and first year

[28]:
deltaT_r45 = tas2_r45.mean(axis=0) - tas1_r45.mean(axis=0)
deltaT_r85 = tas2_r85.mean(axis=0) - tas1_r85.mean(axis=0)
[29]:
print(tas2_r45.shape,deltaT_r45.shape)
(12, 90, 144) (90, 144)

2F. Make plots

[30]:
plt.figure(figsize=(12,8))

# first plot on the left:
ax1 = plt.subplot(1,2,1,projection=ccrs.Robinson(central_longitude=0))
ax1.gridlines()
ax1.add_feature(cf.COASTLINE)
clevs = np.linspace(0,20,41)
plt.contourf(lon_r45,lat_r45,deltaT_r45,levels=clevs,
             transform=ccrs.PlateCarree(),cmap=cm.afmhot_r)
plt.colorbar(orientation='horizontal',shrink=0.75)
plt.title('Temperature change from GFDL RCP-4.5')

# second plot on the left:
ax1 = plt.subplot(1,2,2,projection=ccrs.Robinson(central_longitude=0))
ax1.gridlines()
ax1.add_feature(cf.COASTLINE)
clevs = np.linspace(0,20,41)
plt.contourf(lon_r85,lat_r85,deltaT_r85,levels=clevs,transform=ccrs.PlateCarree(),cmap=cm.afmhot_r)
plt.colorbar(orientation='horizontal',shrink=0.75)
plt.title('Temperature change from GFDL RCP-8.5')
[30]:
Text(0.5, 1.0, 'Temperature change from GFDL RCP-8.5')
../_images/notebooks_0422_Modeling_40_1.png