Skip to content
This repository was archived by the owner on May 12, 2021. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
21 changes: 21 additions & 0 deletions ocw/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,5 +196,26 @@ def test_total_mean(self):
np.testing.assert_array_equal(
utils.calc_climatology_year(self.test_dataset)[1], total_mean)


class TestCalcClimatologyMonthly(unittest.TestCase):
''' Tests the 'calc_climatology_monthly' method from ocw.utils.py '''

def setUp(self):
self.lats = np.array([10, 20, 30, 40, 50])
self.lons = np.array([20, 30, 40, 50, 60])
start_date = datetime.datetime(2000, 1, 1)
self.times = np.array([start_date + relativedelta(months=x)
for x in range(36)])
self.values = np.array([1]*300 + [2]*300 + [0]*300).reshape(36, 5, 5)
self.variable = 'testdata'
self.dataset = Dataset(self.lats, self.lons, self.times,
self.values, self.variable)

def test_calc_climatology_monthly(self):
expected_result = np.ones(300).reshape(12, 5, 5)
actual_result = utils.calc_climatology_monthly(self.dataset)
np.testing.assert_array_equal(actual_result, expected_result)


if __name__ == '__main__':
unittest.main()
24 changes: 24 additions & 0 deletions ocw/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,27 @@ def calc_climatology_season(month_start, month_end, dataset):
t_series = reshape_data[:, month_index].mean(axis=1)
means = t_series.mean(axis=0)
return t_series, means


def calc_climatology_monthly(dataset):
''' Calculate monthly mean values for a dataset.

:param dataset: Monthly binned Dataset object with the number of months
divisible by 12
:type dataset: ocw.dataset.Dataset object

:returns: Mean values for each month of the year
:rtype: A 3D numpy array of shape (12, num_lats, num_lons)

:raise ValueError: If the number of monthly bins is not divisible by 12
'''

if dataset.values.shape[0] % 12:
error = (
"The length of the time axis in the values array should be "
"divisible by 12."
)
raise ValueError(error)
else:
return reshape_monthly_to_annually(dataset).mean(axis=0)