1 of 80

Join at slido.com�#3153196

Start presenting to display the joining instructions on this slide.

3153196

3153196

2 of 80

3153196

3153196

3 of 80

Climate Data Science and XArray

Data 100/Data 200, Spring 2023 @ UC Berkeley

Guest Lecture: Fernando Pérez

Lecture materials by: Dr. Chelle Gentemann, NASA

3

Lecture 19

4 of 80

About the author of these materials

Dr. Chelle Gentemann

More: @ChelleGentemann

3153196

3153196

5 of 80

The foundation of climate change: the Greenhouse Effect

3153196

6 of 80

Climate Change

A simplified animation of the greenhouse effect. Credit: NASA/JPL-Caltech

3153196

3153196

7 of 80

Video credit: NASA SVS

3153196

3153196

8 of 80

Video credit: NASA SVS

3153196

3153196

9 of 80

What does the data say about our climate?

3153196

10 of 80

Keeling Curve

  • In 1958 Keeling got a grant to begin monitoring CO2 in Hawaii.
  • Roger Revelle (a famous scientist) argued that they just needed a snapshot - CO2 was too variable - and another snapshot 20 years later to show that CO2 was increasing
  • Keeling advocated for precise measurements over time. By the mid-1960s we had both a measurement of the Earth’s breathing and the global increase in CO2.
  • How would you remake this figure?

https://pubs.acs.org/doi/10.1021/ac1001492

3153196

11 of 80

Video credit: NASA SVS

3153196

3153196

12 of 80

Calculating the Greenhouse Effect

Goal 1: Calculate how the temperature is changing with increasing CO2.

The Planetary energy balance:

Energy (from the Sun) absorbed = Energy emitted

How does CO2 affects this?

  1. The Sun emits radiation that is absorbed by the Earth (~30% is reflected by clouds, ice/snow, desert, this is the albedo)
  2. The Earth emits radiation according to Stephan-Boltzman’s Law: the rate that a body emits radiation (per unit area) is directly proportional to the body's absolute temperature to the fourth power (blackbody radiation)
  3. The emitted radiation doesn’t all go back into space……..

3153196

13 of 80

Calculate energy in

  1. The Sun emits radiation absorbed by the Earth

Energy in equals the incoming sunlight (W/m2) multiplied by the area (m2) to get W

NASA illustrations by Robert Simmon

= Incoming sunlight x area

r

3153196

14 of 80

Some of the energy in is reflected by the atmosphere

  • The Sun emits radiation absorbed by the Earth (some is reflected by the atmosphere)

NASA illustrations by Robert Simmon

r

Albedo = the fraction of radiation reflected back to space by the atmosphere

The amount that gets through:

Reflective surface

3153196

15 of 80

Calculate Energy out

B) The Earth emits blackbody radiation

Energy out equals the emitted radiation (W/m2) multiplied by the area (m2) to get W

NASA illustrations by Robert Simmon

= Outgoing radiation x area

r

3153196

16 of 80

Energy in = Energy out

Goal 1: Calculate how the temperature is changing with increasing CO2

NASA illustrations by Robert Simmon

Reflective surface

Planetary energy balance

3153196

17 of 80

Calculating temperature

Goal 1: Calculate how the temperature is changing with increasing CO2

What is the Earth’s temperature?

~255 K

~-16 C

~1 F

3153196

18 of 80

3153196

19 of 80

Our atmosphere is like a blanket

  • Solve for the greenhouse effect!
  • What happens to the temperature if we increase the greenhouse effect?
  • What happens to the temperature if we decrease/increase the albedo?

without an atmosphere

Planetary energy balance

with an atmosphere

3153196

20 of 80

Calculating the Temperature dependence on CO2

Goal 1: Calculate how the temperature is changing with increasing CO2

CO2 is ~420 ppm (parts per million - co2.earth/daily-co2)

As CO2 increases what happens to the temperature?

3153196

21 of 80

Plot the results

Use the equation to calculate the increase in temperature with time due to the increase in CO2

3153196

22 of 80

Global warming is a climate crisis

The equation provides solutions to global warming:

Change the planetary albedo to reflect more radiation to space (increase aerosols, clouds, make surface more reflective)

Reduce greenhouse gases (CO2, Methane)

Sun-shades in space?

3153196

23 of 80

Changing by Alisa Singer

"As we witness our planet transforming around us we watch, listen, measure … respond."

www.environmentalgraphiti.org – 2021 Alisa Singer.

AR6 Climate Change 2021:

The Physical Science Basis

3153196

3153196

3153196

24 of 80

3153196

3153196

3153196

25 of 80

3153196

3153196

3153196

26 of 80

3153196

3153196

3153196

27 of 80

3153196

3153196

28 of 80

3153196

3153196

29 of 80

3153196

3153196

3153196

30 of 80

3153196

3153196

31 of 80

3153196

3153196

3153196

32 of 80

3153196

3153196

3153196

33 of 80

Let's check our understanding

This equation:

Shows that all climate change is due to CO2. If we stop CO2 emissions, we can stop climate change.

  • True
  • False

3153196

3153196

34 of 80

The given equation shows that all climate change is due to CO2. If we stop CO2 emissions, we can stop climate change.

Start presenting to display the poll results on this slide.

3153196

3153196

35 of 80

Image credit: NOAA

3153196

3153196

36 of 80

With every increment of global warming, changes get larger

https://www.ipcc.ch/report/ar6/wg1/#FullReport

3153196

37 of 80

… in precipitation

https://www.ipcc.ch/report/ar6/wg1/#FullReport

3153196

38 of 80

Our trajectory from data and models

https://raw.githubusercontent.com/BrodiePearson/IPCC_AR6_Chapter9_Figures/main/Plotting_code_and_data/Fig9_03_SST/Fig9_03_SST.png

3153196

39 of 80

Extremes are the new normal

3153196

40 of 80

Extremes are the new normal

A decade ago - scientists would argue - we can’t attribute any single weather event to climate.

In the last decade, we have all experienced major shifts in our climate through changes in our local weather and scientists have figured out ‘climate event attribution’

They look at the probability of the occurrence of an event (eg. a temperature extreme) in models run without human-influence and then compare it to the probability in models run with human-influence.

How?

https://www.nature.com/articles/d41586-021-01142-4

https://agupubs.onlinelibrary.wiley.com/doi/10.1029/2021GL092765

3153196

41 of 80

Extremes are the new normal

The probability of an event changes

https://www.nature.com/articles/s41467-019-09729-2/figures/1

Model runs with all forcings

Model runs with only natural

How likely is it that there will be a 2 degree anomaly?

3153196

42 of 80

Positive Feedbacks in the Climate System

3153196

43 of 80

Goal: Positive feedbacks in the climate system

The Earth is a system - a complicated game of dominos

As air temperature increases, sea ice concentration decreases…..

3153196

44 of 80

Goal: Arctic Amplification: a positive feedback

A positive feedback amplifies the initial perturbation

Albedo feedback:

  1. The albedo of sea ice is ~0.5-0.7. Most sunlight is reflected back to space.
  2. The albedo of the ocean is 0.04. Most sunlight is absorbed and warms the seawater.
  3. A warmer ocean melts more sea ice.

reflectivity!

3153196

45 of 80

Goal: Arctic Amplification: a positive feedback

A positive feedback amplifies the initial perturbation

Cloud feedback:

  • As sea ice melts, more ocean is exposed and more moisture is absorbed by the atmosphere
  • More moisture == more clouds
  • Clouds trap longwave radiation, warming the Arctic, melting more sea ice.

3153196

46 of 80

Can we look at this ourselves? --- this is global data --- 3D data

….. Latitude, longitude, and time…. How do we handle that?

https://www.nature.com/articles/s41467-019-09729-2/figures/1

Model runs with all forcings

Model runs with only natural

How likely is it that there will be a 2 degree anomaly?

3153196

47 of 80

