Bonus Tutorial 6: Radiative-Convective Equilibrium#
Week 1, Day 5, Introduction to Climate Modeling
Content creators: Jenna Pearson and Brian E. J. Rose
Content reviewers: Mujeeb Abdulfatai, Nkongho Ayuketang Arreyndip, Jeffrey N. A. Aryee, Younkap Nina Duplex, Will Gregory, Paul Heubel, Zahra Khodakaramimaghsoud, Peter Ohue, Abel Shibu, Derick Temfack, Yunlong Xu, Peizhen Yang, Ohad Zivan, Chi Zhang
Content editors: Abigail Bodner, Paul Heubel, Brodie Pearson, Ohad Zivan, Chi Zhang
Production editors: Wesley Banfield, Paul Heubel, Jenna Pearson, Konstantine Tsafatinos, Chi Zhang, Ohad Zivan
Our 2024 Sponsors: CMIP, NFDI4Earth
Tutorial Objectives#
Estimated timing of tutorial: 20 minutes
Note that this and the two previous tutorials contain solely Bonus content that serves experienced participants and for later investigation of 0- and 1-dimensional models after the course. Please check out these tutorials after finishing Tutorial 7-8 successfully.
Building on the understanding of a one-dimensional radiative balance model from the previous tutorial, in this tutorial you will learn about radiative-convective-equilibrium. Much of the code shown here was taken from The Climate Laboratory by Brian E. J. Rose. You are encouraged to visit this website for more tutorials and background on these models.
By the end of this tutorial you will be able to:
Implement a radiative-convective equilibrium model using the python package
climlab.Understand how this model builds off the one-dimensional radiative balance model used in the previous tutorials.
Setup#
# installations ( uncomment and run this cell ONLY when using google colab or kaggle )
# !pip install -q climlab cftime metpy
# !pip install -q git+https://github.com/climlab/climlab-rrtmg
# !pip install -q git+https://github.com/climlab/climlab-cam3-radiation
# !pip install -q git+https://github.com/climlab/climlab-emanuel-convection
# imports
# google colab users, if you get an xarray error, please run this cell again
import xarray as xr # used to manipulate data and open datasets
import numpy as np # used for algebra/arrays
import climlab # one of the models we are using
import matplotlib.pyplot as plt # used for plotting
import metpy # used to make Skew T Plots of temperature and pressure
from metpy.plots import SkewT # plotting function used widely in climate science
import pooch
import os
import tempfile
from IPython.display import HTML
from matplotlib import animation
Downloading data from 'http://www.atmos.albany.edu/facstaff/brose/resources/climlab_data/absorptivity/abs_ems_factors_fastvx.c030508.nc' to file '/home/runner/.cache/pooch/61707eb16bd77eb262c3c7db3706b35d-abs_ems_factors_fastvx.c030508.nc'.
/home/runner/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/cam3.py:45: UserWarning: Cannot import and initialize compiled Fortran extension, CAM3 module will not be functional.
warnings.warn('Cannot import and initialize compiled Fortran extension, CAM3 module will not be functional.')
Install and import feedback gadget#
Show code cell source
# @title Install and import feedback gadget
!pip3 install vibecheck datatops --quiet
from vibecheck import DatatopsContentReviewContainer
def content_review(notebook_section: str):
return DatatopsContentReviewContainer(
"", # No text prompt
notebook_section,
{
"url": "https://pmyvdlilci.execute-api.us-east-1.amazonaws.com/klab",
"name": "comptools_4clim",
"user_key": "l5jpxuee",
},
).render()
feedback_prefix = "W1D5_T6"
Figure settings#
Show code cell source
# @title Figure settings
import ipywidgets as widgets # interactive display
%config InlineBackend.figure_format = 'retina'
plt.style.use(
"https://raw.githubusercontent.com/abodner/climate-course-content/main/cma.mplstyle"
)
Helper functions#
Show code cell source
# @title Helper functions
def pooch_load(filelocation=None, filename=None, processor=None):
shared_location = "/home/jovyan/shared/Data/tutorials/W1D5_IntroductiontoClimateModeling" # this is different for each day
user_temp_cache = tempfile.gettempdir()
if os.path.exists(os.path.join(shared_location, filename)):
file = os.path.join(shared_location, filename)
else:
file = pooch.retrieve(
filelocation,
known_hash=None,
fname=os.path.join(user_temp_cache, filename),
processor=processor,
)
return file
Plotting Functions#
Show code cell source
# @title Plotting Functions
# make the videos at the end of the tutorial
plt.rcParams["animation.html"] = "jshtml"
# these three functions are used to make videos at the end of the tutorial
def initial_figure(model):
with plt.ioff(): # will hide the inital figure which will plot separate from the video otherwise
fig = plt.figure(figsize=(6, 6))
lines = []
skew = SkewT(fig, rotation=30)
# plot the observations
skew.plot(
Tglobal.level,
Tglobal,
color="black",
linestyle="-",
linewidth=2,
label="Observations",
)
lines.append(
skew.plot(
model.lev,
model.Tatm - climlab.constants.tempCtoK,
linestyle="-",
linewidth=2,
color="C0",
label="RC model (all gases)",
)[0]
)
skew.ax.legend()
skew.ax.set_ylim(1050, 10)
skew.ax.set_xlim(-60, 75)
# Add the relevant special lines
skew.plot_dry_adiabats(linewidth=1.5, label="dry adiabats")
# skew.plot_moist_adiabats(linewidth=1.5, label = 'moist adiabats')
skew.ax.set_xlabel("Temperature ($^\circ$C)", fontsize=14)
skew.ax.set_ylabel("Pressure (hPa)", fontsize=14)
lines.append(
skew.plot(
1000,
model.Ts - climlab.constants.tempCtoK,
"o",
markersize=8,
color="C0",
)[0]
)
return fig, lines
def animate(day, model, lines):
lines[0].set_xdata(np.array(model.Tatm) - climlab.constants.tempCtoK)
lines[1].set_xdata(np.array(model.Ts) - climlab.constants.tempCtoK)
# lines[2].set_xdata(np.array(model.q)*1E3)
# lines[-1].set_text('Day {}'.format(int(model.time['days_elapsed'])))
# This is kind of a hack, but without it the initial frame doesn't appear
if day != 0:
model.step_forward()
return lines
# to setup the skewT and plot observations
def make_basic_skewT():
fig = plt.figure(figsize=(9, 9))
skew = SkewT(fig, rotation=30)
skew.plot(
Tglobal.level,
Tglobal,
color="black",
linestyle="-",
linewidth=2,
label="Observations",
)
skew.ax.set_ylim(1050, 10)
skew.ax.set_xlim(-90, 45)
# Add the relevant special lines
# skew.plot_dry_adiabats(linewidth=1.5, label = 'dry adiabats')
# skew.plot_moist_adiabats(linewidth=1.5, label = 'moist adiabats')
# skew.plot_mixing_lines()
skew.ax.legend()
skew.ax.set_xlabel("Temperature (degC)", fontsize=14)
skew.ax.set_ylabel("Pressure (hPa)", fontsize=14)
return skew
# to setup the skewT and plot observations
def make_skewT():
fig = plt.figure(figsize=(9, 9))
skew = SkewT(fig, rotation=30)
skew.plot(
Tglobal.level,
Tglobal,
color="black",
linestyle="-",
linewidth=2,
label="Observations",
)
skew.ax.set_ylim(1050, 10)
skew.ax.set_xlim(-90, 45)
# Add the relevant special lines
skew.plot_dry_adiabats(linewidth=1.5, label="dry adiabats")
# skew.plot_moist_adiabats(linewidth=1.5, label = 'moist adiabats')
# skew.plot_mixing_lines()
skew.ax.legend()
skew.ax.set_xlabel("Temperature (degC)", fontsize=14)
skew.ax.set_ylabel("Pressure (hPa)", fontsize=14)
return skew
# to add a model derived profile to the skewT figure
def add_profile(skew, model, linestyle="-", color=None):
line = skew.plot(
model.lev,
model.Tatm - climlab.constants.tempCtoK,
label=model.name,
linewidth=2,
)[0]
skew.plot(
1000,
model.Ts - climlab.constants.tempCtoK,
"o",
markersize=8,
color=line.get_color(),
)
skew.ax.legend()
Video 1: Radiative-Convective Equilibrium#
Submit your feedback#
Show code cell source
# @title Submit your feedback
content_review(f"{feedback_prefix}_Radiative_Convective_Equilibrium_Video")
If you want to download the slides: https://osf.io/download/msarf/
Submit your feedback#
Show code cell source
# @title Submit your feedback
content_review(f"{feedback_prefix}_Radiative_Convective_Equilibrium_Slides")
Section 1: Reproducing Data from the Last Tutorial’s One-dimensional Radiative Equilibrium Model Using Climlab#
Please refer to the previous Bonus Tutorial 6 for a refresher if needed.
filename_sq = "cpl_1850_f19-Q-gw-only.cam.h0.nc"
url_sq = "https://osf.io/c6q4j/download/"
ds = xr.open_dataset(
pooch_load(filelocation=url_sq, filename=filename_sq)
) # ds = dataset
filename_ncep_air = "air.mon.1981-2010.ltm.nc"
url_ncep_air = "https://osf.io/w6cd5/download/"
ncep_air = xr.open_dataset(
pooch_load(filelocation=url_ncep_air, filename=filename_ncep_air)
) # ds = dataset
# take global, annual average of specific humidity
weight_factor = ds.gw / ds.gw.mean(dim="lat")
Qglobal = (ds.Q * weight_factor).mean(dim=("lat", "lon", "time"))
# use 'lev=Qglobal.lev' to create an identical vertical grid to water vapor data
mystate = climlab.column_state(lev=Qglobal.lev, water_depth=2.5)
radmodel = climlab.radiation.RRTMG(
name="Radiation (all gases)", # give our model a name
state=mystate, # give our model an initial condition
specific_humidity=Qglobal.values, # tell the model how much water vapor there is
albedo=0.25, # set the SURFACE shortwave albedo
timestep=climlab.constants.seconds_per_day, # set the timestep to one day (measured in seconds)
)
# need to take the average over space and time
# the grid cells are not the same size moving towards the poles, so we weight by the cosine of latitude to compensate for this
coslat = np.cos(np.deg2rad(ncep_air.lat))
weight = coslat / coslat.mean(dim="lat")
# global mean temperature from NCEP
Tglobal = (ncep_air.air * weight).mean(dim=("lat", "lon", "time"))
# take a single step forward until the diagnostics are updated and there is some energy imbalance
radmodel.step_forward()
# run the model to equilibrium (the difference between ASR and OLR is a very small number)
while np.abs(radmodel.ASR - radmodel.OLR) > 0.001:
radmodel.step_forward()
skew = make_basic_skewT()
add_profile(skew, radmodel)
skew.ax.set_title("Pure Radiative Equilibrium")
/home/runner/micromamba/envs/climatematch/lib/python3.11/site-packages/xarray/coding/times.py:995: SerializationWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using cftime.datetime objects instead, reason: dates out of range
dtype = _decode_cf_datetime_dtype(data, units, calendar, self.use_cftime)
/home/runner/micromamba/envs/climatematch/lib/python3.11/site-packages/xarray/coding/times.py:170: SerializationWarning: Ambiguous reference date string: 1-1-1 00:00:0.0. The first value is assumed to be the year hence will be padded with zeros to remove the ambiguity (the padded reference date string is: 0001-1-1 00:00:0.0). To remove this message, remove the ambiguity by padding your reference date strings with zeros.
warnings.warn(warning_msg, SerializationWarning)
/home/runner/micromamba/envs/climatematch/lib/python3.11/site-packages/xarray/core/indexing.py:557: SerializationWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using cftime.datetime objects instead, reason: dates out of range
array = array.get_duck_array()
Downloading data from 'http://www.atmos.albany.edu/facstaff/brose/resources/climlab_data/ozone/apeozone_cam3_5_54.nc' to file '/home/runner/.cache/pooch/0e7ac27a9b97c3a843dcfdd7cd89a9b7-apeozone_cam3_5_54.nc'.
---------------------------------------------------------------------------
TimeoutError Traceback (most recent call last)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:239, in HTTPConnection._new_conn(self)
238 try:
--> 239 sock = connection.create_connection(
240 (self._dns_host, self.port),
241 self.timeout,
242 source_address=self.source_address,
243 socket_options=self.socket_options,
244 )
245 except socket.gaierror as e:
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/util/connection.py:85, in create_connection(address, timeout, source_address, socket_options)
84 try:
---> 85 raise err
86 finally:
87 # Break explicitly a reference cycle
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/util/connection.py:73, in create_connection(address, timeout, source_address, socket_options)
72 sock.bind(source_address)
---> 73 sock.connect(sa)
74 # Break explicitly a reference cycle
TimeoutError: timed out
The above exception was the direct cause of the following exception:
ConnectTimeoutError Traceback (most recent call last)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connectionpool.py:793, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
792 # Make the request on the HTTPConnection object
--> 793 response = self._make_request(
794 conn,
795 method,
796 url,
797 timeout=timeout_obj,
798 body=body,
799 headers=headers,
800 chunked=chunked,
801 retries=retries,
802 response_conn=response_conn,
803 preload_content=preload_content,
804 decode_content=decode_content,
805 **response_kw,
806 )
808 # Everything went great!
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connectionpool.py:499, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
498 try:
--> 499 conn.request(
500 method,
501 url,
502 body=body,
503 headers=headers,
504 chunked=chunked,
505 preload_content=preload_content,
506 decode_content=decode_content,
507 enforce_content_length=enforce_content_length,
508 )
510 # We are swallowing BrokenPipeError (errno.EPIPE) since the server is
511 # legitimately able to close the connection after sending a valid response.
512 # With this behaviour, the received response is still readable.
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:567, in HTTPConnection.request(self, method, url, body, headers, chunked, preload_content, decode_content, enforce_content_length)
566 self.putheader(header, value)
--> 567 self.endheaders()
569 # If we're given a body we start sending that in chunks.
File ~/micromamba/envs/climatematch/lib/python3.11/http/client.py:1346, in HTTPConnection.endheaders(self, message_body, encode_chunked)
1345 raise CannotSendHeader()
-> 1346 self._send_output(message_body, encode_chunked=encode_chunked)
File ~/micromamba/envs/climatematch/lib/python3.11/http/client.py:1106, in HTTPConnection._send_output(self, message_body, encode_chunked)
1105 del self._buffer[:]
-> 1106 self.send(msg)
1108 if message_body is not None:
1109
1110 # create a consistent interface to message_body
File ~/micromamba/envs/climatematch/lib/python3.11/http/client.py:1044, in HTTPConnection.send(self, data)
1043 if self.auto_open:
-> 1044 self.connect()
1045 else:
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:398, in HTTPConnection.connect(self)
397 def connect(self) -> None:
--> 398 self.sock = self._new_conn()
399 if self._tunnel_host:
400 # If we're tunneling it means we're connected to our proxy.
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:248, in HTTPConnection._new_conn(self)
247 except SocketTimeout as e:
--> 248 raise ConnectTimeoutError(
249 self,
250 f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
251 ) from e
253 except OSError as e:
ConnectTimeoutError: (<HTTPConnection(host='www.atmos.albany.edu', port=80) at 0x7999a83a63d0>, 'Connection to www.atmos.albany.edu timed out. (connect timeout=30)')
The above exception was the direct cause of the following exception:
MaxRetryError Traceback (most recent call last)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/adapters.py:696, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
695 try:
--> 696 resp = conn.urlopen(
697 method=request.method,
698 url=url,
699 body=request.body, # type: ignore[arg-type] # urllib3 stubs don't accept Iterable[bytes | str]
700 headers=request.headers, # type: ignore[arg-type] # urllib3#3072
701 redirect=False,
702 assert_same_host=False,
703 preload_content=False,
704 decode_content=False,
705 retries=self.max_retries,
706 timeout=resolved_timeout,
707 chunked=chunked,
708 )
710 except (ProtocolError, OSError) as err:
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connectionpool.py:847, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
845 new_e = ProtocolError("Connection aborted.", new_e)
--> 847 retries = retries.increment(
848 method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
849 )
850 retries.sleep()
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/util/retry.py:555, in Retry.increment(self, method, url, response, error, _pool, _stacktrace)
554 reason = error or ResponseError(cause)
--> 555 raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
557 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
MaxRetryError: HTTPConnectionPool(host='www.atmos.albany.edu', port=80): Max retries exceeded with url: /facstaff/brose/resources/climlab_data/ozone/apeozone_cam3_5_54.nc (Caused by ConnectTimeoutError(<HTTPConnection(host='www.atmos.albany.edu', port=80) at 0x7999a83a63d0>, 'Connection to www.atmos.albany.edu timed out. (connect timeout=30)'))
During handling of the above exception, another exception occurred:
ConnectTimeout Traceback (most recent call last)
Cell In[11], line 20
16
17 # use 'lev=Qglobal.lev' to create an identical vertical grid to water vapor data
18 mystate = climlab.column_state(lev=Qglobal.lev, water_depth=2.5)
19
---> 20 radmodel = climlab.radiation.RRTMG(
21 name="Radiation (all gases)", # give our model a name
22 state=mystate, # give our model an initial condition
23 specific_humidity=Qglobal.values, # tell the model how much water vapor there is
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/rrtm/rrtmg.py:125, in RRTMG.__init__(self, icld, irng, idrv, permuteseed_sw, permuteseed_lw, dyofyr, inflgsw, inflglw, iceflgsw, iceflglw, liqflgsw, liqflglw, tauc_sw, tauc_lw, ssac_sw, asmc_sw, fsfc_sw, iaer, tauaer_sw, ssaaer_sw, asmaer_sw, ecaer_sw, tauaer_lw, isolvar, indsolvar, bndsolvar, solcycfrac, **kwargs)
13 def __init__(self,
14 # GENERAL, used in both SW and LW
15 icld = 1, # Cloud overlap method, 0: Clear only, 1: Random, 2, Maximum/random] 3: Maximum
(...) 123
124 **kwargs):
--> 125 super(RRTMG, self).__init__(**kwargs)
127 # Remove specific inputs from kwargs dictionary.
128 # We want any changes implemented in the parent __init__ method to be preserved here
129 remove_list = ['absorber_vmr','cldfrac','clwp','ciwp','r_liq','r_ice',
130 'emissivity','aldif','aldir','asdif','asdir','S0','coszen',
131 'irradiance_factor','insolation',]
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:216, in _Radiation_SW.__init__(self, albedo, aldif, aldir, asdif, asdir, S0, insolation, coszen, irradiance_factor, **kwargs)
205 def __init__(self,
206 albedo = None,
207 aldif = 0.3,
(...) 214 irradiance_factor = 1., # instantaneous irradiance = S0 * irradiance_factor
215 **kwargs):
--> 216 super(_Radiation_SW, self).__init__(**kwargs)
217 self.add_input('S0', S0)
218 self.add_input('coszen', coszen)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:273, in _Radiation_LW.__init__(self, emissivity, **kwargs)
270 def __init__(self,
271 emissivity = 1., # surface emissivity
272 **kwargs):
--> 273 super(_Radiation_LW, self).__init__(**kwargs)
274 self.add_input('emissivity', emissivity)
275 # initialize diagnostics
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:193, in _Radiation.__init__(self, specific_humidity, absorber_vmr, cldfrac, clwp, ciwp, r_liq, r_ice, ozone_file, **kwargs)
191 self.add_input('specific_humidity', specific_humidity)
192 if absorber_vmr is None:
--> 193 absorber_vmr = default_absorbers(self.Tatm, ozone_file, self.verbose)
194 self.add_input('absorber_vmr', absorber_vmr)
195 self.add_input('cldfrac', cldfrac)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:137, in default_absorbers(Tatm, ozone_file, verbose)
135 if ozone_file is not None:
136 ozonepath_http = _datapath_http + 'ozone/' + ozone_file
--> 137 ozonefilehandle = pooch.retrieve(url=ozonepath_http,
138 known_hash="bc659bfa129fafa4ed9368bb19278ae15724a5a66599affd317c143ba511ff84")
139 ozonedata = xr.open_dataset(ozonefilehandle)
140 ## zonal and time average
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/pooch/core.py:242, in retrieve(url, known_hash, fname, path, processor, downloader, progressbar)
239 if downloader is None:
240 downloader = choose_downloader(url, progressbar=progressbar)
--> 242 stream_download(url, full_path, known_hash, downloader, pooch=None)
244 if known_hash is None:
245 get_logger().info(
246 "SHA256 hash of downloaded file: %s\n"
247 "Use this value as the 'known_hash' argument of 'pooch.retrieve'"
(...) 250 file_hash(str(full_path)),
251 )
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/pooch/core.py:823, in stream_download(url, fname, known_hash, downloader, pooch, retry_if_failed)
819 try:
820 # Stream the file to a temporary so that we can safely check its
821 # hash before overwriting the original.
822 with temporary_file(path=str(fname.parent)) as tmp:
--> 823 downloader(url, tmp, pooch)
824 hash_matches(tmp, known_hash, strict=True, source=str(fname.name))
825 shutil.move(tmp, str(fname))
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/pooch/downloaders.py:230, in HTTPDownloader.__call__(self, url, output_file, pooch, check_only)
228 # pylint: enable=consider-using-with
229 try:
--> 230 response = requests.get(url, timeout=timeout, **kwargs)
231 response.raise_for_status()
232 content = response.iter_content(chunk_size=self.chunk_size)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/api.py:87, in get(url, params, **kwargs)
74 def get(
75 url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs]
76 ) -> Response:
77 r"""Sends a GET request.
78
79 :param url: URL for the new :class:`Request` object.
(...) 84 :rtype: requests.Response
85 """
---> 87 return request("get", url, params=params, **kwargs)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/api.py:71, in request(method, url, **kwargs)
67 # By using the 'with' statement we are sure the session is closed, thus we
68 # avoid leaving sockets open which can trigger a ResourceWarning in some
69 # cases, and look like a memory leak in others.
70 with sessions.Session() as session:
---> 71 return session.request(method=method, url=url, **kwargs)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/sessions.py:651, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
646 send_kwargs = {
647 "timeout": timeout,
648 "allow_redirects": allow_redirects,
649 }
650 send_kwargs.update(settings)
--> 651 resp = self.send(prep, **send_kwargs)
653 return resp
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/sessions.py:784, in Session.send(self, request, **kwargs)
781 start = preferred_clock()
783 # Send the request
--> 784 r = adapter.send(request, **kwargs)
786 # Total elapsed time of the request (approximately)
787 elapsed = preferred_clock() - start
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/adapters.py:717, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
714 if isinstance(e.reason, ConnectTimeoutError):
715 # TODO: Remove this in 3.0.0: see #2811
716 if not isinstance(e.reason, NewConnectionError):
--> 717 raise ConnectTimeout(e, request=request)
719 if isinstance(e.reason, ResponseError):
720 raise RetryError(e, request=request)
ConnectTimeout: HTTPConnectionPool(host='www.atmos.albany.edu', port=80): Max retries exceeded with url: /facstaff/brose/resources/climlab_data/ozone/apeozone_cam3_5_54.nc (Caused by ConnectTimeoutError(<HTTPConnection(host='www.atmos.albany.edu', port=80) at 0x7999a83a63d0>, 'Connection to www.atmos.albany.edu timed out. (connect timeout=30)'))
Section 2: Radiative-Convective Equilibrium#
From the plot you just made, one of the largest differences between observations and the pure radiation model with all gases lies in the lower atmosphere, where the surface air temperature is 20 degrees too warm and the 200 hPa pressure surface is 40 degrees too cold. What could be the issue?
One thing we have not included in our model yet is dynamics (motion of the air). The model’s temperature profile is what’s known as statically unstable (note this definition of stability is different than that used in the previous tutorials).
Here static means not due to wind, and unstable means the atmosphere wants to adjust to a different state because the surface air is relatively light and wants to rise into upper layers of the atmosphere. As the air rises, it creates convective turbulence (similar to boiling water, where convective circulation is introduced by heating water from below). The rising air, and the resultant turbulence, mixes the atmospheric column. This mixing often occurs across the troposphere, which is roughly the lowest \(10 \text{ km}\) of the atmosphere. Most of the weather we experience lies in the troposphere.
When air rises adiabatically, it expands and cools due to the lower pressure. The rate of cooling depends on whether the air is saturated with water vapor. When rising air is unsaturated, it cools following the dry adiabats. If the air saturates, it cools at a lesser rate denoted by the moist adiabats (we did not have time to discuss these moisture effects in the mini-lecture).
To identify unstable atmospheric layers, let’s take another look at the SkewT plot, but this time we will plot the dry adiabats. We can then compare the rates of cooling of our model to these adiabats.
skew = make_skewT()
add_profile(skew, radmodel)
skew.ax.set_title("Pure Radiative Equilibrium")
Near the surface, the reanalysis temperature profile is steeper than the dry adiabats. In these layers vertical motion is inhibited, and the surface conditions are considered stable. However, the model profile is shallower than the dry adiabats. In the model, the surface air is statically unstable, which would lead to convective mixing if this physical process was included in the model (the model currently only includes radiative processes). In this tutorial we will see whether including convective mixing in our model can bring the model closer to the reanalysis temperature profile.
To build a radiative-convective model we can take the radiative model we have already made and couple it to a convective model. Here the term couple implies there is communication between the models such that their effects are both incorporated into the final product, which in our case is the temperature profile.
# restate the model here for ease of coding
# make a model on same vertical domain as the water vapor data
mystate = climlab.column_state(lev=Qglobal.lev, water_depth=2.5)
# create the radiation model
rad = climlab.radiation.RRTMG(
name="Radiation (net)",
state=mystate,
specific_humidity=Qglobal.values,
timestep=climlab.constants.seconds_per_day,
albedo=0.25, # surface albedo, tuned to give reasonable ASR for reference cloud-free model
)
# create the convection model
conv = climlab.convection.ConvectiveAdjustment(
name="Convection",
state=mystate,
adj_lapse_rate=6.5, # the adiabatic lapse rate of the atmopshere
timestep=rad.timestep, # same timestep as radiation model
)
# couple the two components
rcm = climlab.couple([rad, conv], name="Radiative-Convective Model")
Downloading data from 'http://www.atmos.albany.edu/facstaff/brose/resources/climlab_data/ozone/apeozone_cam3_5_54.nc' to file '/home/runner/.cache/pooch/0e7ac27a9b97c3a843dcfdd7cd89a9b7-apeozone_cam3_5_54.nc'.
---------------------------------------------------------------------------
TimeoutError Traceback (most recent call last)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:239, in HTTPConnection._new_conn(self)
238 try:
--> 239 sock = connection.create_connection(
240 (self._dns_host, self.port),
241 self.timeout,
242 source_address=self.source_address,
243 socket_options=self.socket_options,
244 )
245 except socket.gaierror as e:
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/util/connection.py:85, in create_connection(address, timeout, source_address, socket_options)
84 try:
---> 85 raise err
86 finally:
87 # Break explicitly a reference cycle
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/util/connection.py:73, in create_connection(address, timeout, source_address, socket_options)
72 sock.bind(source_address)
---> 73 sock.connect(sa)
74 # Break explicitly a reference cycle
TimeoutError: timed out
The above exception was the direct cause of the following exception:
ConnectTimeoutError Traceback (most recent call last)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connectionpool.py:793, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
792 # Make the request on the HTTPConnection object
--> 793 response = self._make_request(
794 conn,
795 method,
796 url,
797 timeout=timeout_obj,
798 body=body,
799 headers=headers,
800 chunked=chunked,
801 retries=retries,
802 response_conn=response_conn,
803 preload_content=preload_content,
804 decode_content=decode_content,
805 **response_kw,
806 )
808 # Everything went great!
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connectionpool.py:499, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
498 try:
--> 499 conn.request(
500 method,
501 url,
502 body=body,
503 headers=headers,
504 chunked=chunked,
505 preload_content=preload_content,
506 decode_content=decode_content,
507 enforce_content_length=enforce_content_length,
508 )
510 # We are swallowing BrokenPipeError (errno.EPIPE) since the server is
511 # legitimately able to close the connection after sending a valid response.
512 # With this behaviour, the received response is still readable.
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:567, in HTTPConnection.request(self, method, url, body, headers, chunked, preload_content, decode_content, enforce_content_length)
566 self.putheader(header, value)
--> 567 self.endheaders()
569 # If we're given a body we start sending that in chunks.
File ~/micromamba/envs/climatematch/lib/python3.11/http/client.py:1346, in HTTPConnection.endheaders(self, message_body, encode_chunked)
1345 raise CannotSendHeader()
-> 1346 self._send_output(message_body, encode_chunked=encode_chunked)
File ~/micromamba/envs/climatematch/lib/python3.11/http/client.py:1106, in HTTPConnection._send_output(self, message_body, encode_chunked)
1105 del self._buffer[:]
-> 1106 self.send(msg)
1108 if message_body is not None:
1109
1110 # create a consistent interface to message_body
File ~/micromamba/envs/climatematch/lib/python3.11/http/client.py:1044, in HTTPConnection.send(self, data)
1043 if self.auto_open:
-> 1044 self.connect()
1045 else:
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:398, in HTTPConnection.connect(self)
397 def connect(self) -> None:
--> 398 self.sock = self._new_conn()
399 if self._tunnel_host:
400 # If we're tunneling it means we're connected to our proxy.
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connection.py:248, in HTTPConnection._new_conn(self)
247 except SocketTimeout as e:
--> 248 raise ConnectTimeoutError(
249 self,
250 f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
251 ) from e
253 except OSError as e:
ConnectTimeoutError: (<HTTPConnection(host='www.atmos.albany.edu', port=80) at 0x7999a819ec50>, 'Connection to www.atmos.albany.edu timed out. (connect timeout=30)')
The above exception was the direct cause of the following exception:
MaxRetryError Traceback (most recent call last)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/adapters.py:696, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
695 try:
--> 696 resp = conn.urlopen(
697 method=request.method,
698 url=url,
699 body=request.body, # type: ignore[arg-type] # urllib3 stubs don't accept Iterable[bytes | str]
700 headers=request.headers, # type: ignore[arg-type] # urllib3#3072
701 redirect=False,
702 assert_same_host=False,
703 preload_content=False,
704 decode_content=False,
705 retries=self.max_retries,
706 timeout=resolved_timeout,
707 chunked=chunked,
708 )
710 except (ProtocolError, OSError) as err:
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/connectionpool.py:847, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
845 new_e = ProtocolError("Connection aborted.", new_e)
--> 847 retries = retries.increment(
848 method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
849 )
850 retries.sleep()
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/urllib3/util/retry.py:555, in Retry.increment(self, method, url, response, error, _pool, _stacktrace)
554 reason = error or ResponseError(cause)
--> 555 raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
557 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
MaxRetryError: HTTPConnectionPool(host='www.atmos.albany.edu', port=80): Max retries exceeded with url: /facstaff/brose/resources/climlab_data/ozone/apeozone_cam3_5_54.nc (Caused by ConnectTimeoutError(<HTTPConnection(host='www.atmos.albany.edu', port=80) at 0x7999a819ec50>, 'Connection to www.atmos.albany.edu timed out. (connect timeout=30)'))
During handling of the above exception, another exception occurred:
ConnectTimeout Traceback (most recent call last)
Cell In[13], line 7
3 # make a model on same vertical domain as the water vapor data
4 mystate = climlab.column_state(lev=Qglobal.lev, water_depth=2.5)
5
6 # create the radiation model
----> 7 rad = climlab.radiation.RRTMG(
8 name="Radiation (net)",
9 state=mystate,
10 specific_humidity=Qglobal.values,
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/rrtm/rrtmg.py:125, in RRTMG.__init__(self, icld, irng, idrv, permuteseed_sw, permuteseed_lw, dyofyr, inflgsw, inflglw, iceflgsw, iceflglw, liqflgsw, liqflglw, tauc_sw, tauc_lw, ssac_sw, asmc_sw, fsfc_sw, iaer, tauaer_sw, ssaaer_sw, asmaer_sw, ecaer_sw, tauaer_lw, isolvar, indsolvar, bndsolvar, solcycfrac, **kwargs)
13 def __init__(self,
14 # GENERAL, used in both SW and LW
15 icld = 1, # Cloud overlap method, 0: Clear only, 1: Random, 2, Maximum/random] 3: Maximum
(...) 123
124 **kwargs):
--> 125 super(RRTMG, self).__init__(**kwargs)
127 # Remove specific inputs from kwargs dictionary.
128 # We want any changes implemented in the parent __init__ method to be preserved here
129 remove_list = ['absorber_vmr','cldfrac','clwp','ciwp','r_liq','r_ice',
130 'emissivity','aldif','aldir','asdif','asdir','S0','coszen',
131 'irradiance_factor','insolation',]
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:216, in _Radiation_SW.__init__(self, albedo, aldif, aldir, asdif, asdir, S0, insolation, coszen, irradiance_factor, **kwargs)
205 def __init__(self,
206 albedo = None,
207 aldif = 0.3,
(...) 214 irradiance_factor = 1., # instantaneous irradiance = S0 * irradiance_factor
215 **kwargs):
--> 216 super(_Radiation_SW, self).__init__(**kwargs)
217 self.add_input('S0', S0)
218 self.add_input('coszen', coszen)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:273, in _Radiation_LW.__init__(self, emissivity, **kwargs)
270 def __init__(self,
271 emissivity = 1., # surface emissivity
272 **kwargs):
--> 273 super(_Radiation_LW, self).__init__(**kwargs)
274 self.add_input('emissivity', emissivity)
275 # initialize diagnostics
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:193, in _Radiation.__init__(self, specific_humidity, absorber_vmr, cldfrac, clwp, ciwp, r_liq, r_ice, ozone_file, **kwargs)
191 self.add_input('specific_humidity', specific_humidity)
192 if absorber_vmr is None:
--> 193 absorber_vmr = default_absorbers(self.Tatm, ozone_file, self.verbose)
194 self.add_input('absorber_vmr', absorber_vmr)
195 self.add_input('cldfrac', cldfrac)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/climlab/radiation/radiation.py:137, in default_absorbers(Tatm, ozone_file, verbose)
135 if ozone_file is not None:
136 ozonepath_http = _datapath_http + 'ozone/' + ozone_file
--> 137 ozonefilehandle = pooch.retrieve(url=ozonepath_http,
138 known_hash="bc659bfa129fafa4ed9368bb19278ae15724a5a66599affd317c143ba511ff84")
139 ozonedata = xr.open_dataset(ozonefilehandle)
140 ## zonal and time average
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/pooch/core.py:242, in retrieve(url, known_hash, fname, path, processor, downloader, progressbar)
239 if downloader is None:
240 downloader = choose_downloader(url, progressbar=progressbar)
--> 242 stream_download(url, full_path, known_hash, downloader, pooch=None)
244 if known_hash is None:
245 get_logger().info(
246 "SHA256 hash of downloaded file: %s\n"
247 "Use this value as the 'known_hash' argument of 'pooch.retrieve'"
(...) 250 file_hash(str(full_path)),
251 )
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/pooch/core.py:823, in stream_download(url, fname, known_hash, downloader, pooch, retry_if_failed)
819 try:
820 # Stream the file to a temporary so that we can safely check its
821 # hash before overwriting the original.
822 with temporary_file(path=str(fname.parent)) as tmp:
--> 823 downloader(url, tmp, pooch)
824 hash_matches(tmp, known_hash, strict=True, source=str(fname.name))
825 shutil.move(tmp, str(fname))
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/pooch/downloaders.py:230, in HTTPDownloader.__call__(self, url, output_file, pooch, check_only)
228 # pylint: enable=consider-using-with
229 try:
--> 230 response = requests.get(url, timeout=timeout, **kwargs)
231 response.raise_for_status()
232 content = response.iter_content(chunk_size=self.chunk_size)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/api.py:87, in get(url, params, **kwargs)
74 def get(
75 url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs]
76 ) -> Response:
77 r"""Sends a GET request.
78
79 :param url: URL for the new :class:`Request` object.
(...) 84 :rtype: requests.Response
85 """
---> 87 return request("get", url, params=params, **kwargs)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/api.py:71, in request(method, url, **kwargs)
67 # By using the 'with' statement we are sure the session is closed, thus we
68 # avoid leaving sockets open which can trigger a ResourceWarning in some
69 # cases, and look like a memory leak in others.
70 with sessions.Session() as session:
---> 71 return session.request(method=method, url=url, **kwargs)
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/sessions.py:651, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
646 send_kwargs = {
647 "timeout": timeout,
648 "allow_redirects": allow_redirects,
649 }
650 send_kwargs.update(settings)
--> 651 resp = self.send(prep, **send_kwargs)
653 return resp
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/sessions.py:784, in Session.send(self, request, **kwargs)
781 start = preferred_clock()
783 # Send the request
--> 784 r = adapter.send(request, **kwargs)
786 # Total elapsed time of the request (approximately)
787 elapsed = preferred_clock() - start
File ~/micromamba/envs/climatematch/lib/python3.11/site-packages/requests/adapters.py:717, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
714 if isinstance(e.reason, ConnectTimeoutError):
715 # TODO: Remove this in 3.0.0: see #2811
716 if not isinstance(e.reason, NewConnectionError):
--> 717 raise ConnectTimeout(e, request=request)
719 if isinstance(e.reason, ResponseError):
720 raise RetryError(e, request=request)
ConnectTimeout: HTTPConnectionPool(host='www.atmos.albany.edu', port=80): Max retries exceeded with url: /facstaff/brose/resources/climlab_data/ozone/apeozone_cam3_5_54.nc (Caused by ConnectTimeoutError(<HTTPConnection(host='www.atmos.albany.edu', port=80) at 0x7999a819ec50>, 'Connection to www.atmos.albany.edu timed out. (connect timeout=30)'))
Now let’s run the radiation part to equilibrium, which should give us the same profile as in the previous section. Once we get this radiative equilibrium profile we will add convective mixing physics to the model and continue running it until it reaches radiative-convective equilibrium.
The new model does not actually resolve the actual vertical motion and mixing that occurs in convection. Instead, the model includes a parameterization for convection which automatically mixes regions of the atmospheric column that are statically unstable.
# run JUST the radiative component to equilibrium
for n in range(1000):
rcm.subprocess["Radiation (net)"].step_forward()
# compute diagnostics
rcm.compute_diagnostics()
# plot the resulting profile (our initial condition once we turn on the physics)
fig, lines = initial_figure(rcm)
# this animation can take a while
animation.FuncAnimation(fig, animate, 50, fargs=(rcm, lines))
Adding convective mixing to the initially unstable temperature profile leads to an instant mixing of air throughout the lower atmosphere, moving the profile toward the observations. The balance at play is between radiative processes that warm the surface and cool the troposphere (lower atmosphere) as well as convection which moves heat away from the surface, leading to a colder surface and warmer troposphere. Note the differences in surface versus tropospheric temperatures in the new versus old equilibrium profiles.
Questions 2: Climate Connection#
The static instability was removed in the first time step! In reality, which process do you think changes temperature faster, convection or radiation?
What do you think the next step would be to move towards a more realistic climate model?
Submit your feedback#
Show code cell source
# @title Submit your feedback
content_review(f"{feedback_prefix}_Questions_2")
Coding Exercises 2#
Recreate the video above except using an isothermal atmosphere (uniform temperature profile) set to the surface temperature
rcm.state.Ts. Does the equilbrium profile look any different than the one you made before?
# set initial temperature profile to be the surface temperature (isothermal)
rcm.state.Tatm[:] = rcm.state.Ts
# compute diagnostics
_ = ...
# plot initial data
fig, lines = initial_figure(rcm)
# make animation - this animation can take a while
# animation.FuncAnimation(fig, animate, 50, fargs=(rcm, lines))
Submit your feedback#
Show code cell source
# @title Submit your feedback
content_review(f"{feedback_prefix}_Coding_Exercises_2")
Summary#
In this tutorial, you explored the concept of radiative-convective equilibrium, learning to implement a Python model using the climlab package. You learned the limitations of a pure radiation model and the necessity to include atmospheric dynamics such as convection. Through coupling a radiation model with a convective model, you have simulated a more realistic atmospheric temperature profile. Even though the model does not directly resolve the vertical motion during convection, it incorporates a parameterization to automatically account for mixing in statically unstable regions. By the end of the tutorial, you could comprehend how this model expands on the previous energy balance models from tutorials 1-4.
Resources#
Data from this tutorial can be accessed for specific humidity here and reanalysis temperature here.
Useful links:
The Climate Laboratory by Brian E. J. Rose,