Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add section on variable naming #7

Merged
merged 45 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
9b9e204
refactor slides to break into separate sections.
jatkinson1000 Jun 18, 2024
9ec93cf
add slide on naming standards
AmyOctoCat Jun 19, 2024
4fb12be
add warning about the use of f strings in logging statements
AmyOctoCat Jun 19, 2024
1c2418f
Adding instructions for naming part of exercise.
AmyOctoCat Jun 19, 2024
7d7aed6
changing some of the naming in the final version of precipitation_cli…
AmyOctoCat Jun 19, 2024
a07e7c4
hopefully made more readable
AmyOctoCat Jun 19, 2024
d273ee7
naming tweeks
AmyOctoCat Jun 19, 2024
8383480
revert changes to pluralise name for array. Not sure what best practi…
AmyOctoCat Jun 19, 2024
99042f7
add a line about boolean naming
AmyOctoCat Jun 20, 2024
1083b88
add a line about boolean naming
AmyOctoCat Jun 20, 2024
3ef0967
formatting
AmyOctoCat Jun 20, 2024
9652abe
Update exercises/00_final/precipitation_climatology.py
AmyOctoCat Jun 20, 2024
c37087c
fix excpetion raising bug introduced in this branch
AmyOctoCat Jun 20, 2024
97cd877
Merge branch 'add_section_on_variable_naming' of github.com:Cambridge…
AmyOctoCat Jun 20, 2024
6752f63
grammar in slide.
AmyOctoCat Jun 20, 2024
3c87e6f
pull naming into it's own section
AmyOctoCat Jun 20, 2024
e88749e
resolve merge conflict
AmyOctoCat Jun 20, 2024
2d2ace5
return matplotlib import to the standard plt and add small fix
AmyOctoCat Jun 20, 2024
6a8fdb0
fix merge conflicts
AmyOctoCat Jun 20, 2024
694c8fe
further renaming and some additional documentation
AmyOctoCat Jun 26, 2024
fa01f3b
further renaming
AmyOctoCat Jun 26, 2024
93caff0
further naming changes
AmyOctoCat Jun 26, 2024
e4c2fd5
further naming changes
AmyOctoCat Jun 26, 2024
09c52cc
revert naming of columns in the netcdf as editing netcdf file is too …
AmyOctoCat Jun 26, 2024
67cb57e
remove comment as have confirmed that this hasn't introduced a runtim…
AmyOctoCat Jun 26, 2024
a55b60c
add some examples into the slides
AmyOctoCat Jun 26, 2024
b60049f
add to example slide
AmyOctoCat Jun 26, 2024
471dfec
finish renaming in exercise 5
AmyOctoCat Jun 26, 2024
40c5912
renumber exercises
AmyOctoCat Jun 26, 2024
c4e37c6
include the naming slides in the main quarto file
AmyOctoCat Jun 26, 2024
7b694b1
add base code for exercise on naming
AmyOctoCat Jun 26, 2024
6710ba1
update naming in exercise 4
AmyOctoCat Jun 26, 2024
e6168aa
update exercise 4 for renaming
AmyOctoCat Jun 26, 2024
0fc9ec8
run black in all the exercises after black
AmyOctoCat Jun 26, 2024
f6ef57b
modified the wrong exercise
AmyOctoCat Jun 26, 2024
c71c31b
missed file naming
AmyOctoCat Jun 26, 2024
28e9359
renumber exercises in slides and a dd a bit of extra detail
AmyOctoCat Jun 27, 2024
fe0c39e
reformatting and splitting black and pylint sections
AmyOctoCat Jun 27, 2024
61e5ced
Update exercises 1 and 2 with blank lines to match changes to later e…
jatkinson1000 Jun 27, 2024
cf759c8
remove redundant use of xr.DataArray wrapping around array multiplica…
AmyOctoCat Jul 3, 2024
99ef3a9
change font size in slides
AmyOctoCat Jul 3, 2024
8e478f2
remove remaining uses of assert in production code
AmyOctoCat Jul 3, 2024
f9a016d
formatting changes to slides on naming
AmyOctoCat Jul 3, 2024
50e4972
Merge pull request #13 from Cambridge-ICCS/jatkinson1000-naming-patch
AmyOctoCat Jul 3, 2024
6539266
Minor typographical updates.
jatkinson1000 Jul 3, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions exercises/00_final/precipitation_climatology.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import json
import numpy as np
import matplotlib.pyplot as plot
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import xarray as xr
import cartopy.crs as ccrs
Expand Down Expand Up @@ -33,9 +33,9 @@ def convert_precipitation_units(precipitation_in_kg_per_m_squared_s):
precipitation_in_mm_per_day.attrs["units"] = "mm/day"

if precipitation_in_mm_per_day.data.min() < 0.0:
print("There is at least one negative precipitation value")
raise ValueError("There is at least one negative precipitation value")
if precipitation_in_mm_per_day.data.max() > 2000:
print("There is a precipitation value/s > 2000 mm/day")
raise ValueError("There is a precipitation value/s > 2000 mm/day")

return precipitation_in_mm_per_day

