Stream: CESM-diagnostics

Topic: Region Mask


view this post on Zulip David Bailey (Jan 29 2024 at 19:34):

I am trying to form region mask from the MOM6 latitude and longitude arrays. This is a tripole grid, so might be why I am running into problems here. Here is the code and error. I'm guessing it is because there are two regions in the latitude array that meet the criteria of being between 50 and 78 on the tripole grid? Does anyone have experience with this?

latm = [50.0, 78.0]
lonm = [284.0, 35.0]

lon = np.where(TLON < 0, TLON+360.,TLON)

print(latm)
print(lonm)
print(np.max(lon))

mask = np.where(((TLAT > latm[0] and TLAT < latm[1]) and (lon > lonm[0] or lon < lonm[1]),1,0))

ValueError Traceback (most recent call last)
Cell In[103], line 10
7 print(lonm)
8 print(np.max(lon))
---> 10 mask = np.where(((TLAT > latm[0] and TLAT < latm[1]) and (lon > lonm[0] or lon < lonm[1]),1.,0))
12 ds1_lab = (tareads1.aice).sum(dim=['nj','ni'])1.0e-12
13 ds2_lab = (tareads2.aice).sum(dim=['nj','ni'])1.0e-12

File /glade/work/dbailey/conda-envs/cupid-analysis/lib/python3.11/site-packages/xarray/core/common.py:154, in AbstractArray.__bool__(self)
153 def __bool__(self: Any) -> bool:
--> 154 return bool(self.values)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

view this post on Zulip Michael Levy (Jan 29 2024 at 19:54):

The error is coming from the and and or statements -- when your conditionals are in arrays, you need to use np.logical_and(cond1, cond2) and np.logical_or(cond1, cond2) instead of cond1 and cond2 and cond1 or cond2, respectively.

view this post on Zulip Michael Levy (Jan 29 2024 at 19:56):

Can you try

mask = np.where(np.logical_and(np.logical_and(TLAT > latm[0], TLAT < latm[1]),
                               np.logical_or(lon > lonm[0], lon < lonm[1])),1,0)

(I think I got the parentheses right, but you might need to play with it -- also, should the logical_or be another logical_and?)

view this post on Zulip David Bailey (Jan 29 2024 at 19:57):

Got it. I will try that out. I think the longitude condition should be an or.

view this post on Zulip Michael Levy (Jan 29 2024 at 19:58):

David Bailey said:

Got it. I will try that out. I think the longitude condition should be an or.

Oh, because it wraps around 0... I think you're right. I didn't actually look at the values in lonm before saying that

view this post on Zulip David Bailey (Jan 29 2024 at 21:32):

This works! I think I like this idea, because I can form several masks and multiply them together for more complicated regions.

mask1 = np.where(np.logical_and(TLAT > latm[0], TLAT < latm[1]),1.,0.)
mask2 = np.where(np.logical_or(lon > lonm[0], lon < lonm[1]),1.,0.)
mask = mask1*mask2

ds1_lab = (mask*tarea*ds1.aice).sum(dim=['nj','ni'])*1.0e-12
ds2_lab = (mask*tarea*ds2.aice).sum(dim=['nj','ni'])*1.0e-12

Last updated: May 16 2025 at 17:14 UTC