diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9fe1642..ad4083d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,14 +1,31 @@ -name: ci +name: ci on: push: branches: - main + pull_request: jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + lfs: false + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + - run: pip install -e ".[dev]" + - run: ruff check . --exclude notebooks + - run: ruff format --check gsiberror tests setup.py + - run: pytest + deploy: + if: github.event_name == 'push' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 with: python-version: 3.x - run: pip install mkdocs-material diff --git a/environment.yml b/environment.yml index 711dd8b..599225c 100644 --- a/environment.yml +++ b/environment.yml @@ -9,9 +9,9 @@ dependencies: - jupyter_client - matplotlib - notebook - - numpy>=1.20.3 + - numpy>=1.22 - pip - - python=3.8.2 + - python>=3.9.18 - xarray - pip: - -e . diff --git a/gsiberror/__init__.py b/gsiberror/__init__.py index 39f3509..c7f154d 100644 --- a/gsiberror/__init__.py +++ b/gsiberror/__init__.py @@ -1,33 +1,53 @@ #! /usr/bin/env python3 +from pathlib import Path + import numpy as np import xarray as xr -from .plot_functions import var_name, global_minmax, plot_reg_coeffs, plot_amplitudes, plot_hscales, plot_vscales +from .plot_functions import ( + var_name, + global_minmax, + plot_reg_coeffs, + plot_amplitudes, + plot_hscales, + plot_vscales, +) + +__all__ = [ + "Berror", + "global_minmax", + "plot_amplitudes", + "plot_hscales", + "plot_reg_coeffs", + "plot_vscales", + "var_name", +] + -class Berror(object): +class Berror: """ Berror ====== - - Class with methods to read all the records of a GSI compatible background error covariance matrix (.gcv format). - """ - + Class with methods to read all the records of a GSI compatible background error covariance matrix (.gcv format). + + """ + def __init__(self, file_name): - self.file_name = file_name - #self._my_name = '' - + self.file_name = str(file_name) + self._name = Path(self.file_name).name + def read_records(self): """ read_records ------------ - + This method reads the first three records of the background error covariance matrix (nlat, nlon and nlev). These records are used to calculate the size of the remainder records from the matrix. All attributes read from the matrix are provided by this function. The plotting of the records are made through the use of the xarray's 'plot()' method; depending on the use, it can be necessary to to load the matplotlib and cartopy modules. - + Input parameters ---------------- None. @@ -35,275 +55,420 @@ def read_records(self): Result ------ bfile: object created with the records and attributes from the background error covariance matrix (see the list below) - + Available attributes -------------------- file_name : string with the name of the file - nlat : integer with the number of latitude points - nlon : integer with the number of longitude points + nlat : integer with the number of latitude points + nlon : integer with the number of longitude points nlev : integer with the number of vertical levels lats : nd-array with the latitude values (-90 to 90) lons : nd-array with the longitude values (0 to 360) levs : nd-array with the vertical levels (1 to nlev) amplitudes : dicionary with the xarrays for the control variables amplitudes amplitudes_names : names of the variables in the amplitudes dictionary - balprojs : dictionary with xarrays for the regression coefficients matrices for the temperature, + balprojs : dictionary with xarrays for the regression coefficients matrices for the temperature, surface pressure and velocity potential hscales : dictionary with xarrays for the horizontal length scales hscales_var_names : names of the variables in the hscales dictionary vscales : dictionary with xarrays for the vertical length scales vscales_var_names : names of the variables in the vscales dictionary - + Use --- import gsiberror as gb - + bfile = gb.Berror('arquivo_matriz_B.gcv') - + bfile.read_records() - + bfile.nlat, bfile.nlon, bfile.nlev - + bfile.amplitudes_names - + bfile.amplitudes['sf'] - + bfile_amp_sf = bfile.amplitudes['sf'] - - bfile_amp_sf.plot.contourf() + + bfile_amp_sf.plot.contourf() """ - + # Reads the first three records to define the grid - dt = np.dtype([ ('grid', '3>i4') ]) + dt = np.dtype([("grid", "3>i4")]) + + try: + with open(self.file_name, "rb") as ftmp: + if ftmp.read(40).startswith(b"version https://git-lfs.github.com"): + raise ValueError( + f"{self.file_name!r} is a Git LFS pointer, not GCV data; " + "run 'git lfs pull' first" + ) + ftmp.seek(0) + fobj = np.fromfile(ftmp, dtype=dt, count=1, offset=4) + except OSError as exc: + raise OSError(f"Unable to read GCV file {self.file_name!r}") from exc + + if fobj.size != 1: + raise ValueError(f"Invalid or truncated GCV header in {self.file_name!r}") - with open(self.file_name, 'rb') as ftmp: - fobj = np.fromfile(ftmp, dtype=dt, count=3, offset=4) - # Calculate the coordinates for lats, lons and levs dimensions - nlev = fobj[0]['grid'][0] - nlat = fobj[0]['grid'][1] - nlon = fobj[0]['grid'][2] - + nlev = fobj[0]["grid"][0] + nlat = fobj[0]["grid"][1] + nlon = fobj[0]["grid"][2] + + if nlev <= 0 or nlat <= 0 or nlon <= 0: + raise ValueError( + f"Invalid GCV grid dimensions: nlev={nlev}, nlat={nlat}, nlon={nlon}" + ) + self.nlat = nlat self.nlon = nlon self.nlev = nlev - - self.lats = np.linspace(-90,90, self.nlat) - self.lons = np.linspace(0,360, self.nlon) - self.levs = np.arange(1, self.nlev+1) - + + self.lats = np.linspace(-90, 90, self.nlat) + # A global cyclic grid must not contain both 0 and 360 degrees. + self.lons = np.linspace(0, 360, self.nlon, endpoint=False) + self.levs = np.arange(1, self.nlev + 1) + # Define the records sizes from within the file ('>f4' indicates 32 bits floats, big endian) - tnlat = str(self.nlat) + '>f4' - s2d = str(self.nlat*self.nlev) + '>f4' - sst2d = str(self.nlat*self.nlon) + '>f4' - s3d = str(self.nlat*self.nlev*self.nlev) + '>f4' + tnlat = str(self.nlat) + ">f4" + s2d = str(self.nlat * self.nlev) + ">f4" + sst2d = str(self.nlat * self.nlon) + ">f4" + s3d = str(self.nlat * self.nlev * self.nlev) + ">f4" # Define a structure for the records within the file ('padX' = 4 bytes; '>i4' indicates 32 bits integers, big endian) # Maybe this isn't the best way to read the records but it is explicity, at least - dt = [ ('grid', '3>i4'), - - ('pad1', '>i4'), ('agvin',s3d), - ('pad2', '>i4'), ('bgvin', s2d), - ('pad3', '>i4'), ('wgvin', s2d), - - ('pad4', '>i4'), ('sf', '|a5'), ('sig_sf', '>i4'), ('pad5', '>i4'), - ('pad6', '>i4'), ('corzin_sf', s2d), ('pad7', '>i4'), - ('pad8', '>i4'), ('hscalesin_sf', s2d), ('pad9', '>i4'), - ('pad10', '>i4'), ('vscalesin_sf', s2d), ('pad11', '>i4'), - - ('pad12', '>i4'), ('vp', '|a5'), ('sig_vp', '>i4'), ('pad13', '>i4'), - ('pad14', '>i4'), ('corzin_vp', s2d), ('pad15', '>i4'), - ('pad16', '>i4'), ('hscalesin_vp', s2d), ('pad17', '>i4'), - ('pad18', '>i4'), ('vscalesin_vp', s2d), ('pad19', '>i4'), - - ('pad20', '>i4'), ('t', '|a5'), ('sig_t', '>i4'), ('pad21', '>i4'), - ('pad22', '>i4'), ('corzin_t', s2d), ('pad23', '>i4'), - ('pad24', '>i4'), ('hscalesin_t', s2d), ('pad25', '>i4'), - ('pad26', '>i4'), ('vscalesin_t', s2d), ('pad27', '>i4'), - - ('pad28', '>i4'), ('q', '|a5'), ('sig_q', '>i4'), ('pad29', '>i4'), - ('pad30', '>i4'), ('corzin_q', s2d), ('corqin_q', s2d), ('pad31', '>i4'), - ('pad32', '>i4'), ('hscalesin_q', s2d), ('pad33', '>i4'), - ('pad34', '>i4'), ('vscalesin_q', s2d), ('pad35', '>i4'), - - ('pad36', '>i4'), ('oz', '|a5'), ('sig_oz', '>i4'), ('pad37', '>i4'), - ('pad38', '>i4'), ('corzin_oz', s2d), ('pad39', '>i4'), - ('pad40', '>i4'), ('hscalesin_oz', s2d), ('pad41', '>i4'), - ('pad42', '>i4'), ('vscalesin_oz', s2d), ('pad43', '>i4'), - - ('pad44', '>i4'), ('cw', '|a5'), ('sig_cw', '>i4'), ('pad45', '>i4'), - ('pad46', '>i4'), ('corzin_cw', s2d), ('pad47', '>i4'), - ('pad48', '>i4'), ('hscalesin_cw', s2d), ('pad49', '>i4'), - ('pad50', '>i4'), ('vscalesin_cw', s2d), ('pad51', '>i4'), - - ('pad52', '>i4'), ('ps', '|a5'), ('sig_ps', '>i4'), ('pad53', '>i4'), - ('pad54', '>i4'), ('corpin_ps', tnlat), ('pad55', '>i4'), - ('pad56', '>i4'), ('hscalespin_ps', tnlat), ('pad57', '>i4'), - - ('pad58', '>i4'), ('sst', '|a5'), ('sig_sst', '>i4'), ('pad59', '>i4'), - ('pad60', '>i4'), ('corsstin_sst', sst2d), ('pad61', '>i4'), - ('pad62', '>i4'), ('hsstin_ps', sst2d), ('pad63', '>i4') ] - - dt_obj = np.dtype(dt)#, align=True) # align=True should be automatic (?) - # accounts for 4 bytes padding (before and after the records) - + dt = [ + ("grid", "3>i4"), + ("pad1", ">i4"), + ("agvin", s3d), + ("pad2", ">i4"), + ("bgvin", s2d), + ("pad3", ">i4"), + ("wgvin", s2d), + ("pad4", ">i4"), + ("sf", "|a5"), + ("sig_sf", ">i4"), + ("pad5", ">i4"), + ("pad6", ">i4"), + ("corzin_sf", s2d), + ("pad7", ">i4"), + ("pad8", ">i4"), + ("hscalesin_sf", s2d), + ("pad9", ">i4"), + ("pad10", ">i4"), + ("vscalesin_sf", s2d), + ("pad11", ">i4"), + ("pad12", ">i4"), + ("vp", "|a5"), + ("sig_vp", ">i4"), + ("pad13", ">i4"), + ("pad14", ">i4"), + ("corzin_vp", s2d), + ("pad15", ">i4"), + ("pad16", ">i4"), + ("hscalesin_vp", s2d), + ("pad17", ">i4"), + ("pad18", ">i4"), + ("vscalesin_vp", s2d), + ("pad19", ">i4"), + ("pad20", ">i4"), + ("t", "|a5"), + ("sig_t", ">i4"), + ("pad21", ">i4"), + ("pad22", ">i4"), + ("corzin_t", s2d), + ("pad23", ">i4"), + ("pad24", ">i4"), + ("hscalesin_t", s2d), + ("pad25", ">i4"), + ("pad26", ">i4"), + ("vscalesin_t", s2d), + ("pad27", ">i4"), + ("pad28", ">i4"), + ("q", "|a5"), + ("sig_q", ">i4"), + ("pad29", ">i4"), + ("pad30", ">i4"), + ("corzin_q", s2d), + ("corqin_q", s2d), + ("pad31", ">i4"), + ("pad32", ">i4"), + ("hscalesin_q", s2d), + ("pad33", ">i4"), + ("pad34", ">i4"), + ("vscalesin_q", s2d), + ("pad35", ">i4"), + ("pad36", ">i4"), + ("oz", "|a5"), + ("sig_oz", ">i4"), + ("pad37", ">i4"), + ("pad38", ">i4"), + ("corzin_oz", s2d), + ("pad39", ">i4"), + ("pad40", ">i4"), + ("hscalesin_oz", s2d), + ("pad41", ">i4"), + ("pad42", ">i4"), + ("vscalesin_oz", s2d), + ("pad43", ">i4"), + ("pad44", ">i4"), + ("cw", "|a5"), + ("sig_cw", ">i4"), + ("pad45", ">i4"), + ("pad46", ">i4"), + ("corzin_cw", s2d), + ("pad47", ">i4"), + ("pad48", ">i4"), + ("hscalesin_cw", s2d), + ("pad49", ">i4"), + ("pad50", ">i4"), + ("vscalesin_cw", s2d), + ("pad51", ">i4"), + ("pad52", ">i4"), + ("ps", "|a5"), + ("sig_ps", ">i4"), + ("pad53", ">i4"), + ("pad54", ">i4"), + ("corpin_ps", tnlat), + ("pad55", ">i4"), + ("pad56", ">i4"), + ("hscalespin_ps", tnlat), + ("pad57", ">i4"), + ("pad58", ">i4"), + ("sst", "|a5"), + ("sig_sst", ">i4"), + ("pad59", ">i4"), + ("pad60", ">i4"), + ("corsstin_sst", sst2d), + ("pad61", ">i4"), + ("pad62", ">i4"), + ("hsstin_ps", sst2d), + ("pad63", ">i4"), + ] + + dt_obj = np.dtype(dt) # , align=True) # align=True should be automatic (?) + # accounts for 4 bytes padding (before and after the records) + # Opens the file again to read all the records - with open(self.file_name, 'rb') as ftmp: - fobj = np.fromfile(ftmp, dtype=dt_obj, count=-1, offset=4) # count=-1 reads the whole file - + with open(self.file_name, "rb") as ftmp: + fobj = np.fromfile(ftmp, dtype=dt_obj, count=1, offset=4) + + if fobj.size != 1: + raise ValueError( + f"Invalid or truncated GCV records in {self.file_name!r}; " + f"expected at least {dt_obj.itemsize + 4} bytes" + ) + # - # Records reading - Regression coefficients (balance projection matrices) + # Records reading - Regression coefficients (balance projection matrices) # - - balprojs = {} - + + balprojs = {} + self.balprojs = balprojs - - agvin = np.reshape(fobj[0]['agvin'], (self.nlat, self.nlev, self.nlev), order='F') - da_agvin = xr.DataArray(agvin, dims=['latitude', 'level', 'level_2'], coords={'latitude':self.lats, 'level':self.levs, 'level_2':self.levs}) - da_agvin = da_agvin.transpose('level', 'latitude', 'level_2') - da_agvin = da_agvin.rename('agvin') - - balprojs['agvin'] = da_agvin - - bgvin = np.reshape(fobj[0]['bgvin'], (self.nlat, self.nlev), order='F') - da_bgvin = xr.DataArray(bgvin, dims=['latitude', 'level'], coords={'latitude':self.lats, 'level':self.levs}) - da_bgvin = da_bgvin.transpose('level', 'latitude') - da_bgvin = da_bgvin.rename('bgvin') - - balprojs['bgvin'] = da_bgvin - - wgvin = np.reshape(fobj[0]['wgvin'], (self.nlat, self.nlev), order='F') - da_wgvin = xr.DataArray(wgvin, dims=['latitude', 'level'], coords={'latitude':self.lats, 'level':self.levs}) - da_wgvin = da_wgvin.transpose('level', 'latitude') - da_wgvin = da_wgvin.rename('wgvin') - - balprojs['wgvin'] = da_wgvin - + + agvin = np.reshape( + fobj[0]["agvin"], (self.nlat, self.nlev, self.nlev), order="F" + ) + da_agvin = xr.DataArray( + agvin, + dims=["latitude", "level", "level_2"], + coords={"latitude": self.lats, "level": self.levs, "level_2": self.levs}, + ) + da_agvin = da_agvin.transpose("level", "latitude", "level_2") + da_agvin = da_agvin.rename("agvin") + + balprojs["agvin"] = da_agvin + + bgvin = np.reshape(fobj[0]["bgvin"], (self.nlat, self.nlev), order="F") + da_bgvin = xr.DataArray( + bgvin, + dims=["latitude", "level"], + coords={"latitude": self.lats, "level": self.levs}, + ) + da_bgvin = da_bgvin.transpose("level", "latitude") + da_bgvin = da_bgvin.rename("bgvin") + + balprojs["bgvin"] = da_bgvin + + wgvin = np.reshape(fobj[0]["wgvin"], (self.nlat, self.nlev), order="F") + da_wgvin = xr.DataArray( + wgvin, + dims=["latitude", "level"], + coords={"latitude": self.lats, "level": self.levs}, + ) + da_wgvin = da_wgvin.transpose("level", "latitude") + da_wgvin = da_wgvin.rename("wgvin") + + balprojs["wgvin"] = da_wgvin + # # Records reading - Amplitudes (standard deviations) # - + amplitudes = {} - + self.amplitudes = amplitudes - + amplitudes_names = { - 'sf': 'corzin_sf', - 'vp': 'corzin_vp', - 't': 'corzin_t', - 'q': 'corzin_q', - 'qin': 'corqin_q', - 'oz': 'corzin_oz', - 'ps': 'corpin_ps', - 'cw': 'corzin_cw', - 'sst': 'corsstin_sst', + "sf": "corzin_sf", + "vp": "corzin_vp", + "t": "corzin_t", + "q": "corzin_q", + "qin": "corqin_q", + "oz": "corzin_oz", + "ps": "corpin_ps", + "cw": "corzin_cw", + "sst": "corsstin_sst", } - + self.amplitudes_names = amplitudes_names - + # Loop over the variables to create a dictionary with xarrays for the amplitudes for var in amplitudes_names.items(): - if var[0] == 'ps': - corzin_var = np.reshape(fobj[0][var[1]], (self.nlat), order='F') - da_corzin_var = xr.DataArray(corzin_var, dims=['latitude'], coords={'latitude':self.lats}) - elif var[0] == 'sst': - corzin_var = np.reshape(fobj[0][var[1]], (self.nlat, self.nlon), order='F') - da_corzin_var = xr.DataArray(corzin_var, dims=['latitude', 'longitude'], coords={'latitude':self.lats, 'longitude':self.lons}) + if var[0] == "ps": + corzin_var = np.reshape(fobj[0][var[1]], (self.nlat), order="F") + da_corzin_var = xr.DataArray( + corzin_var, dims=["latitude"], coords={"latitude": self.lats} + ) + elif var[0] == "sst": + corzin_var = np.reshape( + fobj[0][var[1]], (self.nlat, self.nlon), order="F" + ) + da_corzin_var = xr.DataArray( + corzin_var, + dims=["latitude", "longitude"], + coords={"latitude": self.lats, "longitude": self.lons}, + ) else: - corzin_var = np.reshape(fobj[0][var[1]], (self.nlat, self.nlev), order='F') - da_corzin_var = xr.DataArray(corzin_var, dims=['latitude', 'level'], coords={'latitude':self.lats, 'level':self.levs}) - da_corzin_var = da_corzin_var.transpose('level', 'latitude') - + corzin_var = np.reshape( + fobj[0][var[1]], (self.nlat, self.nlev), order="F" + ) + da_corzin_var = xr.DataArray( + corzin_var, + dims=["latitude", "level"], + coords={"latitude": self.lats, "level": self.levs}, + ) + da_corzin_var = da_corzin_var.transpose("level", "latitude") + da_corzin_var = da_corzin_var.rename(var[1]) - + amplitudes[var[0]] = da_corzin_var - + # # Records reading - Horizontal length scales (in meters) -> the in plot_functions.py script, the horizontal length scales # are divided by 1000 # - + hscales = {} - + self.hscales = hscales - + hscales_var_names = { - 'sf': 'hscalesin_sf', - 'vp': 'hscalesin_vp', - 't': 'hscalesin_t', - 'q': 'hscalesin_q', - 'oz': 'hscalesin_oz', - 'ps': 'hscalespin_ps', - 'cw': 'hscalesin_cw', - 'sst': 'hsstin_ps', - } - + "sf": "hscalesin_sf", + "vp": "hscalesin_vp", + "t": "hscalesin_t", + "q": "hscalesin_q", + "oz": "hscalesin_oz", + "ps": "hscalespin_ps", + "cw": "hscalesin_cw", + "sst": "hsstin_ps", + } + self.hscales_var_names = hscales_var_names - + # Loop over the variables to create a dictionary with xarrays for the horizontal length scales for var in hscales_var_names.items(): - if var[0] == 'ps': - hscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat), order='F') - da_hscalesin_var = xr.DataArray(hscalesin_var, dims=['latitude'], coords={'latitude':self.lats}) - elif var[0] == 'sst': - hscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat, self.nlon), order='F') - da_hscalesin_var = xr.DataArray(hscalesin_var, dims=['latitude', 'longitude'], coords={'latitude':self.lats, 'longitude':self.lons}) + if var[0] == "ps": + hscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat), order="F") + da_hscalesin_var = xr.DataArray( + hscalesin_var, dims=["latitude"], coords={"latitude": self.lats} + ) + elif var[0] == "sst": + hscalesin_var = np.reshape( + fobj[0][var[1]], (self.nlat, self.nlon), order="F" + ) + da_hscalesin_var = xr.DataArray( + hscalesin_var, + dims=["latitude", "longitude"], + coords={"latitude": self.lats, "longitude": self.lons}, + ) else: - hscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat, self.nlev), order='F') - da_hscalesin_var = xr.DataArray(hscalesin_var, dims=['latitude', 'level'], coords={'latitude':self.lats, 'level':self.levs}) - da_hscalesin_var = da_hscalesin_var.transpose('level', 'latitude') - + hscalesin_var = np.reshape( + fobj[0][var[1]], (self.nlat, self.nlev), order="F" + ) + da_hscalesin_var = xr.DataArray( + hscalesin_var, + dims=["latitude", "level"], + coords={"latitude": self.lats, "level": self.levs}, + ) + da_hscalesin_var = da_hscalesin_var.transpose("level", "latitude") + da_hscalesin_var = da_hscalesin_var.rename(var[1]) - - hscales[var[0]] = da_hscalesin_var - + + hscales[var[0]] = da_hscalesin_var + # # Records reading - Vertical length scales # - + vscales = {} - + self.vscales = vscales vscales_var_names = { - 'sf': 'vscalesin_sf', - 'vp': 'vscalesin_vp', - 't': 'vscalesin_t', - 'q': 'vscalesin_q', - 'oz': 'vscalesin_oz', - 'cw': 'vscalesin_cw', - } - + "sf": "vscalesin_sf", + "vp": "vscalesin_vp", + "t": "vscalesin_t", + "q": "vscalesin_q", + "oz": "vscalesin_oz", + "cw": "vscalesin_cw", + } + self.vscales_var_names = vscales_var_names - + # Loop over the variables to create a dictionary with xarrays for the vertical length scales for var in vscales_var_names.items(): - if var[0] == 'ps': - vscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat), order='F') - da_vscalesin_var = xr.DataArray(vscalesin_var, dims=['latitude'], coords={'latitude':self.lats}) - elif var[0] == 'sst': - vscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat, self.nlon), order='F') - da_vscalesin_var = xr.DataArray(vscalesin_var, dims=['latitude', 'longitude'], coords={'latitude':self.lats, 'longitude':self.lons}) + if var[0] == "ps": + vscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat), order="F") + da_vscalesin_var = xr.DataArray( + vscalesin_var, dims=["latitude"], coords={"latitude": self.lats} + ) + elif var[0] == "sst": + vscalesin_var = np.reshape( + fobj[0][var[1]], (self.nlat, self.nlon), order="F" + ) + da_vscalesin_var = xr.DataArray( + vscalesin_var, + dims=["latitude", "longitude"], + coords={"latitude": self.lats, "longitude": self.lons}, + ) else: - vscalesin_var = np.reshape(fobj[0][var[1]], (self.nlat, self.nlev), order='F') - da_vscalesin_var = xr.DataArray(vscalesin_var, dims=['latitude', 'level'], coords={'latitude':self.lats, 'level':self.levs}) - da_vscalesin_var = da_vscalesin_var.transpose('level', 'latitude') - + vscalesin_var = np.reshape( + fobj[0][var[1]], (self.nlat, self.nlev), order="F" + ) + da_vscalesin_var = xr.DataArray( + vscalesin_var, + dims=["latitude", "level"], + coords={"latitude": self.lats, "level": self.levs}, + ) + da_vscalesin_var = da_vscalesin_var.transpose("level", "latitude") + da_vscalesin_var = da_vscalesin_var.rename(var[1]) - + vscales[var[0]] = da_vscalesin_var -# @property + # @property def my_name(self, name): - #return self._my_name - self.my_name = str(name) -# return self.my_name - -# @my_name.setter -# def my_name(self, name): -# self._my_name = str(name) - -# @property - def get_name(self): - return self.my_name + """Set the human-readable name used by the plotting helpers. + + This method is retained for backwards compatibility with the notebooks. + Unlike the previous implementation, it does not overwrite itself. + """ + self._name = str(name) + return self + + def get_name(self): + """Return the configured display name (the filename by default).""" + return self._name diff --git a/gsiberror/plot_functions.py b/gsiberror/plot_functions.py index 973cde2..49da1e8 100644 --- a/gsiberror/plot_functions.py +++ b/gsiberror/plot_functions.py @@ -1,448 +1,640 @@ #! /usr/bin/env python3 -import os import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import make_axes_locatable -from mpl_toolkits import axes_grid1 import cartopy.crs as ccrs import cartopy.feature as cfeature + # This function defines the names of the variables and mnemonics -def var_name(var): - - if var == 'sf': - vname = 'Stream function' - vsimb = '$\psi$' - elif var == 'vp': - vname = 'Velocity Potential' - vsimb = '$\chi$' - elif var == 't': - vname = 'Virtual Temperature' - vsimb = '$tv$' - elif var == 'q': - vname = 'Pseudo-Relative Humidity - qoption=1' - vsimb = '$rh_{p}$' - elif var == 'qin': - vname = 'Normalizes Relative Humidity - qoption=2' - vsimb = '$rh_{n}$' - elif var == 'oz': - vname = 'Ozone' - vsimb = '$oz$' - elif var == 'ps': - vname = 'Surface Pressure' - vsimb = '$ps$' - elif var == 'cw': - vname = 'Liquid Cloud Water Content' - vsimb = '$cw$' - elif var == 'sst': - vname = 'Sea Surface Temperature' - vsimb = '$sst$' - - return vname, vsimb +def var_name(var): + variables = { + "sf": ("Stream function", r"$\psi$"), + "vp": ("Velocity Potential", r"$\chi$"), + "t": ("Virtual Temperature", "$tv$"), + "q": ("Pseudo-Relative Humidity - qoption=1", "$rh_{p}$"), + "qin": ("Normalized Relative Humidity - qoption=2", "$rh_{n}$"), + "oz": ("Ozone", "$oz$"), + "ps": ("Surface Pressure", "$ps$"), + "cw": ("Liquid Cloud Water Content", "$cw$"), + "sst": ("Sea Surface Temperature", "$sst$"), + } + try: + return variables[var] + except KeyError as exc: + raise ValueError( + f"Unknown variable {var!r}; expected one of {', '.join(variables)}" + ) from exc + # This function defines global values of min and max given two xarrays -def global_minmax(l_matrix, t_array, m_rec): +def global_minmax(l_matrix, t_array, m_rec, scale=1.0): + + if not l_matrix: + raise ValueError("At least one Berror matrix is required") + if t_array not in {"balprojs", "amplitudes", "hscales", "vscales"}: + raise ValueError(f"Unknown data collection {t_array!r}") lmin = [] lmax = [] - + for mtx in l_matrix: - - if t_array == 'balprojs': - vmin = mtx.balprojs[str(m_rec)].min() - vmax = mtx.balprojs[str(m_rec)].max() - elif t_array == 'amplitudes': - vmin = mtx.amplitudes[str(m_rec)].min() - vmax = mtx.amplitudes[str(m_rec)].max() - elif t_array == 'hscales': - vmin = mtx.hscales[str(m_rec)].min() - vmax = mtx.hscales[str(m_rec)].max() - elif t_array == 'vscales': - vmin = mtx.vscales[str(m_rec)].min() - vmax = mtx.vscales[str(m_rec)].max() - + values = getattr(mtx, t_array)[str(m_rec)] * scale + vmin = float(values.min()) + vmax = float(values.max()) + lmin.append(vmin) lmax.append(vmax) return min(lmin), max(lmax) + # This function plots the regression coefficients def plot_reg_coeffs(lmatrix, rec, lev, **kwargs): - - if 'eqrange' in kwargs: - eqrange = kwargs['eqrange'] + if not lmatrix: + raise ValueError("At least one Berror matrix is required") + if rec not in {"agvin", "bgvin", "wgvin"}: + raise ValueError("rec must be one of 'agvin', 'bgvin', or 'wgvin'") + + if "eqrange" in kwargs: + eqrange = kwargs["eqrange"] else: eqrange = False - - if 'suptitle' in kwargs: - suptitle = kwargs['suptitle'] + + if "suptitle" in kwargs: + suptitle = kwargs["suptitle"] else: suptitle = False - - if 'savefig' in kwargs: - savefig = kwargs['savefig'] + + if "savefig" in kwargs: + savefig = kwargs["savefig"] else: - savefig = False - + savefig = False + len_lmatrix = len(lmatrix) - - if eqrange: - minval, maxval = global_minmax(lmatrix, 'balprojs', str(rec)) - + + if eqrange: + scale = 1e2 if rec == "wgvin" else 1.0 + minval, maxval = global_minmax(lmatrix, "balprojs", str(rec), scale) + length_x_axis = 20 length_y_axis = 10 - fig_height = 5. - + fig_height = 5.0 + rows = 1 - columns = len_lmatrix - + columns = len_lmatrix + height = length_y_axis * rows - width = length_x_axis * columns - - plot_aspect_ratio= float(width) / float(height) - - fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) - - spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace = .25, hspace = .25) - - cbar_kwargs = {'spacing': 'proportional', 'pad': 0.08, 'shrink': 1, 'aspect': 15, 'extend':'neither'} - - for i in range(rows*columns): - + width = length_x_axis * columns + + plot_aspect_ratio = float(width) / float(height) + + fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + + spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace=0.25, hspace=0.25) + + cbar_kwargs = { + "spacing": "proportional", + "pad": 0.08, + "shrink": 1, + "aspect": 15, + "extend": "neither", + } + + for i in range(rows * columns): ax = fig.add_subplot(spec[i]) - - if rec == 'agvin': - nrec = 'Virtual Temperature' + + if rec == "agvin": + nrec = "Virtual Temperature" if eqrange: - im = lmatrix[i].balprojs[str(rec)].isel(level_2=lev).plot.contourf(vmin=minval, vmax=maxval, add_colorbar=True, cbar_kwargs=cbar_kwargs, ax=ax) + lmatrix[i].balprojs[str(rec)].isel(level_2=lev).plot.contourf( + vmin=minval, + vmax=maxval, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + ax=ax, + ) else: - im = lmatrix[i].balprojs[str(rec)].isel(level_2=lev).plot.contourf(add_colorbar=True, cbar_kwargs=cbar_kwargs, ax=ax) - elif rec == 'bgvin': - nrec = 'Velocity Potencial' + lmatrix[i].balprojs[str(rec)].isel(level_2=lev).plot.contourf( + add_colorbar=True, cbar_kwargs=cbar_kwargs, ax=ax + ) + elif rec == "bgvin": + nrec = "Velocity Potencial" if eqrange: - im = lmatrix[i].balprojs[str(rec)].plot.contourf(vmin=minval, vmax=maxval, add_colorbar=True, cbar_kwargs=cbar_kwargs, ax=ax) + lmatrix[i].balprojs[str(rec)].plot.contourf( + vmin=minval, + vmax=maxval, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + ax=ax, + ) else: - im = lmatrix[i].balprojs[str(rec)].plot.contourf(add_colorbar=True, cbar_kwargs=cbar_kwargs, ax=ax) - elif rec == 'wgvin': - nrec = 'Surface Pressure' + lmatrix[i].balprojs[str(rec)].plot.contourf( + add_colorbar=True, cbar_kwargs=cbar_kwargs, ax=ax + ) + elif rec == "wgvin": + nrec = "Surface Pressure" # Note: multiplying by 1e2 (100) to make it comparable to https://dtcenter.ucar.edu/com-GSI/users/docs/presentations/2011_tutorial/L8_06302011-BkgObsErrs-DarylKleist.pdf - wgproj = lmatrix[i].balprojs[str(rec)]*1e2 + wgproj = lmatrix[i].balprojs[str(rec)] * 1e2 if eqrange: - im = wgproj.isel(level=0,latitude=slice(0,-2)).plot.line(ylim=[minval.data, maxval.data], ax=ax) + wgproj.isel(level=0, latitude=slice(0, -2)).plot.line( + ylim=[minval, maxval], ax=ax + ) else: - im = wgproj.isel(level=0,latitude=slice(0,-2)).plot.line(ax=ax) - - ax.set_title(str(lmatrix[i].get_name()) + '\n' + str(lmatrix[i].nlev) + ' levels') - + wgproj.isel(level=0, latitude=slice(0, -2)).plot.line(ax=ax) + + ax.set_title( + str(lmatrix[i].get_name()) + "\n" + str(lmatrix[i].nlev) + " levels" + ) + if suptitle: - if rec == 'agvin': - sptitle = plt.suptitle('Projection of the Stream Function ($\psi$) at the level ' + str(lev) + ' over the vertical profile of the balanced part of ' + str(nrec) + ' ($\mathbf{G}_{'+str(lev)+'}$): $T_{b}=\mathbf{G}\psi$', y=1.05, fontsize=16) - elif rec == 'bgvin': - sptitle = plt.suptitle('Projection of the Stream Function ($\psi$) over the balanced part of ' + str(nrec) + ' ($\mathbf{c}$): $\chi_{b}=\mathbf{c}\psi$', y=1.05, fontsize=16) - elif rec == 'wgvin': - sptitle = plt.suptitle('Projection of the Stream Function of the Stream Function ($\psi$) over the balanced part of ' + str(nrec) + ' ($\mathbf{w}$): $ps_{b}=\mathbf{w}\psi$', y=1.05, fontsize=16) - + if rec == "agvin": + sptitle = plt.suptitle( + r"Projection of the Stream Function ($\psi$) at the level " + + str(lev) + + " over the vertical profile of the balanced part of " + + str(nrec) + + r" ($\mathbf{G}_{" + + str(lev) + + r"}$): $T_{b}=\mathbf{G}\psi$", + y=1.05, + fontsize=16, + ) + elif rec == "bgvin": + sptitle = plt.suptitle( + r"Projection of the Stream Function ($\psi$) over the balanced part of " + + str(nrec) + + r" ($\mathbf{c}$): $\chi_{b}=\mathbf{c}\psi$", + y=1.05, + fontsize=16, + ) + elif rec == "wgvin": + sptitle = plt.suptitle( + r"Projection of the Stream Function of the Stream Function ($\psi$) over the balanced part of " + + str(nrec) + + r" ($\mathbf{w}$): $ps_{b}=\mathbf{w}\psi$", + y=1.05, + fontsize=16, + ) + if savefig: if suptitle: - fig.savefig('reg_coeffs_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight', bbox_extra_artists=[sptitle]) + fig.savefig( + "reg_coeffs_" + str(rec) + ".png", + dpi=fig.dpi, + bbox_inches="tight", + bbox_extra_artists=[sptitle], + ) else: - fig.savefig('reg_coeffs_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight') + fig.savefig( + "reg_coeffs_" + str(rec) + ".png", dpi=fig.dpi, bbox_inches="tight" + ) + + return fig + # This function plots the amplitudes -def plot_amplitudes(lmatrix, rec, **kwargs): - - if 'eqrange' in kwargs: - eqrange = kwargs['eqrange'] +def plot_amplitudes(lmatrix, rec, **kwargs): + if not lmatrix: + raise ValueError("At least one Berror matrix is required") + var_name(rec) + + if "eqrange" in kwargs: + eqrange = kwargs["eqrange"] else: eqrange = False - if 'profile' in kwargs: - profile = kwargs['profile'] + if "profile" in kwargs: + profile = kwargs["profile"] else: profile = False - - if 'suptitle' in kwargs: - suptitle = kwargs['suptitle'] + + if "suptitle" in kwargs: + suptitle = kwargs["suptitle"] else: - suptitle = False + suptitle = False - if 'savefig' in kwargs: - savefig = kwargs['savefig'] + if "savefig" in kwargs: + savefig = kwargs["savefig"] else: - savefig = False - - if rec == 'ps' or rec == 'sst': + savefig = False + + if rec == "ps" or rec == "sst": profile = False - + len_lmatrix = len(lmatrix) - - if eqrange: - minval, maxval = global_minmax(lmatrix, 'amplitudes', str(rec)) + + if eqrange: + scale = 1e2 if rec in {"q", "qin"} and not profile else 1.0 + minval, maxval = global_minmax(lmatrix, "amplitudes", str(rec), scale) length_x_axis = 20 length_y_axis = 10 - fig_height = 5. - + fig_height = 5.0 + rows = 1 - columns = len_lmatrix - + columns = len_lmatrix + height = length_y_axis * rows - width = length_x_axis * columns - - plot_aspect_ratio= float(width) / float(height) - - fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) - -# if profile: -# fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) -# else: -# if rec == 'sst': -# fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) -# else: -# fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) - - spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace = .25, hspace = .25) - - cbar_kwargs = {'spacing': 'proportional', 'pad': 0.08, 'shrink': 1, 'aspect': 15, 'extend':'neither'} - + width = length_x_axis * columns + + plot_aspect_ratio = float(width) / float(height) + + fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + + # if profile: + # fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + # else: + # if rec == 'sst': + # fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + # else: + # fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + + spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace=0.25, hspace=0.25) + + cbar_kwargs = { + "spacing": "proportional", + "pad": 0.08, + "shrink": 1, + "aspect": 15, + "extend": "neither", + } + crs = ccrs.PlateCarree() - + nrec = var_name(rec)[0] srec = var_name(rec)[1] - - for i in range(rows*columns): - - if rec == 'sst': + + for i in range(rows * columns): + if rec == "sst": ax = plt.subplot(spec[i], projection=crs) else: ax = plt.subplot(spec[i]) - + if profile: if eqrange: - im = lmatrix[i].amplitudes[str(rec)].mean(dim='latitude').plot(ax=ax, y='level', xlim=(minval, maxval)) + lmatrix[i].amplitudes[str(rec)].mean(dim="latitude").plot( + ax=ax, y="level", xlim=(minval, maxval) + ) else: - im = lmatrix[i].amplitudes[str(rec)].mean(dim='latitude').plot(ax=ax, y='level') + lmatrix[i].amplitudes[str(rec)].mean(dim="latitude").plot( + ax=ax, y="level" + ) else: - if rec == 'sst': - lmatrix[i].amplitudes[str(rec)].plot.contourf(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) - ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '110m', edgecolor='face', facecolor='white')) - ax.coastlines() - elif rec == 'qin': + if rec == "sst": + plot_kwargs = {"vmin": minval, "vmax": maxval} if eqrange else {} + lmatrix[i].amplitudes[str(rec)].plot.contourf( + ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs, **plot_kwargs + ) + ax.add_feature( + cfeature.NaturalEarthFeature( + "physical", "land", "110m", edgecolor="face", facecolor="white" + ) + ) + ax.coastlines() + elif rec == "qin": # Note 1: slice(0,25) is applied to plot just the first quarter of the field # in an attempt to retrieve something comparable to https://dtcenter.ucar.edu/com-GSI/users/docs/presentations/2011_tutorial/L8_06302011-BkgObsErrs-DarylKleist.pdf # Note 2: multiplying by 1e2 (100) to make it comparable to the above document - ampqin = lmatrix[i].amplitudes[str(rec)]*1e2 + ampqin = lmatrix[i].amplitudes[str(rec)] * 1e2 if eqrange: - im = ampqin.isel(latitude=slice(0,25)).drop('latitude').plot.contourf(ax=ax, vmin=minval, vmax=maxval, add_colorbar=True, cbar_kwargs=cbar_kwargs, add_labels=False) + ampqin.isel(latitude=slice(0, 25)).drop("latitude").plot.contourf( + ax=ax, + vmin=minval, + vmax=maxval, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + add_labels=False, + ) else: - im = ampqin.isel(latitude=slice(0,25)).drop('latitude').plot.contourf(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs, add_labels=False) - elif rec == 'q': + ampqin.isel(latitude=slice(0, 25)).drop("latitude").plot.contourf( + ax=ax, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + add_labels=False, + ) + elif rec == "q": # Note: multiplying by 1e2 (100) to make it comparable to the above document - ampq = lmatrix[i].amplitudes[str(rec)]*1e2 + ampq = lmatrix[i].amplitudes[str(rec)] * 1e2 if eqrange: - im = ampq.plot.contourf(ax=ax, vmin=minval, vmax=maxval, add_colorbar=True, cbar_kwargs=cbar_kwargs) + ampq.plot.contourf( + ax=ax, + vmin=minval, + vmax=maxval, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + ) else: - im = ampq.plot.contourf(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) - elif rec == 'ps': + ampq.plot.contourf( + ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs + ) + elif rec == "ps": if eqrange: - im = lmatrix[i].amplitudes[str(rec)].plot(ax=ax, ylim=(minval, maxval)) + lmatrix[i].amplitudes[str(rec)].plot(ax=ax, ylim=(minval, maxval)) else: - #im = lmatrix[i].amplitudes[str(rec)].plot(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) - im = lmatrix[i].amplitudes[str(rec)].plot(ax=ax) + # im = lmatrix[i].amplitudes[str(rec)].plot(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) + lmatrix[i].amplitudes[str(rec)].plot(ax=ax) else: if eqrange: - im = lmatrix[i].amplitudes[str(rec)].plot.contourf(ax=ax, vmin=minval, vmax=maxval, add_colorbar=True, cbar_kwargs=cbar_kwargs) + lmatrix[i].amplitudes[str(rec)].plot.contourf( + ax=ax, + vmin=minval, + vmax=maxval, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + ) else: - im = lmatrix[i].amplitudes[str(rec)].plot.contourf(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) + lmatrix[i].amplitudes[str(rec)].plot.contourf( + ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs + ) - if rec == 'sst': + if rec == "sst": ax.set_title(str(lmatrix[i].get_name())) else: - ax.set_title(str(lmatrix[i].get_name()) + ' (' + str(lmatrix[i].nlev) + ' levels)') - + ax.set_title( + str(lmatrix[i].get_name()) + " (" + str(lmatrix[i].nlev) + " levels)" + ) + if suptitle: - if rec == 'sf': - sptitle = plt.suptitle('Standard Deviation of ' + str(nrec) + ' (' + str(srec) + ')', y=1.05, fontsize=16) - elif rec == 'q' or rec == 'qin': - sptitle = plt.suptitle('Standard Deviation of the unbalanced part of ' + str(nrec) + ' (' + str(srec) + ', %)', y=1.05) + if rec == "sf": + sptitle = plt.suptitle( + "Standard Deviation of " + str(nrec) + " (" + str(srec) + ")", + y=1.05, + fontsize=16, + ) + elif rec == "q" or rec == "qin": + sptitle = plt.suptitle( + "Standard Deviation of the unbalanced part of " + + str(nrec) + + " (" + + str(srec) + + ", %)", + y=1.05, + ) else: - #sptitle = plt.suptitle('Desvio Padrão da Parte não balanceada da ' + str(nrec) + ' (' + str(srec) + ')', y=1.05) - sptitle = plt.suptitle('Standard Deviation of the unbalanced part of ' + str(nrec) + ' (' + str(srec) + ')', y=1.05) - + # sptitle = plt.suptitle('Desvio Padrão da Parte não balanceada da ' + str(nrec) + ' (' + str(srec) + ')', y=1.05) + sptitle = plt.suptitle( + "Standard Deviation of the unbalanced part of " + + str(nrec) + + " (" + + str(srec) + + ")", + y=1.05, + ) + if savefig: if suptitle: - fig.savefig('amplitudes_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight', bbox_extra_artists=[sptitle]) + fig.savefig( + "amplitudes_" + str(rec) + ".png", + dpi=fig.dpi, + bbox_inches="tight", + bbox_extra_artists=[sptitle], + ) else: - fig.savefig('amplitudes_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight') + fig.savefig( + "amplitudes_" + str(rec) + ".png", dpi=fig.dpi, bbox_inches="tight" + ) + + return fig + + +# This function plots the horizontal length scales +def plot_hscales(lmatrix, rec, **kwargs): + if not lmatrix: + raise ValueError("At least one Berror matrix is required") + var_name(rec) -# This function plots the horizontal length scales -def plot_hscales(lmatrix, rec, **kwargs): - - if 'eqrange' in kwargs: - eqrange = kwargs['eqrange'] + if "eqrange" in kwargs: + eqrange = kwargs["eqrange"] else: - eqrange = False + eqrange = False - if 'suptitle' in kwargs: - suptitle = kwargs['suptitle'] + if "suptitle" in kwargs: + suptitle = kwargs["suptitle"] else: - suptitle = False - - if 'savefig' in kwargs: - savefig = kwargs['savefig'] + suptitle = False + + if "savefig" in kwargs: + savefig = kwargs["savefig"] else: - savefig = False + savefig = False len_lmatrix = len(lmatrix) - - if eqrange: - minval, maxval = global_minmax(lmatrix, 'hscales', str(rec)) -# if rec == 'sst': -# fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(20,4), subplot_kw={'projection': ccrs.PlateCarree()}) -# else: -# fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(10,4)) + if eqrange: + minval, maxval = global_minmax(lmatrix, "hscales", str(rec), 1e-3) + + # if rec == 'sst': + # fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(20,4), subplot_kw={'projection': ccrs.PlateCarree()}) + # else: + # fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(10,4)) length_x_axis = 20 length_y_axis = 10 - fig_height = 5. - + fig_height = 5.0 + rows = 1 - columns = len_lmatrix - + columns = len_lmatrix + height = length_y_axis * rows - width = length_x_axis * columns - - plot_aspect_ratio= float(width) / float(height) - - fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) - -# if rec == 'sst': -# fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) -# else: -# fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) - - spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace = .25, hspace = .25) - - cbar_kwargs = {'spacing': 'proportional', 'pad': 0.08, 'shrink': 1, 'aspect': 15, 'extend':'neither'} - + width = length_x_axis * columns + + plot_aspect_ratio = float(width) / float(height) + + fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + + # if rec == 'sst': + # fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + # else: + # fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + + spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace=0.25, hspace=0.25) + + cbar_kwargs = { + "spacing": "proportional", + "pad": 0.08, + "shrink": 1, + "aspect": 15, + "extend": "neither", + } + crs = ccrs.PlateCarree() - - nrec = var_name(rec)[0] - srec = var_name(rec)[1] - - for i in range(rows*columns): - - if rec == 'sst': + + nrec = var_name(rec)[0] + srec = var_name(rec)[1] + + for i in range(rows * columns): + if rec == "sst": ax = plt.subplot(spec[i], projection=crs) else: ax = plt.subplot(spec[i]) - + # m -> km to make it consistent with https://dtcenter.ucar.edu/com-GSI/users/docs/presentations/2011_tutorial/L8_06302011-BkgObsErrs-DarylKleist.pdf - hscl = lmatrix[i].hscales[str(rec)]*1e-3 - - if rec == 'sst': - hscl.plot.contourf(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) - ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '110m', edgecolor='face', facecolor='white')) + hscl = lmatrix[i].hscales[str(rec)] * 1e-3 + + if rec == "sst": + plot_kwargs = {"vmin": minval, "vmax": maxval} if eqrange else {} + hscl.plot.contourf( + ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs, **plot_kwargs + ) + ax.add_feature( + cfeature.NaturalEarthFeature( + "physical", "land", "110m", edgecolor="face", facecolor="white" + ) + ) ax.coastlines() - - elif rec == 'ps': + + elif rec == "ps": if eqrange: - hscl.plot(ax=ax, ylim=(minval, maxval)) + hscl.plot(ax=ax, ylim=(minval, maxval)) else: - hscl.plot(ax=ax)#, add_colorbar=True, cbar_kwargs=cbar_kwargs) + hscl.plot(ax=ax) # , add_colorbar=True, cbar_kwargs=cbar_kwargs) else: - if eqrange: - hscl.plot.contourf(ax=ax, vmin=minval, vmax=maxval, add_colorbar=True, cbar_kwargs=cbar_kwargs) - else: + if eqrange: + hscl.plot.contourf( + ax=ax, + vmin=minval, + vmax=maxval, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + ) + else: hscl.plot.contourf(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) - if rec == 'sst': - ax.set_title(str(lmatrix[i].get_name())) + if rec == "sst": + ax.set_title(str(lmatrix[i].get_name())) else: - ax.set_title(str(lmatrix[i].get_name()) + ' (' + str(lmatrix[i].nlev) + ' levels)') - + ax.set_title( + str(lmatrix[i].get_name()) + " (" + str(lmatrix[i].nlev) + " levels)" + ) + if suptitle: - sptitle = plt.suptitle('Horizontal Length Scale of ' + str(nrec) + ' (' + str(srec) + ', km)', y=1.05, fontsize=16) - + sptitle = plt.suptitle( + "Horizontal Length Scale of " + str(nrec) + " (" + str(srec) + ", km)", + y=1.05, + fontsize=16, + ) + if savefig: if suptitle: - fig.savefig('hscales_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight', bbox_extra_artists=[sptitle]) + fig.savefig( + "hscales_" + str(rec) + ".png", + dpi=fig.dpi, + bbox_inches="tight", + bbox_extra_artists=[sptitle], + ) else: - fig.savefig('hscales_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight') + fig.savefig( + "hscales_" + str(rec) + ".png", dpi=fig.dpi, bbox_inches="tight" + ) + + return fig + -# This function plots vertical length scales -def plot_vscales(lmatrix, rec, **kwargs): +# This function plots vertical length scales +def plot_vscales(lmatrix, rec, **kwargs): + if not lmatrix: + raise ValueError("At least one Berror matrix is required") + var_name(rec) - if 'eqrange' in kwargs: - eqrange = kwargs['eqrange'] + if "eqrange" in kwargs: + eqrange = kwargs["eqrange"] else: eqrange = False - - if 'suptitle' in kwargs: - suptitle = kwargs['suptitle'] + + if "suptitle" in kwargs: + suptitle = kwargs["suptitle"] else: - suptitle = False + suptitle = False - if 'savefig' in kwargs: - savefig = kwargs['savefig'] + if "savefig" in kwargs: + savefig = kwargs["savefig"] else: - savefig = False - + savefig = False + len_lmatrix = len(lmatrix) - - if eqrange: - minval, maxval = global_minmax(lmatrix, 'vscales', str(rec)) -# if rec == 'sst': -# fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(20,4), subplot_kw={'projection': ccrs.PlateCarree()}) -# else: -# fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(10,4)) + if eqrange: + minval, maxval = global_minmax(lmatrix, "vscales", str(rec)) + + # if rec == 'sst': + # fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(20,4), subplot_kw={'projection': ccrs.PlateCarree()}) + # else: + # fig, axs = plt.subplots(1, len_lmatrix, constrained_layout=False, figsize=(10,4)) length_x_axis = 20 length_y_axis = 10 - fig_height = 5. - + fig_height = 5.0 + rows = 1 - columns = len_lmatrix - + columns = len_lmatrix + height = length_y_axis * rows - width = length_x_axis * columns - - plot_aspect_ratio= float(width) / float(height) - -# if rec == 'sst': -# fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) -# else: -# fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) - - fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) - - spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace = .25, hspace = .25) - - cbar_kwargs = {'spacing': 'proportional', 'pad': 0.08, 'shrink': 1, 'aspect': 15, 'extend':'neither'} - - crs = ccrs.PlateCarree() - - nrec = var_name(rec)[0] - srec = var_name(rec)[1] - - for i in range(rows*columns): - - ax = plt.subplot(spec[i]) - + width = length_x_axis * columns + + plot_aspect_ratio = float(width) / float(height) + + # if rec == 'sst': + # fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + # else: + # fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + + fig = plt.figure(figsize=(fig_height * plot_aspect_ratio, fig_height)) + + spec = fig.add_gridspec(ncols=len_lmatrix, nrows=rows, wspace=0.25, hspace=0.25) + + cbar_kwargs = { + "spacing": "proportional", + "pad": 0.08, + "shrink": 1, + "aspect": 15, + "extend": "neither", + } + + nrec = var_name(rec)[0] + srec = var_name(rec)[1] + + for i in range(rows * columns): + ax = plt.subplot(spec[i]) + if eqrange: - lmatrix[i].vscales[str(rec)].plot.contourf(ax=ax, vmin=minval, vmax=maxval, add_colorbar=True, cbar_kwargs=cbar_kwargs) - else: - lmatrix[i].vscales[str(rec)].plot.contourf(ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs) + lmatrix[i].vscales[str(rec)].plot.contourf( + ax=ax, + vmin=minval, + vmax=maxval, + add_colorbar=True, + cbar_kwargs=cbar_kwargs, + ) + else: + lmatrix[i].vscales[str(rec)].plot.contourf( + ax=ax, add_colorbar=True, cbar_kwargs=cbar_kwargs + ) + + ax.set_title( + str(lmatrix[i].get_name()) + " (" + str(lmatrix[i].nlev) + " levels)" + ) - ax.set_title(str(lmatrix[i].get_name()) + ' (' + str(lmatrix[i].nlev) + ' levels)') - if suptitle: - sptitle = plt.suptitle('Vertical Length Scale of ' + str(nrec) + ' (' + str(srec) + ', grid units)', y=1.05, fontsize=16) - + sptitle = plt.suptitle( + "Vertical Length Scale of " + + str(nrec) + + " (" + + str(srec) + + ", grid units)", + y=1.05, + fontsize=16, + ) + if savefig: if suptitle: - fig.savefig('vscales_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight', bbox_extra_artists=[sptitle]) + fig.savefig( + "vscales_" + str(rec) + ".png", + dpi=fig.dpi, + bbox_inches="tight", + bbox_extra_artists=[sptitle], + ) else: - fig.savefig('vscales_' + str(rec) + '.png', dpi=fig.dpi, bbox_inches='tight') + fig.savefig( + "vscales_" + str(rec) + ".png", dpi=fig.dpi, bbox_inches="tight" + ) + + return fig diff --git a/setup.py b/setup.py index b3d59c2..776ebdc 100644 --- a/setup.py +++ b/setup.py @@ -1,28 +1,35 @@ -from setuptools import setup, find_packages +from pathlib import Path + +from setuptools import find_packages, setup + + +ROOT = Path(__file__).parent setup( - name='GSIBerror', - version='1.1.0', - url='https://gad-dimnt-cptec.github.io/GSIBerror', - author='Carlos Frederico Bastarz', - author_email='carlos.bastarz@inpe.br', - url = "https://github.com/GAD-DIMNT-CPTEC/GSIBerror", - license = "CC BY-NC-SA-4.0", - long_description=open('README.md').read(), - long_description_content_type='text/markdown', - description='A Python class to read the records and attributes from the background error covariance matrices compatible with the Gridpoint Statistical Interpolation in the .gcv file format.', + name="GSIBerror", + version="1.1.0", + author="Carlos Frederico Bastarz", + author_email="carlos.bastarz@inpe.br", + url="https://github.com/GAD-DIMNT-CPTEC/GSIBerror", + project_urls={ + "Documentation": "https://gad-dimnt-cptec.github.io/GSIBerror", + }, + license="CC BY-NC-SA-4.0", + long_description=(ROOT / "README.md").read_text(encoding="utf-8"), + long_description_content_type="text/markdown", + description="A Python class to read the records and attributes from the background error covariance matrices compatible with the Gridpoint Statistical Interpolation in the .gcv file format.", packages=find_packages(), install_requires=[ - 'numpy>=1.22', - 'xarray', - 'Cartopy==0.22.0', - 'matplotlib', - ], - extra_requires={'dev': ['twine>=4.0.2']}, + "numpy>=1.22", + "xarray", + "Cartopy>=0.22.0", + "matplotlib", + ], + extras_require={"dev": ["pytest>=7", "ruff", "twine>=4.0.2"]}, classifiers=[ - 'Programming Language :: Python :: 3', - 'License :: OSI Approved :: MIT License', - 'Operating System :: OS Independent', + "Programming Language :: Python :: 3", + "License :: Other/Proprietary License", + "Operating System :: OS Independent", ], - python_requires='>=3.9.18', + python_requires=">=3.9.18", ) diff --git a/tests/test_berror.py b/tests/test_berror.py new file mode 100644 index 0000000..5702ae4 --- /dev/null +++ b/tests/test_berror.py @@ -0,0 +1,39 @@ +from pathlib import Path + +import pytest + +import gsiberror as gb + + +DATA = Path(__file__).parents[1] / "data" +SAMPLE = DATA / "global_berror.l64y386.f77-ncep-dtc.gcv" + + +def test_reports_actionable_error_for_unfetched_lfs_data(): + with pytest.raises(ValueError, match="git lfs pull"): + gb.Berror(SAMPLE).read_records() + + +def test_display_name_can_be_changed_more_than_once(): + berror = gb.Berror(SAMPLE) + + assert berror.get_name() == SAMPLE.name + assert berror.my_name("first") is berror + assert berror.my_name("second") is berror + assert berror.get_name() == "second" + + +def test_rejects_truncated_file(tmp_path): + truncated = tmp_path / "truncated.gcv" + truncated.write_bytes(b"1234") + + with pytest.raises(ValueError, match="truncated GCV header"): + gb.Berror(truncated).read_records() + + +def test_rejects_non_positive_grid_dimensions(tmp_path): + invalid = tmp_path / "invalid.gcv" + invalid.write_bytes(b"\0" * 20) + + with pytest.raises(ValueError, match="Invalid GCV grid dimensions"): + gb.Berror(invalid).read_records() diff --git a/tests/test_plot_functions.py b/tests/test_plot_functions.py new file mode 100644 index 0000000..ee83447 --- /dev/null +++ b/tests/test_plot_functions.py @@ -0,0 +1,36 @@ +from types import SimpleNamespace + +import numpy as np +import pytest +import xarray as xr + +from gsiberror.plot_functions import global_minmax, var_name + + +def matrix(values): + array = xr.DataArray(np.asarray(values)) + return SimpleNamespace( + amplitudes={"q": array}, + balprojs={"wgvin": array}, + hscales={"sf": array}, + vscales={"sf": array}, + ) + + +def test_var_name_rejects_unknown_variable(): + with pytest.raises(ValueError, match="Unknown variable"): + var_name("invalid") + + +def test_global_minmax_applies_plot_unit_conversion(): + matrices = [matrix([1, 2]), matrix([-3, 4])] + + assert global_minmax(matrices, "amplitudes", "q", scale=100) == (-300, 400) + assert global_minmax(matrices, "hscales", "sf", scale=0.001) == (-0.003, 0.004) + + +def test_global_minmax_validates_inputs(): + with pytest.raises(ValueError, match="At least one"): + global_minmax([], "amplitudes", "q") + with pytest.raises(ValueError, match="Unknown data collection"): + global_minmax([matrix([1])], "invalid", "q")