Back to home page

MITgcm

 
 

    


File indexing completed on 2025-11-19 06:09:44 UTC

view on githubraw file Latest commit e6feef68 on 2025-11-18 19:40:16 UTC
58679b5a83 Esta*0001 # Created by EGavilan Pascual-Ahuir on 2023-04-07
                0002 import numpy as np
                0003 import matplotlib.pyplot as plt
                0004 import matplotlib.patches as patches
                0005 from matplotlib.colors import ListedColormap
                0006 from mpl_toolkits.axes_grid1.inset_locator import (mark_inset,inset_axes,
                0007                                                   zoomed_inset_axes)
                0008 __doc__ = """
                0009 Utilities for MITgcm.
                0010 """
                0011 
                0012 _typeprefixes = {'ieee-be': '>',
                0013                  'b': '>',
                0014                  '>': '>',
                0015                  'ieee-le': '<',
                0016                  'l': '<',
                0017                  '<': '<',
                0018                  }
                0019 _typesuffixes = {'float32': 'f4',
                0020                  'float64': 'f8',
                0021                  }
                0022 
                0023 cmap_lm =  ListedColormap(["lightsteelblue"])
                0024 
                0025 def gen_blanklist(depth, sNx, sNy, tilemap=False,fill_value=0):
                0026     """
                0027     Computes blanklist for data.exch2
                0028 
                0029 
                0030     Parameters
                0031     ----------
                0032     depth      : 2D array_like
                0033                  depth [m].
                0034     sNx        : int
                0035                  x point in each tile.
                0036     sNy        : int
                0037                  y point in each tile.
                0038     tilemap    : bool
                0039                  True : output tile contourplot,
                0040                  default False.
                0041 
                0042     Returns
                0043     -------
                0044     blank         : list of int
                0045                     empty tiles numbers
                0046     fig(optional) : matplotlib figure
                0047                     tile plot
                0048 
                0049     Usage
                0050     -----
                0051     >>> blank=gen_blanklist(bathy, 5, 5, tilemap=False)
                0052     10,11,12,..,103
                0053     >>> [blank,fig]=gen_blanklist(bathy, 5, 5, tilemap=True)
                0054     10,11,12,..,103
                0055 
                0056     Example
                0057     -------
                0058     >>> eg_blanklist()
                0059     10,11,12,..,103
                0060 
                0061     """
                0062 
                0063     assert depth.ndim==2,'check_stp: depth must be 2D'
                0064 
                0065     [Ny,Nx]=depth.shape
                0066     nPx = Nx//sNx
                0067     nPy = Ny//sNy
                0068     blank = []
                0069     tile_order = np.zeros([nPy, nPx], dtype=int)
                0070     for n in range(0, nPy):
                0071       for m in range(0, nPx):
                0072         tile_sum = np.sum(depth[n*sNy:(n+1)*sNy, m*sNx:(m+1)*sNx])
                0073         tile_order[n, m] = int(n*nPx+m+1)
                0074         if tile_sum == 0:  # the tile with only land cells
                0075           blank.append(tile_order[n, m])