Expand All @@ -60,24 +60,24 @@ def plot_zonally_averaged_precipitation(data):
"""
zonal_precipitation = data["precipitation"].mean("longitude", keep_attrs=True)

figure, axes = plot.subplots(nrows=4, ncols=1, figsize=(12, 8))
figure, axes = plt.subplots(nrows=4, ncols=1, figsize=(12, 8))

zonal_precipitation.sel(lat=[0]).plot.line(ax=axes[0], hue="latitude")
zonal_precipitation.sel(lat=[-20, 20]).plot.line(ax=axes[1], hue="latitude")
zonal_precipitation.sel(lat=[-45, 45]).plot.line(ax=axes[2], hue="latitude")
zonal_precipitation.sel(lat=[-70, 70]).plot.line(ax=axes[3], hue="latitude")

plot.tight_layout()
plt.tight_layout()
for axis in axes:
AmyOctoCat marked this conversation as resolved.
Show resolved Hide resolved
axis.set_ylim(0.0, 1.0e-4)
axis.grid()
plot.savefig("zonal.png", dpi=200) # Save figure to file
plt.savefig("zonal.png", dpi=200) # Save figure to file

figure, axes = plot.subplots(nrows=1, ncols=1, figsize=(12, 5))
figure, axes = plt.subplots(nrows=1, ncols=1, figsize=(12, 5))

zonal_precipitation.T.plot()

plot.savefig("zonal_map.png", dpi=200) # Save figure to file
plt.savefig("zonal_map.png", dpi=200) # Save figure to file

# could data be named more specifically and more detail be given in the docstring about
# what the dimension and contents of the array are?
Expand Down Expand Up @@ -121,7 +121,7 @@ def get_country_annual_average(data, countries):

# could data be named more specifically and more detail be given in the docstring about
# what the dimension and contents of the array are?
def plot_hovmoller_diagram(data):
def plot_enso_hovmoller_diagram(data):
"""
Plot Hovmöller diagram of equatorial precipitation to visualise ENSO.

Expand All @@ -143,7 +143,7 @@ def plot_hovmoller_diagram(data):
)

enso.plot()
plot.savefig("enso.png", dpi=200) # Save figure to file
plt.savefig("enso.png", dpi=200) # Save figure to file


def create_precipitation_climatology_plot(climatology_data, model_name, season, mask=None, plot_gridlines=False, levels=None):
Expand Down Expand Up @@ -174,7 +174,7 @@ def create_precipitation_climatology_plot(climatology_data, model_name, season,
if not levels:
levels = np.arange(0, 13.5, 1.5)

fig, geo_axes = plot.subplots(
fig, geo_axes = plt.subplots(
nrows=1,
ncols=1,
figsize=(12, 5),
Expand Down Expand Up @@ -226,7 +226,7 @@ def create_precipitation_climatology_plot(climatology_data, model_name, season,
gridlines.ylabel_style = {"size": 15, "color": "gray"}

title = f"{model_name} precipitation climatology ({season})"
plot.title(title)
plt.title(title)


def main(
Expand Down Expand Up @@ -270,7 +270,7 @@ def main(
input_data = xr.open_dataset(precipitation_netcdf_file)

plot_zonally_averaged_precipitation(input_data)
plot_hovmoller_diagram(input_data)
plot_enso_hovmoller_diagram(input_data)
get_country_annual_average(input_data, countries)

climatology = input_data["precipitation"].groupby("time.season").mean("time", keep_attrs=True)
Expand Down Expand Up @@ -298,7 +298,7 @@ def main(
levels=cbar_levels,
)

plot.savefig(output_file, dpi=200)
plt.savefig(output_file, dpi=200)


if __name__ == "__main__":
Expand Down
18 changes: 0 additions & 18 deletions slides/_fstrings_magic_config.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,6 @@ print(f"a={a} and b={b}. Their product is {a * b}, sum is {a + b}, and a/b is {a
See [Real Python](https://realpython.com/python-f-strings/) for more information.
Note: pylint W1203 recommends against using f-strings in logging calls.

## Naming Standards

It may seem inconsequential, but carefully naming variables and methods can improve the
readability of code massively and can help to make code self documenting.

A few naming tips and conventions:

- The name should show the intention, think about how someone else might read it (this could be future you)
- Use pronounceable names e.g. `mass` not `ms`, `stem` not `stm`
- avoid abbreviations and single letter variable names where possible
- One word per concept e.g. choose one of `put`, `insert`, `add` in the same code base
- Use names that can be searched
- Describe content rather than storage type
- Naming booleans, use prefixes like 'is', 'has' or 'can' and avoid negations like `not_green`
- Plurals to indicate groups, e.g. a list of dog objects would be `dogs`, not `dog_list`
- Keep it simple and use technical terms where appropriate
- Use explaining variables

jatkinson1000 marked this conversation as resolved.
Show resolved Hide resolved
## Remove Magic Numbers {.smaller}

Numbers in code that are not immediately obvious.
Expand Down
21 changes: 21 additions & 0 deletions slides/_naming_for_clarity.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
## Naming For Clarity

It may seem inconsequential, but carefully naming variables and methods can improve the
readability of code massively and can help to make code self documenting.

A few naming tips and conventions:

- The name should show the intention, think about how someone else might read it (this could be future you)
- Use pronounceable names e.g. `mass` not `ms`, `stem` not `stm`
- avoid abbreviations and single letter variable names where possible
- One word per concept e.g. choose one of `put`, `insert`, `add` in the same code base
- Use names that can be searched
- Describe content rather than storage type
- Naming booleans, use prefixes like `is`, `has` or `can` and avoid negations like `not_green`
- Plurals to indicate groups, e.g. a list of dog objects would be `dogs`, not `dog_list`
- Keep it simple and use technical terms where appropriate
- Use explaining variables

## Naming For Clarity
AmyOctoCat marked this conversation as resolved.
Show resolved Hide resolved

Some examples: