update notebook format, removed binary blobs

intro16
epifanio 2016-04-20 00:17:58 -04:00
parent c870a04a84
commit b13ebb491e
16 changed files with 6086 additions and 7729 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,42 +1,57 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1:\n",
"\n",
"1\\. Using the file in ``iris.sample_data_path('atlantic_profiles.nc')`` load the data and print the cube list. Store these cubes in a variable called cubes.\n",
"\n",
"2\\. Print a sorted list of unique names for the cubes.\n",
"\n",
"3\\. Extract the \"sea_water_potential_temperature\" cube. Print the minimum, maximum, mean and standard deviation of the cube's data.\n",
"\n",
"4\\. Print the attributes of the cube.\n",
"\n",
"5\\. Print the names of all coordinates on the cube. (Hint: Remember the cube.coords method)\n",
"\n",
"6\\. Get hold of the \"latitude\" coordinate on the cube. Identify whether the cube has bounds. Print the minimum and maximum latitude points in this cube."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1:\n",
"\n",
"1\\. Using the file in ``iris.sample_data_path('atlantic_profiles.nc')`` load the data and print the cube list. Store these cubes in a variable called cubes.\n",
"\n",
"2\\. Print a sorted list of unique names for the cubes.\n",
"\n",
"3\\. Extract the \"sea_water_potential_temperature\" cube. Print the minimum, maximum, mean and standard deviation of the cube's data.\n",
"\n",
"4\\. Print the attributes of the cube.\n",
"\n",
"5\\. Print the names of all coordinates on the cube. (Hint: Remember the cube.coords method)\n",
"\n",
"6\\. Get hold of the \"latitude\" coordinate on the cube. Identify whether the cube has bounds. Print the minimum and maximum latitude points in this cube."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": []
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

View File

@ -1,80 +1,79 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 2:**\n",
"Print the result of ``iris.sample_data_path('uk_hires.pp')`` to verify that it returns a string pointing to a file on your system. Use this string directly in the call to ``iris.load`` and confirm the result is the same as in the previous example e.g.:\n",
"\n",
" print iris.load('/path/to/iris/sampledata/uk_hires.pp', 'air_potential_temperature')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 2 continued:** Read in the files found at ``iris.sample_data_path('GloSea4', 'ensemble_010.pp')`` and ``iris.sample_data_path('GloSea4', 'ensemble_011.pp')`` using a single load call. Do this by:\n",
"\n",
"1\\. Providing a list of the two filenames."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import iris\n",
"print iris.load([iris.sample_data_path('GloSea4', 'ensemble_010.pp'),\n",
" iris.sample_data_path('GloSea4', 'ensemble_011.pp')])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0: surface_temperature / (K) (realization: 2; time: 6; latitude: 145; longitude: 192)\n"
]
}
],
"prompt_number": 2
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2\\. Providing a suitable glob pattern."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print iris.load(iris.sample_data_path('GloSea4', 'ensemble_01[12].pp'))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0: surface_temperature / (K) (time: 6; forecast_reference_time: 2; latitude: 145; longitude: 192)\n"
]
}
],
"prompt_number": 3
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 2:**\n",
"Print the result of ``iris.sample_data_path('uk_hires.pp')`` to verify that it returns a string pointing to a file on your system. Use this string directly in the call to ``iris.load`` and confirm the result is the same as in the previous example e.g.:\n",
"\n",
" print iris.load('/path/to/iris/sampledata/uk_hires.pp', 'air_potential_temperature')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 2 continued:** Read in the files found at ``iris.sample_data_path('GloSea4', 'ensemble_010.pp')`` and ``iris.sample_data_path('GloSea4', 'ensemble_011.pp')`` using a single load call. Do this by:\n",
"\n",
"1\\. Providing a list of the two filenames."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import iris\n",
"print iris.load([iris.sample_data_path('GloSea4', 'ensemble_010.pp'),\n",
" iris.sample_data_path('GloSea4', 'ensemble_011.pp')])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2\\. Providing a suitable glob pattern."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print iris.load(iris.sample_data_path('GloSea4', 'ensemble_01[12].pp'))"
]
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