e6feef680a Ivan*0076 
58679b5a83 Esta*0077     assert len(blank)>0,'There are not land tiles'
e6feef680a Ivan*0078 
58679b5a83 Esta*0079     if tilemap:
                0080 
                0081       # plot ocean and blank tiles
                0082       mland = np.copy(depth)
                0083       mland[mland!=fill_value] = 1
                0084       mland[mland==fill_value] = np.nan
                0085 
                0086       [cn_x, cn_y] = np.meshgrid(np.arange(sNx//2, Nx, sNx),
                0087                                 np.arange(sNy//2, Ny, sNy))
                0088       p0 = 0
                0089       fig = plt.figure()
                0090       ax = fig.add_subplot(111)
                0091       ax.pcolormesh(mland,cmap=cmap_lm)
                0092       major_xticks = np.arange(0, Nx+sNx, sNx)
                0093       major_yticks = np.arange(0, Ny+sNy, sNy)
                0094       for a, b, c in zip(cn_x.flat, cn_y.flat, tile_order.flat):
                0095         if c==blank[p0]:
                0096          rect = patches.Rectangle((a-sNx//2, b-sNy//2),
                0097                  sNx, sNy, linewidth=2,edgecolor='r', facecolor='none')
                0098          ax.add_patch(rect)
                0099          rect.set_clip_path(rect)
                0100          p0+=1
                0101         ax.annotate(str(c), (a, b), color='black',
                0102                     ha='center', va='center')
                0103         if p0==len(blank):p0=0
                0104       ax.set_xticks(major_xticks)
                0105       ax.set_yticks(major_yticks)
                0106       ax.set_aspect('equal', adjustable='box')
                0107       ax.set_xlim([0,Nx])
                0108       ax.set_ylim([0,Ny])
                0109       ax.set_xlabel('x')
                0110       ax.set_ylabel('y')
                0111 
                0112       ax.grid()
                0113 
                0114       return blank,fig
                0115 
                0116     else:
                0117 
                0118       return blank
                0119 
                0120 
                0121 def hfac(depth,rF,hFacMin=0.3,hFacMinDr=50,htype='C'):
                0122     """
                0123     Computes hFacC,W,S
                0124 
                0125 
                0126     Parameters
                0127     ----------
                0128     depth      : 2D array_like
                0129                  Depth [m].
                0130     rF         : 1D array_like
                0131                  Depth at the f point.
                0132     hFacMin    : float
                0133                  Min fraction for partial vertical levels.
                0134     hFacMinDr  : float
                0135                  Min depth for partial vertical levels.
                0136     htype      : string
                0137                  Types of hfac: one or more of 'C','S','W', default='C'.
                0138 
                0139     Returns
                0140     -------
                0141     hFacC,W,S : tuple of array_like
                0142                 The hfac arrays requested in htype.
                0143     Usage
                0144     -----
                0145     >>> [hFacC]=mit.hfac(depth,rF,0.3,50,'C')
                0146 
                0147     Example
                0148     -------
                0149     >>> [hFacC]=eg_hfac()
                0150 
                0151     Notes
                0152     -----
                0153 
                0154     The first row and column are filled with zeros
                0155     for the hFacS and hFacW, respectively.
                0156     """
                0157 
                0158     assert depth.ndim==2,'check_stp: depth must be 2D'
                0159     assert rF.ndim==1,'check_stp: rF must be 1D'
                0160 
                0161     assert np.any(depth<0),'check_stp: depth does not have no negative values'
                0162     assert np.all(rF<=0),'check_stp: rF must be negative'
                0163 
                0164     [Ny,Nx] = depth.shape
e6feef680a Ivan*0165     drF = abs(np.diff(rF))
                0166     Nr = drF.size
58679b5a83 Esta*0167 
e6feef680a Ivan*0168     recip_drF = 1/drF
58679b5a83 Esta*0169 
                0170     hFacC = np.zeros([Nr,Ny,Nx])
                0171     hFacW = np.zeros([Nr,Ny,Nx])
                0172     hFacS = np.zeros([Nr,Ny,Nx])
                0173     for k in range(0,Nr):
                0174       hFacMnSz = np.max([hFacMin, np.min([hFacMinDr*recip_drF[k],1])])
                0175 
                0176 #     Calculate lopping factor hFacC :
                0177       hFac_loc = (rF[k]-depth)*recip_drF[k]
                0178       hFac_loc = np.minimum(np.maximum(hFac_loc, 0 ) , 1)
                0179 #     o Impose minimum fraction and/or size (dimensional)
                0180       hFac_loc[hFac_loc < hFacMnSz/2]=np.nan
                0181       hFac_loc[depth >= 0]=np.nan
                0182       hFac_loc = np.maximum(hFac_loc, hFacMnSz)
                0183       hFac_loc[np.isnan(hFac_loc)]=0
                0184       hFacC[k,:,:] = hFac_loc
                0185       hFacW[k,:,1:Nx] = np.minimum(hFacC[k,:,1:Nx],hFacC[k,:,0:Nx-1])
                0186       hFacS[k,1:Ny,:] = np.minimum(hFacC[k,1:Ny,:],hFacC[k,0:Ny-1,:])
                0187 
                0188     hfac_dic = {}
                0189     hfac_dic['C'] = hFacC
                0190     hfac_dic['S'] = hFacS
                0191     hfac_dic['W'] = hFacW
                0192 
                0193     return tuple(hfac_dic[i] for i in htype)
                0194 
                0195 def readbin(fname, ndims, dataprec='float32', machineformat='b'):
                0196     """
                0197     Read meta-data files as written by MITgcm.
                0198 
                0199     Parameters
                0200     ----------
                0201     fname : string
                0202         name of file to read
                0203     ndims : int
                0204         dimension of the file
                0205     dataprec : string
                0206         precision of resulting file ('float32' or 'float64')
                0207     machineformat : string
                0208         endianness ('b' or 'l', default 'b')
                0209 
                0210     Returns
                0211     -------
                0212     arr : array_like
                0213           numpy array of the data read
                0214 
                0215     Usage
                0216     -----
                0217     >>> arr=readbin('bathy.bin',[Y,X])
                0218     """
                0219 
                0220     tp = _typeprefixes[machineformat]
                0221     try:
                0222         tp = tp + _typesuffixes[dataprec]
                0223     except KeyError:
                0224         raise ValueError("dataprec must be 'float32' or 'float64'.")
                0225 
                0226     f = open(fname)
                0227     arr = np.fromfile(f, tp, count=np.prod(ndims)).reshape(ndims)
                0228     f.close()
                0229 
                0230     return arr
                0231 
                0232 def tilecmap(arr, sNx, sNy, tilen=None, sel_zoom=5, fill_value=0):
                0233     """
                0234     Pseudocolor plot of land mask with tiles superimposed, optionally
                0235     showing the values of arr for a single tile.
                0236 
                0237     Parameters
                0238     ----------
                0239     arr        : 2D array_like
                0240                  values to plot, land mask is taken as arr==fill_value
                0241     sNx        : int
                0242                  number of x points in each tile
                0243     sNy        : int
                0244                  number of y points in each tile
                0245     tilen      : int or None
                0246                  plot a specific tile, default None
                0247     sel_zoom   : int
                0248                  zooming range, default 5
                0249     fill_value : float
                0250                  default 0
                0251 
                0252     Returns
                0253     -------
                0254     figure     : matplotlib figure
                0255                  Plot of land mask, tiles and arr values
                0256 
                0257     Usage
                0258     -----
                0259     >>> [fig]=tilecmap(bathy, 5, 5)
                0260     >>> [fig]=tilecmap(bathy, 5, 5, 66, sel_zoom=4)
                0261 
                0262     Example
                0263     -------
                0264     >>> eg_tilemap()
                0265 
                0266 
                0267     """
                0268     #Check dimensions of arr
                0269 
                0270     assert arr.ndim==2,'check_stp: array must be 2D'
                0271 
                0272     [Ny,Nx]=arr.shape
                0273 
                0274     nTx = Nx//sNx
                0275     nTy = Ny//sNy
                0276 
                0277     mland = np.copy(arr)
                0278     mland[mland!=fill_value] = 1
                0279     mland[mland==fill_value] = np.nan
                0280     arr = arr*mland
                0281 
                0282     tile_order = np.zeros([nTy, nTx], dtype=int)
                0283 
                0284     for n in range(0, nTy):
                0285       for m in range(0, nTx):
                0286         tile_order[n, m] = int(n*nTx+m+1)
                0287 
                0288     [cn_x, cn_y] = np.meshgrid(np.arange(sNx//2, Nx, sNx),
                0289                                 np.arange(sNy//2, Ny, sNy))
                0290 
                0291     major_xticks = np.arange(0, Nx+sNx, sNx)
                0292     major_yticks = np.arange(0, Ny+sNy, sNy)
                0293 
                0294 
                0295     fig = plt.figure()
                0296     ax = fig.add_subplot(111)
                0297     ax.pcolormesh(mland,cmap=cmap_lm)
                0298 
                0299     for a, b, c in zip(cn_x.flat, cn_y.flat, tile_order.flat):
                0300         ax.annotate(str(c), (a, b), color='black',
                0301                     ha='center', va='center')
                0302 
                0303     if tilen is not None:
                0304 
                0305      [Tind]=np.argwhere(tile_order==tilen)
                0306 
                0307      #Select position for the zoom inseting
                0308      if (Tind[0]>nTy/2):
                0309        if(Tind[1]>nTx//2):locz=2; locm1=1; locm2=4; cbar_pos=-0.1
                0310        else:locz=1; locm1=2; locm2=3; cbar_pos=1.05
                0311      else:
                0312        if(Tind[1]>nTx//2):locz=1; locm1=3; locm2=4; cbar_pos=1.05
                0313        else:locz=2; locm1=3; locm2=4; cbar_pos=-0.1
                0314 
                0315      #Select colorbar range for zoom
                0316      Tix = Tind[1]*sNx;  Tiy = Tind[0]*sNy
                0317      arrmin = np.nanmin(arr[Tiy:Tiy+sNy,Tix:Tix+sNx])
                0318      arrmax = np.nanmax(arr[Tiy:Tiy+sNy,Tix:Tix+sNx])
                0319 
                0320      ax2 = zoomed_inset_axes(ax, zoom=sel_zoom, loc=locz, borderpad=-1)
                0321      pc=ax2.pcolormesh(arr,vmin=arrmin,vmax=arrmax,cmap=plt.cm.jet)
                0322 
                0323      ax2.set_xlim([major_xticks[Tind[1]],major_xticks[Tind[1]]+sNx])
                0324      ax2.set_ylim([major_yticks[Tind[0]],major_xticks[Tind[0]]+sNy])
                0325      mark_inset(ax, ax2, loc1=locm1, loc2=locm2, fc="none", lw=1.5, ec='0')
                0326      plt.xticks(visible=False)
                0327      plt.yticks(visible=False)
                0328      cax = inset_axes(ax2,
                0329                       width="5%",
                0330                       height="100%",
                0331                       loc="lower left",
                0332                       bbox_to_anchor=(cbar_pos,0,1,1),
                0333                       bbox_transform=ax2.transAxes,
                0334                       borderpad=0,
                0335                       )
                0336      cbar=plt.colorbar(pc,cax=cax, orientation='vertical')
                0337      if cbar_pos<0:
                0338       cax.yaxis.tick_left()
                0339     ax.set_xticks(major_xticks)
                0340     ax.set_yticks(major_yticks)
                0341     ax.set_aspect('equal', adjustable='box')
                0342     ax.set_xlim([0,Nx])
                0343     ax.set_ylim([0,Ny])
                0344     ax.set_xlabel('x')
                0345     ax.set_ylabel('y')
                0346     ax.grid()
                0347 
                0348     return fig
                0349 
                0350 
                0351 
                0352 def writebin(fname, arr, dataprec='float32', machineformat='b'):
                0353     '''Write an array to a bin format for MITgcm
                0354 
                0355     Parameters
                0356     ----------
                0357     fbase : string
                0358             Name of file to write
                0359     arr : array_like
                0360           Numpy array to write
                0361     dataprec : string
                0362                precision of resulting file ('float32' or 'float64')
                0363                ('float32' by default)
                0364     machineformat : string
                0365                     'b' or 'l' for big or little endian
e6feef680a Ivan*0366                     ('b' by default)
58679b5a83 Esta*0367     Usage
                0368     -----
                0369     >>> writebin('data.bin',arr)
                0370     '''
                0371 
                0372     tp = _typeprefixes[machineformat]
                0373     try:
                0374         tp = tp + _typesuffixes[dataprec]
                0375     except KeyError:
                0376         raise ValueError("dataprec must be 'float32' or 'float64'.")
                0377 
                0378     arr.astype(tp).tofile(fname)