Learning objective: climate data analysis

  • 3D data (time,latitude,longitude)
  • Introduction to Xarray python library
  • Xarray Probability density functions
  • Xarray linear regression: calculating mean trends
  • Xarray global analysis of trends

3153196

48 of 80

ERA5 - 5th gen ECMWF atmospheric global climate ReAnalyses

  • ERA5 combines vast amounts of historical observations into global estimates using advanced modelling and data assimilation systems.
  • From 1979 - 2019, hourly estimates of atmospheric, land and oceanic climate variables.
  • 30 km global grid, with 137 levels from the surface up to a height of 80 km.

An ECMWF snow depth analysis for Scandinavia using ERA5 data shows the highest levels in a decade.

3153196

49 of 80

Vast amount of data

  • The number of observations assimilated in ERA5 has increased from approximately 0.75 million per day on average in 1979 to around 24 million per day by the end of 2018
  • ~14,000 GB (14 TB)
  • A key dataset used for understanding our weather and climate, but inaccessible to all but a few privileged institutions

3153196

50 of 80

Data Frames are not enough: not all data is tabular

3153196

51 of 80

Xarray

Xarray introduces labels in the form of dimensions, coordinates and attributes on top of raw NumPy-like multidimensional arrays, which allows for a more intuitive, more concise, and less error-prone developer experience.

‘data variables’ : temperature and precipitation “data variables”

‘coordinate variables’: they label the points along the dimensions.

3153196

52 of 80

Xarray: Dataset

ERA5

Xarray Datasets are essentially groups of DataArrays.

This is really valuable when you are looking at datasets that have multidimensional groups of data, for example, temperature, precipitation, cloud cover.

Some Xarray methods can be applied to all that Dataset contains.

For example, you can subset a Dataset and the subset, interpolate, calculate a mean, and it will do this across all the DataArrays the Dataset contains.

3153196

53 of 80

Xarray read in a Dataset

  • 3D data
  • Dimensions: 504x90x180
  • Coordinates: time,latitude,longitude
  • 15 data variables (in DataArrays)
  • Attributes

import xarray as xr

ds = xr.open_dataset('./../data/era5_monthly_2deg_aws_v20210920.nc')

ds

3153196

54 of 80

Explore the data

Xarray allows you easily explore the data

Look at data attributes

3153196

55 of 80

Coordinates versus dimensions

  • DataArray objects inside a Dataset may have any number of dimensions but are presumed to share a common coordinate system.
  • Coordinates can also have any number of dimensions but denote constant/independent quantities, unlike the varying/dependent quantities that belong in data
  • A dimension is just a name of an axis, like ‘time’

Text from Xarray docs http://xarray.pydata.org/en/stable/user-guide/data-structures.html

3153196

56 of 80

DataArray are data variables in a Dataset

  • A DataArray holds a multi-dimensional information
  • DataArray objects inside a Dataset may have any number of dimensions but are presumed to share a common coordinate system.
  • You can explore the data easily using either syntax

ds["air_temperature_at_2_metres"]

ds.air_temperature_at_2_metres

Text from Xarray docs http://xarray.pydata.org/en/stable/user-guide/data-structures.html

3153196

57 of 80

Review: DataFrame access: [], loc, iloc

iloc: integer/positional

loc: Labels

[]: flexible, confusing?

  • Strings, integers - row/column labels
  • Lists - similar, but always return dataframes
  • Slices of labels: end-point inclusive!
  • Boolean arrays: “mask” selection.
  • Always 0-based, for rows and columns.
  • Slices as usual, end-point exclusive.
  • Use carefully (error prone).

[]

List

[]

Numeric Slice

[]

Name

DataFrame

DataFrame

Series

Single Column Selection

Multiple Column Selection

(Multiple) Row Selection

3153196

58 of 80

New: DataArray access: [], sel, isel

isel: integer/positional

sel: coordinates

[]: flexible, confusing?

  • Strings, integers - coordinates*
  • Slices: end-point inclusive!
  • Always 0-based
  • Slices as usual, end-point exclusive.
  • Use carefully (error prone).
  • Only for DataArrays

