Replies: 1 comment
-
I got this to work by modifying my code slightly and properly broadcasting import os
import pytest
import gsw_xarray as gsw
import xarray as xr
import numpy as np
import pandas as pd
"""
Note test requires use of gsw-xarray package to run Nsquared
https://github.com/DocOtak/gsw-xarray
"""
@pytest.fixture(scope="function")
def setup(request):
request.cls.lons = np.arange(0, 2, 1)
request.cls.lats = np.arange(0, 5, 1)
request.cls.depths = np.arange(0, 40, 1)
request.cls.times = np.arange(np.datetime64("2000-01-01"), np.datetime64("2010-01-01"), np.timedelta64(1, "7D"))
@pytest.mark.usefixtures("setup")
class Test_gsw:
def get_4d_coords(self):
return {"depth": (["depth"], self.depths),
"time": (["time"], self.times),
"lat": (["y"], self.lats),
"lon": (["x"], self.lons),
}
def create_4d_src_dataset(
self, source_4d_depth_levels, pmid=None, name="temperature"
) -> xr.Dataset:
if pmid is not None:
self.depths = pmid
return xr.DataArray(
name=name,
data=source_4d_depth_levels,
coords=self.get_4d_coords(),
dims=["depth", "time", "y", "x"],
).to_dataset()
def test_N2(self):
"""Test to use xarray to calculate the square of the buoyancy frequency.
Returns: None
"""
CT = 10 * np.random.rand(len(self.depths), len(self.times), len(self.lats), len(self.lons))
SA = 35 * np.random.rand(len(self.depths), len(self.times), len(self.lats), len(self.lons))
ds_temp = self.create_4d_src_dataset(CT, name="temp")
ds_sa = self.create_4d_src_dataset(SA, name="so")
ds_sa = ds_sa.assign(depth_n=ds_sa["depth"])
(ds1, ds2) = xr.broadcast(ds_sa, ds_temp)
N2, pmid = xr.apply_ufunc(gsw.Nsquared,
ds1["so"].values,
ds2["temp"].values,
ds1["depth_n"].values,
input_core_dims=[["depth", "time", "y", "x"],
["depth", "time", "y", "x"],
["depth"]],
output_core_dims=[["depth", "time", "y", "x"],
["depth", "time", "y", "x"]],
exclude_dims=set(("depth", "time", "y", "x",)),
vectorize=True)
ds_n2 = self.create_4d_src_dataset(N2, pmid=np.squeeze(pmid[:, 0, 0, 0]), name="n2")
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi all,
I would like to run the calculation of the squared buoyancy at grid points (
lat
,lon
) with time-varying properties at depth. This. gives me 4D variables as input to my function (time
,depth
,lat
,lon
). I use thegsw-xarray
wrapper package for ocean packagegsw
from where I use the functionNsquared
. TheNsquared
function is calculated as a function of depth and the wrapper package enablesDataArray
as input. I am having some issues getting this to work when following the example inxarray
and I am hoping you could help me. Below is a standalonepytest
that currently fails with error (requires thegsw-xarray
package to run):The test:
The header of the
Nsquared
function ingsw
looks like this:Beta Was this translation helpful? Give feedback.
All reactions