View File

@ -1,24 +1,39 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 3:**\n",
"\n",
"1. Write a function, which when given a cube, returns True or False depending on whether a cell method exists.\n",
"2. Use this function as a value for the ``iris.Constraint`` **cube_func** keyword, and load the file in ``iris.sample_data_path('A1B_north_america.nc')`` such that only cubes with cell methods are loaded (note: in this case, that is all that exists in the file)."
]
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 3:**\n",
"\n",
"1. Write a function, which when given a cube, returns True or False depending on whether a cell method exists.\n",
"2. Use this function as a value for the ``iris.Constraint`` **cube_func** keyword, and load the file in ``iris.sample_data_path('A1B_north_america.nc')`` such that only cubes with cell methods are loaded (note: in this case, that is all that exists in the file)."
]
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

View File

@ -1,43 +1,58 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 4\n",
"\n",
"The following exercise is designed to give you experience of identifying why two cubes are not merging. Work is underway to make this identification process more automatic, but the resolution of the identified differences will still be a necessary process.\n",
"\n",
"There are 6 problems, each of which are not merging into a single cube as desired. In no particular order the problems are:\n",
"\n",
" 1. one of the cubes has a history attribute, but the other doesn't\n",
" 2. one of the cubes has bounds on the spatial coordinates, but the other doesn't\n",
" 3. the two cubes have different time coordinate units\n",
" 4. the two cubes have different data dtypes\n",
" 5. the two cubes have different long names\n",
" 6. the two cubes have different shapes (the data must currently be loaded to correct this)\n",
" \n",
"The files can be found in the repository along with this course in ```exercises/iris/merge/```. There are two files to be loaded for each exercise: ```merge_exercise.{problem_number}.f1.nc``` and ```merge_exercise.{problem_number}.f2.nc```.\n",
"\n",
"Identify, and correct, the reason that the two cubes are not merging for all 6 sets of files."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Problem 1"
]
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 4\n",
"\n",
"The following exercise is designed to give you experience of identifying why two cubes are not merging. Work is underway to make this identification process more automatic, but the resolution of the identified differences will still be a necessary process.\n",
"\n",
"There are 6 problems, each of which are not merging into a single cube as desired. In no particular order the problems are:\n",
"\n",
" 1. one of the cubes has a history attribute, but the other doesn't\n",
" 2. one of the cubes has bounds on the spatial coordinates, but the other doesn't\n",
" 3. the two cubes have different time coordinate units\n",
" 4. the two cubes have different data dtypes\n",
" 5. the two cubes have different long names\n",
" 6. the two cubes have different shapes (the data must currently be loaded to correct this)\n",
" \n",
"The files can be found in the repository along with this course in ```exercises/iris/merge/```. There are two files to be loaded for each exercise: ```merge_exercise.{problem_number}.f1.nc``` and ```merge_exercise.{problem_number}.f2.nc```.\n",
"\n",
"Identify, and correct, the reason that the two cubes are not merging for all 6 sets of files."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Problem 1"
]
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

View File

@ -1,44 +1,61 @@
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"import iris.analysis.cartography\n",
"cube.coord('grid_latitude').guess_bounds()\n",
"cube.coord('grid_longitude').guess_bounds()\n",
"grid_areas = iris.analysis.cartography.area_weights(cube)\n",
"\n",
"area_avg = cube.collapsed(['grid_longitude', 'grid_latitude'], iris.analysis.MEAN, weights=grid_areas)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 5:** What other aggregators are available? Calculate the potential temperature variance with time for the area averaged cube (hint: We want to reduce the vertical dimension, and end up with a cube of length 3). Print the data values of the resulting cube."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import iris.analysis.cartography\n",
"cube.coord('grid_latitude').guess_bounds()\n",
"cube.coord('grid_longitude').guess_bounds()\n",
"grid_areas = iris.analysis.cartography.area_weights(cube)\n",
"\n",
"area_avg = cube.collapsed(['grid_longitude', 'grid_latitude'], iris.analysis.MEAN, weights=grid_areas)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 5:** What other aggregators are available? Calculate the potential temperature variance with time for the area averaged cube (hint: We want to reduce the vertical dimension, and end up with a cube of length 3). Print the data values of the resulting cube."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": []
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