point = ds.isel(time=0,

latitude=26,

longitude=119)

point = ds.air_temperature_at_2_metres[0,26,119]

point = ds.sel(time="1979-01",

latitude=37.125,

longitude=238.875)

3153196

59 of 80

Find data at a point or in a region:

sel: coordinates

  • Strings, integers - coordinates*
  • Slices of coordinates: end-point inclusive!

point = ds.sel(time="1979-01",

latitude=37.125,

longitude=238.875)

region = ds.sel(time="1979-01",

latitude=slice(30,40),

longitude=slice(230,250))

Xarray helps you understand your code.

3153196

60 of 80

Xarray has all sort of high-level cool tricks built in

Select data and plot data in one line (using matplotlib)

ds.air_temperature_at_2_metres.sel(time="1979-01").plot()

ds.air_temperature_at_2_metres.sel(

latitude=37.125,

longitude=238.875).plot()

Select a variable

Select coordinate

Apply a method()

Select a variable

Select coordinate

Apply a method()

3153196

61 of 80

Methods can be called across a DataArray or a Dataset -- LAZY

Select data and plot data in one line (using matplotlib)

Same thing, but across all variables

ds.air_temperature_at_2_metres.mean("time").plot()

mean_map = ds.mean("time")

mean_map.air_temperature_at_2_metres.plot()

Select a variable

Apply a method() across a coordinate

Apply a method()

Lazy

3153196

62 of 80

Plot the global trend in a variable

  • Calculate a time series
  • Take out the annual cycle
  • Plot the trend

3153196

63 of 80

Goal: Calculate time series

Xarray has high level methods like .mean(), .std(), etc.

ave = ds.mean("time")

ave.air_temperature_at_2_metres.plot()

Take the mean across all time

ave = ds.mean(("latitude", "longitude"))

ave.air_temperature_at_2_metres.plot()

Take the mean across all locations

Does that look right?

(279 K ~ 6 ºC ~ 43 ºF)

3153196

64 of 80

The map is flat - but the Earth is not - Gaussian grid

Programs aren’t smart - you are - so what went wrong?

Gridded data is nice to work with but what does it represent?

How many grid points are at 90N (the North Pole)?

How many grid points are at the Equator?

3153196

65 of 80

Weigh your data

Xarray provides the ability to weigh your data

weights = np.cos(np.deg2rad(ds.latitude))

weights.name = "weights"

weights.plot()

3153196

66 of 80

Goal: Examine average values - weighted version

Xarray methods like .weighted() can be combined with .mean()

ds_weighted = ds.weighted(weights)

weighted_mean = ds_weighted.mean()

weighted_mean

Does that look right?

3153196

67 of 80

Goal: Weighted global time series data

You can create means across coordinates: eg. latitude and longitude

ds_weighted = ds.weighted(weights)

weighted_mean = ds_weighted.mean(("latitude", "longitude"))

weighted_mean.air_temperature_at_2_metres.plot()

288 K ~ 15 ºC ~ 59 ºF. 👍

3153196

68 of 80

Take out the annual cycle using .groupby()

Use .groupby on a coordinate

3153196

69 of 80

Goal: Calculate annual cycle

Can use .groupby & .mean

annual_cycle = weighted_mean.groupby("time.month").mean()

annual_cycle.air_temperature_at_2_metres.plot()

3153196

70 of 80

Put it all together and plot the trend

Can use .groupby & .mean

weighted_mean = ds_weighted.mean(("latitude", "longitude")) #weighted mean time series

annual_cycle = weighted_mean.groupby("time.month").mean() #calculate annual cycle

annual_cycle += annual_cycle.mean() #add back in the mean value

weighted_trend = weighted_mean.groupby("time.month") - annual_cycle

weighted_mean.air_temperature_at_2_metres.plot()

weighted_trend.air_temperature_at_2_metres.plot()

3153196

71 of 80

