Extracting isopycnals from multi-dimensional arrays

@Aidan Thanks for the tips - I’ll get it working this week and then update my replies.

@Dougie where my code above takes 14 mins, yours takes 2 mins. Thank you!

1 Like

I also want to include this comment about how to do, and not to do, loops with xarray.

For a person coming from matlab, and even python, I pre-set my array size, then fill it in. With xarray you do something different. As far as I understand it, you tell xarray all the calculations it needs to do in a for loop. Then, once the for loop is complete you tell it to actually do those calculations, at which point the size of the array is set. Thanks to Dougie for explaining this to me.

Below is an example of how to loop Dougie’s code (above) to extract information about all the isopycnals. This xarray-approved way uses a list and xarray.concat:

isopycnal_layer_depths = []
for z in range(start,finish): # iterate over the depth/density coordinates
        isopycnal_layer_depth = isosurface(gridded_gamma, density_bins[z], dim='pressure')
        isopycnal_layer_depth = isopycnal_layer_depth.assign_coords({"isopycnal_surface": density_bins[z]})
        isopycnal_layer_depths.append(isopycnal_layer_depth)

isopycnal_layer_depths = xr.concat(isopycnal_layer_depths, dim="isopycnal_surface").compute()

Just noting that when the aim is to transform the entire field (rather than just extracting one or a few isosurfaces), I think one of the approaches in @claireyung’s great notebook is probably better.

I just notice the extend that this thread :thread: reached.

Is there something we need to add or modify the current example to explain things better/optimize things? Did anyone added an issue about this in the hackathon tasks?