File diff suppressed because one or more lines are too long

View File

@ -1,254 +1,183 @@
{
"metadata": {
"name": "iris_exercise_7"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Graduation exercise\n",
"\n",
"1\\. Load 'A1B_north_america.nc' from the iris sample data"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import iris\n",
"filename = iris.sample_data_path(\"A1B_north_america.nc\")\n",
"cube = iris.load_cube(filename)\n",
"print cube"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"air_temperature / (K) (time: 240; latitude: 37; longitude: 49)\n",
" Dimension coordinates:\n",
" time x - -\n",
" latitude - x -\n",
" longitude - - x\n",
" Auxiliary coordinates:\n",
" forecast_period x - -\n",
" Scalar coordinates:\n",
" forecast_reference_time: 1859-09-01 06:00:00\n",
" height: 1.5 m\n",
" Attributes:\n",
" Conventions: CF-1.5\n",
" Model scenario: A1B\n",
" STASH: m01s03i236\n",
" source: Data from Met Office Unified Model 6.05\n",
" Cell methods:\n",
" mean: time (6 hour)\n"
]
}
],
"prompt_number": 2
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2\\. Extract just data from the year 1980 and beyond from the loaded cube"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"tcoord = cube.coord('time')\n",
"def since_1980(cell):\n",
" return tcoord.units.num2date(cell.point).year >= 1980\n",
"\n",
"tcon = iris.Constraint(time=since_1980)\n",
"cube = cube.extract(tcon)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"tcoord = cube.coord('time')\n",
"\n",
"print tcoord.units.num2date(tcoord.points.min())\n",
"print tcoord.units.num2date(tcoord.points.max())"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1980-06-01 00:00:00\n",
"2099-06-01 00:00:00\n"
]
}
],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"3\\. Define a function which takes a coordinate and a single time point as arguments, and returns the decade. For example, your function should return 2010 for the following:\n",
"\n",
" time = iris.coords.DimCoord([10], 'time', units='days since 2018-01-01')\n",
" print your_decade_function(time, time.points[0])"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def get_decade(coord, point):\n",
" year = coord.units.num2date(point).year\n",
" return (year/10)*10\n",
"time = iris.coords.DimCoord([10], 'time', units='days since 2018-01-01')\n",
"print get_decade(time, time.points[0])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"2010\n"
]
}
],
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4\\. Add a \"decade\" coordinate to the loaded cube using your function and the coord categorisation module"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import iris.coord_categorisation as coord_cat\n",
"coord_cat.add_categorised_coord(cube, 'decade', 'time', get_decade)\n",
"print cube.coord('decade')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"AuxCoord(array([1980, 1980, 1980, 1980, 1980, 1980, 1980, 1980, 1980, 1980, 1990,\n",
" 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 2000, 2000,\n",
" 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2010, 2010, 2010,\n",
" 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2020, 2020, 2020, 2020,\n",
" 2020, 2020, 2020, 2020, 2020, 2020, 2030, 2030, 2030, 2030, 2030,\n",
" 2030, 2030, 2030, 2030, 2030, 2040, 2040, 2040, 2040, 2040, 2040,\n",
" 2040, 2040, 2040, 2040, 2050, 2050, 2050, 2050, 2050, 2050, 2050,\n",
" 2050, 2050, 2050, 2060, 2060, 2060, 2060, 2060, 2060, 2060, 2060,\n",
" 2060, 2060, 2070, 2070, 2070, 2070, 2070, 2070, 2070, 2070, 2070,\n",
" 2070, 2080, 2080, 2080, 2080, 2080, 2080, 2080, 2080, 2080, 2080,\n",
" 2090, 2090, 2090, 2090, 2090, 2090, 2090, 2090, 2090, 2090]), standard_name=None, units=Unit('1'), long_name=u'decade')\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"5\\. Calculate the decadal means cube for this scenario"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import iris.analysis\n",
"cube = cube.aggregated_by('decade', iris.analysis.MEAN)\n",
"print cube"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"air_temperature / (K) (time: 12; latitude: 37; longitude: 49)\n",
" Dimension coordinates:\n",
" time x - -\n",
" latitude - x -\n",
" longitude - - x\n",
" Auxiliary coordinates:\n",
" decade x - -\n",
" forecast_period x - -\n",
" Scalar coordinates:\n",
" forecast_reference_time: 1859-09-01 06:00:00\n",
" height: 1.5 m\n",
" Attributes:\n",
" Conventions: CF-1.5\n",
" Model scenario: A1B\n",
" STASH: m01s03i236\n",
" history: Mean of air_temperature aggregated over decade\n",
" source: Data from Met Office Unified Model 6.05\n",
" Cell methods:\n",
" mean: time (6 hour)\n",
" mean: decade\n"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"6\\. Create a figure with 3 rows and 4 columns displaying the decadal means, with the decade displayed prominently in each axes' title"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import matplotlib.pyplot as plt\n",
"import iris.plot as iplt\n",
"\n",
"plt.figure(figsize=(12, 6))\n",
"\n",
"plt.suptitle('Decadal means for the A1B scenario')\n",
"for i, decade_cube in enumerate(cube.slices(['latitude', 'longitude'])):\n",
" plt.subplot(3, 4, i+1)\n",
" iplt.contourf(decade_cube, 20)\n",
" plt.title('{}'.format(decade_cube.coord('decade').points[0]))\n",
" plt.gca().coastlines()\n",
"plt.show()"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 16
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"# Graduation exercise\n",
"\n",
"1\\. Load 'A1B_north_america.nc' from the iris sample data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import iris\n",
"filename = iris.sample_data_path(\"A1B_north_america.nc\")\n",
"cube = iris.load_cube(filename)\n",
"print cube"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2\\. Extract just data from the year 1980 and beyond from the loaded cube"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tcoord = cube.coord('time')\n",
"def since_1980(cell):\n",
" return tcoord.units.num2date(cell.point).year >= 1980\n",
"\n",
"tcon = iris.Constraint(time=since_1980)\n",
"cube = cube.extract(tcon)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tcoord = cube.coord('time')\n",
"\n",
"print tcoord.units.num2date(tcoord.points.min())\n",
"print tcoord.units.num2date(tcoord.points.max())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"3\\. Define a function which takes a coordinate and a single time point as arguments, and returns the decade. For example, your function should return 2010 for the following:\n",
"\n",
" time = iris.coords.DimCoord([10], 'time', units='days since 2018-01-01')\n",
" print your_decade_function(time, time.points[0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def get_decade(coord, point):\n",
" year = coord.units.num2date(point).year\n",
" return (year/10)*10\n",
"time = iris.coords.DimCoord([10], 'time', units='days since 2018-01-01')\n",
"print get_decade(time, time.points[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4\\. Add a \"decade\" coordinate to the loaded cube using your function and the coord categorisation module"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import iris.coord_categorisation as coord_cat\n",
"coord_cat.add_categorised_coord(cube, 'decade', 'time', get_decade)\n",
"print cube.coord('decade')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"5\\. Calculate the decadal means cube for this scenario"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import iris.analysis\n",
"cube = cube.aggregated_by('decade', iris.analysis.MEAN)\n",
"print cube"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"6\\. Create a figure with 3 rows and 4 columns displaying the decadal means, with the decade displayed prominently in each axes' title"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import iris.plot as iplt\n",
"\n",
"plt.figure(figsize=(12, 6))\n",
"\n",
"plt.suptitle('Decadal means for the A1B scenario')\n",
"for i, decade_cube in enumerate(cube.slices(['latitude', 'longitude'])):\n",
" plt.subplot(3, 4, i+1)\n",
" iplt.contourf(decade_cube, 20)\n",
" plt.title('{}'.format(decade_cube.coord('decade').points[0]))\n",
" plt.gca().coastlines()\n",
"plt.show()"
]
}
]
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,111 +1,99 @@
{
"metadata": {
"name": "",
"signature": "sha256:848ef38126532012d51f85fda6138dfe097a4c6c37850c846063ebee9d3928bb"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1\n",
"\n",
"Use ``np.arange`` and ``reshape`` to create the array\n",
"\n",
" A = [[1 2 3 4]\n",
" [5 6 7 8]]"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import numpy as np\n",
"A = np.arange(1, 9).reshape(2, -1)\n",
"print A"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[[1 2 3 4]\n",
" [5 6 7 8]]\n"
]
}
],
"prompt_number": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"Use ``np.array`` to create the array\n",
"\n",
" B = [1 2]"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"B = np.array([1, 2])\n",
"print B"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1 2]\n"
]
}
],
"prompt_number": 2
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use broadcasting to add ``B`` to ``A`` to create the final array\n",
"\n",
" A + B = [[2 3 4 5]\n",
" [7 8 9 10]\n",
"\n",
"Hint: what shape does ``B`` have to be changed to?"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print A + B.reshape(2, 1)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[[ 2 3 4 5]\n",
" [ 7 8 9 10]]\n"
]
}
],
"prompt_number": 3
}
],
"metadata": {}
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1\n",
"\n",
"Use ``np.arange`` and ``reshape`` to create the array\n",
"\n",
" A = [[1 2 3 4]\n",
" [5 6 7 8]]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"A = np.arange(1, 9).reshape(2, -1)\n",
"print A"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"Use ``np.array`` to create the array\n",
"\n",
" B = [1 2]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"B = np.array([1, 2])\n",
"print B"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use broadcasting to add ``B`` to ``A`` to create the final array\n",
"\n",
" A + B = [[2 3 4 5]\n",
" [7 8 9 10]\n",
"\n",
"Hint: what shape does ``B`` have to be changed to?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print A + B.reshape(2, 1)"
]
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