Goal: Are extremes more likely? PDF analysis.

xr.plot.hist(darray,

bins=bin_array,

density=True,

alpha=.9,

color="b",

)

3153196

72 of 80

ERA5 temperature PDFs

bins = np.arange(284, 291)

xr.plot.hist(

weighted_mean.air_temperature_at_2_metres.sel(time=slice("1980","2000")),

bins=bins,

density=True,

alpha=.9,

color="b",

)

xr.plot.hist(

weighted_mean.air_temperature_at_2_metres.sel(time=slice("2000","2020")),

bins=bins,

density=True,

alpha=.85,

color="r",

)

plt.ylabel("Probability Density (/K)")

3153196

73 of 80

Goal: Can we plot the trend with our ERA5 data?

pfit = ds.air_temperature_at_2_metres.polyfit("time", 1)

pfit.polyfit_coefficients[0] *= 3.154000000101e+16

pfit.polyfit_coefficients[0].plot(cbar_kwargs={"label":"trend deg/yr"})

3153196

74 of 80

Goal: How about all fancy on a globe?

import cartopy.crs as ccrs

p = pfit.polyfit_coefficients[0].plot(

subplot_kws=dict(projection=ccrs.Orthographic(0, 55), facecolor="gray"),

transform=ccrs.PlateCarree(central_longitude=0),

cbar_kwargs={"label": "trend deg/yr"},

)

p.axes.coastlines()

3153196

75 of 80

Goal: Positive feedbacks in the climate system

The Earth is a system - a complicated game of dominos

As air temperature increases, sea ice concentration decreases…..

3153196

76 of 80

Models and data tell us about our weather and climate

Xarray is a powerful tool to analyze climate data.

I’ve just given some simple examples here, but really, we need more eyes on the data, more eyes on the models.

The models use ‘parameterizations’ which are approximations for all sorts of different physical processes. Each parameterization uses coefficients derived fro data science - but the experiments may be limited or imperfect. Often parameters are adjusted to compensate for an error, but then end up causing other issues, and we are all still working on this.

We need more of you, more data scientists working with climate and weather scientists to look at this data, helping to find new discoveries, amplify messages about changes to our climate and their impacts, and build machine learning models to replace old parameterizations.

3153196

77 of 80

(Channeling Dr. Gentemann) I’m just an oceanographer

I started off like you, I’m just an oceanographer trying to find my way through the data science world. You are all data scientists maybe trying to find something interesting to work on.

Well, we all need your help. We need minds like yours to help solve the problems our and previous generations have caused. We need your voices, backed by solid data science, to mitigate what is going on, to change our trajectory.

I’ve shown you how to take pandas and leap to another level library, Xarray, you can do tutorials, leap to Scipy, or other libraries. I hope you enjoyed this small tour of Xarray and climate science.

3153196

78 of 80

79 of 80

https://science.nasa.gov/open-science/

https://github.com/nasa/Transform-to-Open-Science

to change everything, we need everyone

80 of 80

2023

NASA’s Year of

Open Science

80

NASA Transform to Open Science Mission

Dr. Chelle Gentemann, Science Lead

Yvonne Ivey, Equity Lead

Cyndi Hall, Community Coordinator

Isabella Martinez, Content Coordinator

Dr. Yaitza Luna-Cruz, TOPS Program Officer

Dr. Paige Martin, TOPS Program Officer

Kevin Murphy, Chief Science Data Officer SMD

Katie Baynes, Deputy Chief Science Data Officer SMD

Dr. Steve Crawford, Science Policy Officer SMD

Andy Mitchell,

Dr. Elena Steponaitis, SMD Development Program Executive

Amy (Uyen) Truong, Chief Science Data Office Coordinator

Dr. Rachel Paseka, OSSI Program Officer

Dr. J.L. Galache, OSSI Program Officer

Dr. Demitri Muna, OSSI Program Officer

Molly Adams, OSSI Coordinator

TOPS Email List

TOPS Website

SCIENCE MISSION DIRECTORATE