View File

@ -1,305 +1,268 @@
{
"metadata": {
"name": "",
"signature": "sha256:e3e7c1608702d0a84f35e6fa63112daab968fe74a96ae1f6ee9f39993826a343"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
"cells": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Exercise: trapezoidal integration\n",
"\n",
"In this exercise, you are tasked with implementing the simple trapezoid rule\n",
"formula for numerical integration. If we want to compute the definite integral\n",
"\n",
"$$\n",
" \\int_{a}^{b}f(x)dx\n",
"$$\n",
"\n",
"we can partition the integration interval $[a,b]$ into smaller subintervals. We then approximate the area under the curve for each subinterval by calculating the area of the trapezoid created by linearly interpolating between the two function values at each end of the subinterval:\n",
"\n",
"![Illustration of the trapezoidal rule](../images/trapezoidal_rule.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"For a pre-computed $y$ array (where $y = f(x)$ at discrete samples) the trapezoidal rule equation is:\n",
"\n",
"$$\n",
" \\int_{a}^{b}f(x)dx\\approx\\frac{1}{2}\\sum_{i=1}^{n}\\left(x_{i}-x_{i-1}\\right)\\left(y_{i}+y_{i-1}\\right).\n",
"$$\n",
"\n",
"In pure python, this can be written as:\n",
"\n",
" def trapz_slow(x, y):\n",
" area = 0.\n",
" for i in range(1, len(x)):\n",
" area += (x[i] - x[i-1]) * (y[i] + y[i-1])\n",
" return area / 2"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Exercise 2\n",
"\n",
"#### Part 1\n",
"\n",
"Create two arrays $x$ and $y$, where $x$ is a linearly spaced array in the interval $[0, 3]$ of length 10, and $y$ represents the function $f(x) = x^2$ sampled at $x$."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import numpy as np\n",
"\n",
"x = np.linspace(0, 3, 10)\n",
"y = x ** 2\n",
"\n",
"print x\n",
"print y"
],
"language": "python",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[ 0. 0.33333333 0.66666667 1. 1.33333333 1.66666667\n",
" 2. 2.33333333 2.66666667 3. ]\n",
"[ 0. 0.11111111 0.44444444 1. 1.77777778 2.77777778\n",
" 4. 5.44444444 7.11111111 9. ]\n"
]
}
],
"prompt_number": 1
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 2\n",
"\n",
"Use indexing (not a for loop) to find the 9 values representing $y_{i}+y_{i-1}$ for $i$ between 1 and 10.\n",
"\n",
"Hint: What indexing would be needed to get all but the last element of the 1d array **``y``**. Similarly what indexing would be needed to get all but the first element of a 1d array."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"y_roll_sum = y[:-1] + y[1:]\n",
"print y_roll_sum"
],
"language": "python",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[ 0.11111111 0.55555556 1.44444444 2.77777778 4.55555556\n",
" 6.77777778 9.44444444 12.55555556 16.11111111]\n"
]
}
],
"prompt_number": 2
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 3\n",
"\n",
"Write a function `trapz(x, y)`, that applies the trapezoid formula to pre-computed values, where `x` and `y` are 1-d arrays. The function should not use a for loop."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def trapz(x, y):\n",
" return 0.5 * np.sum((x[1:] - x[:-1]) * (y[:-1] + y[1:]))"
],
"language": "python",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 4\n",
"\n",
"Verify that your function is correct by using the arrays created in #1 as input to ``trapz``. Your answer should be a close approximation of $\\int_0^3 x^2$ which is $9$."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"trapz(x, y)"
],
"language": "python",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 4,
"text": [
"9.0555555555555554"
]
}
],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 5 (extension)\n",
"\n",
"``numpy`` and ``scipy.integrate`` provides many common integration schemes. Find the documentation for NumPy's own version of the trapezoidal integration scheme and check its result with your own:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print np.trapz(y, x)"
],
"language": "python",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"9.05555555556\n"
]
}
],
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 6 (extension)\n",
"\n",
"Write a function `trapzf(f, a, b, npts=100)` that accepts a function `f`, the endpoints `a` and `b` and the number of samples to take `npts`. Sample the function uniformly at these\n",
"points and return the value of the integral.\n",
"\n",
"Use the trapzf function to identify the minimum number of sampling points needed to approximate the integral $\\int_0^3 x^2$ with an absolute error of $<=0.0001$. (A loop is necessary here)"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def trapzf(f, a, b, npts=100):\n",
" x = np.linspace(a, b, npts)\n",
" y = f(x)\n",
" return trapz(x, y)\n",
"\n",
"def x_squared(x):\n",
" return x ** 2\n",
"\n",
"abs_err = 1.0\n",
"n_samples = 0\n",
"expected = 9\n",
"while abs_err > 0.0001:\n",
" n_samples += 1\n",
" integral = trapzf(x_squared, 0, 3, npts=n_samples)\n",
" abs_err = np.abs(integral - 9)\n",
"\n",
"print 'Minimum samples for absolute error less than or equal to 0.0001:', n_samples\n",
" "
],
"language": "python",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Minimum samples for absolute error less than or equal to 0.0001: 214\n"
]
}
],
"prompt_number": 6
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
],
"metadata": {}
},
"source": [
"# Exercise: trapezoidal integration\n",
"\n",
"In this exercise, you are tasked with implementing the simple trapezoid rule\n",
"formula for numerical integration. If we want to compute the definite integral\n",
"\n",
"$$\n",
" \\int_{a}^{b}f(x)dx\n",
"$$\n",
"\n",
"we can partition the integration interval $[a,b]$ into smaller subintervals. We then approximate the area under the curve for each subinterval by calculating the area of the trapezoid created by linearly interpolating between the two function values at each end of the subinterval:\n",
"\n",
"![Illustration of the trapezoidal rule](../images/trapezoidal_rule.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"For a pre-computed $y$ array (where $y = f(x)$ at discrete samples) the trapezoidal rule equation is:\n",
"\n",
"$$\n",
" \\int_{a}^{b}f(x)dx\\approx\\frac{1}{2}\\sum_{i=1}^{n}\\left(x_{i}-x_{i-1}\\right)\\left(y_{i}+y_{i-1}\\right).\n",
"$$\n",
"\n",
"In pure python, this can be written as:\n",
"\n",
" def trapz_slow(x, y):\n",
" area = 0.\n",
" for i in range(1, len(x)):\n",
" area += (x[i] - x[i-1]) * (y[i] + y[i-1])\n",
" return area / 2"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Exercise 2\n",
"\n",
"#### Part 1\n",
"\n",
"Create two arrays $x$ and $y$, where $x$ is a linearly spaced array in the interval $[0, 3]$ of length 10, and $y$ represents the function $f(x) = x^2$ sampled at $x$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"x = np.linspace(0, 3, 10)\n",
"y = x ** 2\n",
"\n",
"print x\n",
"print y"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 2\n",
"\n",
"Use indexing (not a for loop) to find the 9 values representing $y_{i}+y_{i-1}$ for $i$ between 1 and 10.\n",
"\n",
"Hint: What indexing would be needed to get all but the last element of the 1d array **``y``**. Similarly what indexing would be needed to get all but the first element of a 1d array."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"y_roll_sum = y[:-1] + y[1:]\n",
"print y_roll_sum"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 3\n",
"\n",
"Write a function `trapz(x, y)`, that applies the trapezoid formula to pre-computed values, where `x` and `y` are 1-d arrays. The function should not use a for loop."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"def trapz(x, y):\n",
" return 0.5 * np.sum((x[1:] - x[:-1]) * (y[:-1] + y[1:]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 4\n",
"\n",
"Verify that your function is correct by using the arrays created in #1 as input to ``trapz``. Your answer should be a close approximation of $\\int_0^3 x^2$ which is $9$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"trapz(x, y)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 5 (extension)\n",
"\n",
"``numpy`` and ``scipy.integrate`` provides many common integration schemes. Find the documentation for NumPy's own version of the trapezoidal integration scheme and check its result with your own:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"print np.trapz(y, x)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"#### Part 6 (extension)\n",
"\n",
"Write a function `trapzf(f, a, b, npts=100)` that accepts a function `f`, the endpoints `a` and `b` and the number of samples to take `npts`. Sample the function uniformly at these\n",
"points and return the value of the integral.\n",
"\n",
"Use the trapzf function to identify the minimum number of sampling points needed to approximate the integral $\\int_0^3 x^2$ with an absolute error of $<=0.0001$. (A loop is necessary here)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"def trapzf(f, a, b, npts=100):\n",
" x = np.linspace(a, b, npts)\n",
" y = f(x)\n",
" return trapz(x, y)\n",
"\n",
"def x_squared(x):\n",
" return x ** 2\n",
"\n",
"abs_err = 1.0\n",
"n_samples = 0\n",
"expected = 9\n",
"while abs_err > 0.0001:\n",
" n_samples += 1\n",
" integral = trapzf(x_squared, 0, 3, npts=n_samples)\n",
" abs_err = np.abs(integral - 9)\n",
"\n",
"print 'Minimum samples for absolute error less than or equal to 0.0001:', n_samples\n",
" "
]
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 Sys",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1+"
},
"widgets": {
"state": {},
"version": "0.3.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}