### Install Cubedsphere (Development) Source: https://cubedsphere.readthedocs.io/en/latest/installation.html Install the cubedsphere package in editable mode from the cloned repository. ```bash pip install -e . ``` -------------------------------- ### Example: Regridding Dataset Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Example demonstrating how to open an ASCII dataset and then regrid it using the cubedsphere Regridder. ```python >>> import cubedsphere as cs # import cubedsphere >>> outdir = "../run" # specify output directory >>> # open Dataset >>> ds_ascii, grid = cs.open_ascii_dataset(outdir_ascii, iters='all', prefix = ["T","U","V","W"]) >>> # regrid dataset >>> regrid = cs.Regridder(ds_ascii, grid) >>> ds_reg = regrid() ``` -------------------------------- ### Install Cubedsphere (Prepackaged) Source: https://cubedsphere.readthedocs.io/en/latest/installation.html Install the cubedsphere package using conda from the conda-forge channel. ```bash conda install -c conda-forge cubedsphere ``` -------------------------------- ### Minimal Plotting Example Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Creates a basic plot of temperature data and overplots wind vectors. Requires matplotlib. ```python plt.figure() # Select horizontal slice at latest time: data = ds.isel(time=-1,Z=-20) # Plot temperature: data.T.plot() # Overplot winds: cs.overplot_wind(ds, data.U.values, data.V.values) plt.show() ``` -------------------------------- ### Specify Simulation Data Directory Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Defines the output directory for simulation data. Ensure this path is correct for your setup. ```python outdir_ascii = "/Volumes/EXTERN/Simulations/exorad/new_run/paper_runs/WASP-43b/run/" ``` -------------------------------- ### Install Development Dependencies Source: https://cubedsphere.readthedocs.io/en/latest/installation.html Install necessary dependencies for the development version of cubedsphere using conda. ```bash conda install -c conda-forge xesmf esmpy xgcm xmitgcm matplotlib-base xarray ``` -------------------------------- ### Activate Conda Environment Source: https://cubedsphere.readthedocs.io/en/latest/installation.html Activate the 'mitgcm' conda environment before proceeding with installations. ```bash conda activate mitgcm ``` -------------------------------- ### Get Parameter from MITgcm Data File Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/exorad/utils.html Parses a specified MITgcm 'data' file to retrieve the string value of a given keyword. Raises FileNotFoundError if the datafile is not found or KeyError if the keyword is absent. ```python def get_parameter(datafile, keyword): """ Function to parse the MITgcm 'data' file and return the parameter values of the given specific keyword. Parameters ---------- datafile: string Full path to the MITgcm data file. keyword: string Parameter of which the value is required. Returns ---------- value: string The value associated with the given keyword is returned as a string (!). """ if not os.path.isfile(datafile): raise FileNotFoundError("could not find the datafile.") parser = MITgcmDataParser() data = parser.read(datafile) for section in data: for key, val in data[section].items(): if key.lower() == keyword.lower(): return val raise KeyError("Keyword not found") ``` -------------------------------- ### cubedsphere.init_grid_LL() Source: https://cubedsphere.readthedocs.io/en/latest/genindex.html Initializes a Latitude-Longitude grid. ```APIDOC ## Function init_grid_LL ### Description Initializes a Latitude-Longitude grid. ### Module cubedsphere ``` -------------------------------- ### cubedsphere.init_grid_CS() Source: https://cubedsphere.readthedocs.io/en/latest/genindex.html Initializes a Cubed Sphere grid. ```APIDOC ## Function init_grid_CS ### Description Initializes a Cubed Sphere grid. ### Module cubedsphere ``` -------------------------------- ### Regridder Initialization with Parameters Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/regrid.html Builds the regridder, creating output grid and weight files. This constructor handles different input types ('cs' or 'll') and regridding configurations like concat_mode and method. It prints the time taken and a warning if the chosen method might not conserve fluxes or return zeros on borders. ```python t = time.time() self._ds = ds self._input_type = input_type if self._input_type not in ["cs", "ll"]: raise NotImplementedError( f"wrong input_type={self._input_type}. You need to either use input_type='cs' or input_type='ll'.") if self._input_type == "cs": self._ds_grid_in = cs_grid self.grid = self._build_output_grid(d_lon, d_lat) self._concat_mode = concat_mode else: self.grid = cs_grid self._ds_grid_in = self._ds self._concat_mode = False self._method = method if self._concat_mode: self._build_regridder_concat(filename, **kwargs) else: self._build_regridder_faces(filename, **kwargs) print(f"time needed to build regridder: {time.time() - t}") print(f"Regridder will use {self._method} method") if self._method not in ["patch", "conservative"]: print("Caution: The regridding method that you chose might not conserve fluxes") if self._method not in ["conservative", "nearest_s2d"]: print( "Caution: The regridding method that you chose might return 0's on borders, double check by plotting the dataset") ``` -------------------------------- ### ExoRad Preliminary Postprocessing Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/exorad/utils.html Applies preliminary postprocessing to an ExoRad dataset, including adding metadata by parsing a 'data' file, converting winds and temperature, and optionally converting pressure units to bar and time units to days. ```python def exorad_postprocessing(ds, outdir=None, datafile=None, convert_to_bar=True, convert_to_days=True): """ Preliminaray postprocessing on exorad dataset. This function converts the vertical windspeed from Pa into meters and saves attributes to the dataset. Parameters ---------- ds: Dataset dataset to be extended outdir: string directory in which to find the data file (following the convention f'{outdir}/data') datafile: string alternatively specify datafile directly convert_to_bar: (Optional) bool convert vertical pressure dimension to bar convert_to_days: (Optional) bool convert time dimension to days Returns ---------- ds: Dataset to be returned """ assert outdir is not None or datafile is not None, "please specify a datafile or a folder where we can find a datafile" if outdir is not None: datafile = f'{outdir}/data' # Add metadata radius = float(get_parameter(datafile, 'rSphere')) # planet radius in m attrs = {"p_ref": float(get_parameter(datafile, 'Ro_SeaLevel')), # bottom layer pressure in pascal "cp": float(get_parameter(datafile, 'atm_Cp')), # heat capacity at constant pressure "R": float(get_parameter(datafile, 'atm_Rd')), # specific gas constant "g": float(get_parameter(datafile, 'gravity')), # surface gravity in m/s^2 "dt": int(get_parameter(datafile, 'deltaT')), # time step size in s "radius": radius, } ds.attrs.update(attrs) # Convert Temperature and winds if c.T in ds: ds = convert_winds_and_T(ds, c.T, c.W) if c.Ttave in ds: ds = convert_winds_and_T(ds, c.Ttave, c.wVeltave) # Convert pressure from SI to bar if convert_to_bar: for dim in {c.Z, c.Z_l, c.Z_p1, c.Z_u}: if dim in ds.dims: ds = convert_vertical_to_bar(ds, dim) ds.attrs.update({'p_ref': ds.p_ref/1e5}) # Convert time to days if convert_to_days: ds[c.time] = ds.iter * ds.attrs["dt"] / (3600 * 24) ``` -------------------------------- ### init_grid_CS Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/grid.html Initializes an xgcm grid for a cubedsphere dataset. This is useful for raw datasets that need grid information to be loaded from a directory or provided directly. ```APIDOC ## init_grid_CS ### Description Initializes an xgcm grid for a cubedsphere dataset. Useful for raw datasets. ### Parameters - **grid_dir** (string): Direction where the grid can be found (optional). - **ds** (xarray DataSet): Dataset that contains the grid (optional). - **kwargs**: Additional keyword arguments to pass to xgcm.Grid. ### Returns - **grid** (xgcm.grid): The initialized xgcm grid object. ``` -------------------------------- ### Plotting Cubed Sphere Data Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/plot.html Renders cubed sphere data onto a 3D plot or a 2D map projection. Handles data tiling, color normalization, and axis setup. Use `mapit=-1` for 3D sphere plotting and `mapit=1` for map projection. ```python ny, nx = data.shape # determine range for color range cax = [data.min(), data.max()] if cax[1] - cax[0] == 0: cax = [cax[0] - 1, cax[1] + 1] if vmin != None: cax[0] = vmin if vmax != None: cax[1] = vmax norm = kwargs.pop('norm', None) if norm is None: norm = mcolors.Normalize(cax[0], cax[1]) if mapit == -1: # set up 3D plot if len(fig.axes) > 0: # if present, remove and replace the last axis of fig geom = fig.axes[-1].get_geometry() plt.delaxes(fig.axes[-1]) else: # otherwise use full figure geom = ((1, 1, 1)) ax = kwargs.pop("ax", fig.add_subplot(geom[0], geom[1], geom[2], projection='3d', facecolor='None')) # define color range tmp = data - data.min() N = tmp / tmp.max() # use this colormap colmap = cm.jet colmap.set_bad('w', 1.0) mycolmap = colmap(N) # cm.jet(N) ph = np.array([]) jc = x.shape[0] // 2 xxf = np.empty((jc + 1, jc + 1, 4)) yyf = xxf ffld = np.empty((jc, jc, 4)) xff = [] yff = [] fldf = [] for k in range(0, 6): ix = np.arange(0, ny) + k * ny xff.append(x[0:ny, ix]) yff.append(y[0:ny, ix]) fldf.append(data[0:ny, ix]) # find the missing corners by interpolation (one in the North Atlantic) xfodd = (xff[0][-1, 0] + xff[2][-1, 0] + xff[4][-1, 0]) / 3. yfodd = (yff[0][-1, 0] + yff[2][-1, 0] + yff[4][-1, 0]) / 3. # and one south of Australia xfeven = (xff[1][0, -1] + xff[3][0, -1] + xff[5][0, -1]) / 3. yfeven = (yff[1][0, -1] + yff[3][0, -1] + yff[5][0, -1]) / 3. # loop over tiles for k in range(0, 6): kodd = 2 * (k // 2) kodd2 = kodd if kodd == 4: kodd2 = kodd - 6 keven = 2 * (k // 2) keven2 = keven if keven == 4: keven2 = keven - 6 fld = fldf[k] if np.mod(k + 1, 2): xf = np.vstack([np.column_stack([xff[k], xff[1 + kodd][:, 0]]), np.flipud(np.append(xff[2 + kodd2][:, 0], xfodd))]) yf = np.vstack([np.column_stack([yff[k], yff[1 + kodd][:, 0]]), np.flipud(np.append(yff[2 + kodd2][:, 0], yfodd))]) else: xf = np.column_stack([np.vstack([xff[k], xff[2 + keven2][0, :]]), np.flipud(np.append(xff[3 + keven2][0, :], xfeven))]) yf = np.column_stack([np.vstack([yff[k], yff[2 + keven2][0, :]]), np.flipud(np.append(yff[3 + keven2][0, :], yfeven))]) if mapit == -1: ix = np.arange(0, ny) + k * ny # no projection at all (projection argument is 'sphere'), # just convert to cartesian coordinates and plot a 3D sphere deg2rad = np.pi / 180. xcart, ycart, zcart = _sph2cart(xf * deg2rad, yf * deg2rad) ax.plot_surface(xcart, ycart, zcart, rstride=1, cstride=1, facecolors=mycolmap[0:ny, ix], linewidth=2, shade=False) ph = np.append(ph, ax) else: # divide all faces into 4 because potential problems arise at # the centers for kf in range(0, 4): if kf == 0: i0, i1, j0, j1 = 0, jc + 1, 0, jc + 1 elif kf == 1: i0, i1, j0, j1 = 0, jc + 1, jc, 2 * jc + 1 elif kf == 2: i0, i1, j0, j1 = jc, 2 * jc + 1, 0, jc + 1 elif kf == 3: i0, i1, j0, j1 = jc, 2 * jc + 1, jc, 2 * jc + 1 xx = xf[i0:i1, j0:j1] yy = yf[i0:i1, j0:j1] ff = fld[i0:i1 - 1, j0:j1 - 1] if np.median(xx) < 0: xx = np.where(xx >= 180, xx - 360., xx) else: xx = np.where(xx <= -180, xx + 360., xx) # if provided use projection if mapit == 1: xx, yy = mp(xx, yy) # now finally plot 4x6 tiles ph = np.append(ph, ax.pcolormesh(xx, yy, ff, norm=norm, **kwargs)) if mapit == -1: # ax.axis('image') ax.set_axis_off() # ax.set_visible=False # add a reasonable colormap m = cm.ScalarMappable(cmap=colmap) m.set_array(data) plt.colorbar(m) return ph ``` -------------------------------- ### Initialize LatLon Grid Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Initializes an xgcm grid for a latlon dataset, useful for regridded datasets. ```APIDOC ## cubedsphere.init_grid_LL ### Description Init a xgcm grid for a latlon dataset. Useful for regridded datasets ### Parameters - **grid_dir** (string) - direction where the grid can be found (optional) - **ds** (xarray DataSet) - dataset that contains the grid (optional) - **kwargs** - ### Returns - **grid** (xgcm.grid) - xgcm grid ``` -------------------------------- ### init_grid_LL Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/grid.html Initializes an xgcm grid for a latlon dataset. This is useful for regridded datasets where the grid information is either provided directly or can be found in a specified directory. ```APIDOC ## init_grid_LL ### Description Initializes an xgcm grid for a latlon dataset. Useful for regridded datasets. ### Parameters - **grid_dir** (string): Direction where the grid can be found (optional). - **ds** (xarray DataSet): Dataset that contains the grid (optional). - **kwargs**: Additional keyword arguments to pass to xgcm.Grid. ### Returns - **grid** (xgcm.grid): The initialized xgcm grid object. ``` -------------------------------- ### Initialize Lat/Lon xGCM Grid Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Initialize an xGCM grid for a lat/lon dataset. Useful for regridded datasets. ```python cubedsphere.init_grid_LL(_ds =None_, _grid_dir =None_, _** kwargs_) ``` -------------------------------- ### Regridder Initialization and Configuration Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/regrid.html This section details how the Regridder class is initialized and configured based on input grid types (cubed sphere or latlon) and regridding methods. It outlines the logic for selecting appropriate regridding strategies and handling potential errors or fallbacks. ```APIDOC ## Regridder Class Initialization ### Description Initializes the Regridder object, setting up the input and output grids, and determining the regridding method. It handles different input types like 'cs' (cubed sphere) and 'll' (latitude-longitude) and configures the regridder based on these types and specified methods. ### Method `__init__(self, ds_grid_in, grid, filename, method, input_type, concat_mode, **kwargs)` ### Parameters - **ds_grid_in** (xarray.Dataset) - Input dataset containing the grid information. - **grid** (xarray.Dataset or xe.util.Grid) - Output grid definition. - **filename** (string) - Base filename for saving regridding weights. - **method** (string) - Regridding method to use (e.g., 'conservative', 'nearest_s2d'). - **input_type** (string) - Type of the input grid ('cs' or 'll'). - **concat_mode** (bool) - Whether to use concatenation mode for regridding. - **kwargs** - Additional keyword arguments passed to `xe.Regridder`. ### Internal Logic - Handles different `input_type` values ('cs' or 'll'). - For `input_type='cs'`, it processes grid information for each of the 6 faces. - For `input_type='ll'`, it expects specific latitude and longitude dimensions. - Selects and configures `xe.Regridder` instances based on the chosen `method` and grid geometry. - Includes fallbacks to 'conservative' or 'nearest_s2d' methods if the chosen method is incompatible with the grid or `concat_mode`. - Raises `NotImplementedError` or `KeyError` for unsupported configurations or missing grid information. ``` -------------------------------- ### Open ASCII Dataset Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Use this wrapper to open simulation outputs from standard MITgcm ASCII files. Ensure `useSingleCpuIO=.TRUE.` is set in MITgcm for ASCII files. ```python cubedsphere.open_ascii_dataset(_outdir_ , _return_grid =True_, _** kwargs_) ``` -------------------------------- ### cubedsphere.Regridder.__init__() Source: https://cubedsphere.readthedocs.io/en/latest/genindex.html Initializes a new instance of the Regridder class. ```APIDOC ## Method __init__ ### Description Initializes a new instance of the Regridder class. ### Class cubedsphere.Regridder ``` -------------------------------- ### Initialize CubedSphere Grid Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Initializes an xgcm grid for a CubedSphere dataset, useful for raw datasets. ```APIDOC ## cubedsphere.init_grid_CS ### Description Init a xgcm grid for a cubedsphere dataset. Useful for raw datasets. ### Parameters - **grid_dir** (string) - direction where the grid can be found (optional) - **ds** (xarray DataSet) - dataset that contains the grid (optional) - **kwargs** - ### Returns - **grid** (xgcm.grid) - xgcm grid ``` -------------------------------- ### Initialize Cubed Sphere xGCM Grid Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Initialize an xGCM grid for a cubedsphere dataset. Useful for raw datasets. ```python cubedsphere.init_grid_CS(_ds =None_, _grid_dir =None_, _** kwargs_) ``` -------------------------------- ### Build Global Lat/Lon Output Grid Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/regrid.html Creates a global longitude-latitude (ll) grid with specified longitude and latitude step sizes. This is used as an output grid when the input type is 'cs'. ```python grid = xe.util.grid_global(d_lon, d_lat) grid_LL = {'lat': grid["lat"][:, 0].values, 'lon': grid["lon"][0, :].values, 'lat_b': grid["lat_b"][:, 0].values, 'lon_b': grid["lon_b"][0, :].values} return grid_LL ``` -------------------------------- ### Load and Regrid Data Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Opens a dataset using xmitgcm and performs conservative regridding. Optionally applies exorad postprocessing. ```python # open Dataset using xmitgcm (see docs for xmitgcm.open_mdsdataset for more details) ds_ascii, grid = cs.open_ascii_dataset(outdir_ascii, iters=[41472000], prefix = ["T","U","V","W"]) # regrid dataset regrid = cs.Regridder(ds_ascii, grid) ds = regrid() # (optional) converts wind, temperature and stuff ds = cs.exorad_postprocessing(ds, outdir=outdir_ascii) ``` -------------------------------- ### Open User-Specific Dataset Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Opens a dataset including user-specific variables like bolometric planetary flux using `cs.open_ascii_dataset` and `extra_variables`. ```python # open Dataset using xmitgcm (see docs for xmitgcm.open_mdsdataset for more details) ds_ascii, grid = cs.open_ascii_dataset(outdir_ascii, iters=[41472000], prefix = ["EXOBFPla"], extra_variables=extra_variables) ``` -------------------------------- ### Open ASCII Dataset Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Opens simulation outputs from standard MITgcm outputs. It can optionally return a grid generated with xmitgcm.get_grid_from_input. ```APIDOC ## cubedsphere.open_ascii_dataset ### Description Wrapper that opens simulation outputs from standard mitgcm outputs. ### Parameters - **outdir** (string) - Output directory - **return_grid** (Boolean) - Return a grid generated with xmitgcm.get_grid_from_input - **kwargs** - everything else that is passed to xmitgcm ### Returns - **ds** (xarray Dataset) - Dataset of simulation output - **grid** (xarray Dataset) - Only if return_grid is True. Grid generated with xmitgcm.get_grid_from_input. ### Warning You need to use `useSingleCpuIO=.TRUE.` if you want to use ascii files (the default MITgcm output) ``` -------------------------------- ### open_ascii_dataset Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/utils.html Wrapper that opens simulation outputs from standard mitgcm outputs. ```APIDOC ## open_ascii_dataset ### Description Wrapper that opens simulation outputs from standard mitgcm outputs. ### Parameters #### Path Parameters - **outdir** (string) - Required - Output directory #### Query Parameters - **return_grid** (Boolean) - Optional - Return a grid generated with xmitgcm.get_grid_from_input. Defaults to True. - **kwargs** - Optional - everything else that is passed to xmitgcm ### Returns - **ds** (xarray Dataset) - Dataset of simulation output - **grid** (xarray Dataset) - Only if return_grid is True. Grid generated with xmitgcm.get_grid_from_input. ``` -------------------------------- ### cubedsphere.exorad.exorad_postprocessing() Source: https://cubedsphere.readthedocs.io/en/latest/genindex.html Performs post-processing operations for exorad. ```APIDOC ## Function exorad_postprocessing ### Description Performs post-processing operations for exorad. ### Module cubedsphere.exorad ``` -------------------------------- ### Initialize Regridder Class Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/regrid.html Initializes the Regridder class, which wraps the xESMF regridder for cubedsphere geometry. This step creates output grid and weight files. It supports 'cs' or 'll' input types and allows specifying regridding method and resolution. ```python import cubedsphere as cs # import cubedsphere outdir = "../run" # specify output directory # open Dataset ds_ascii, grid = cs.open_ascii_dataset(outdir_ascii, iters='all', prefix = ["T","U","V","W"]) # regrid dataset regrid = cs.Regridder(ds_ascii, grid) ds_reg = regrid() ``` -------------------------------- ### exorad_postprocessing Source: https://cubedsphere.readthedocs.io/en/latest/exorad.html Performs preliminary post-processing on exorad datasets, including unit conversions for wind speed and time dimensions. ```APIDOC ## exorad_postprocessing ### Description Preliminary postprocessing on exorad dataset. This function converts the vertical windspeed from Pa into meters and saves attributes to the dataset. ### Parameters #### Path Parameters - **ds** (Dataset) - Required - dataset to be extended - **outdir** (string) - Optional - directory in which to find the data file (following the convention f’{outdir}/data’) - **datafile** (string) - Optional - alternatively specify datafile directly - **convert_to_bar** (bool) - Optional - convert vertical pressure dimension to bar - **convert_to_days** (bool) - Optional - convert time dimension to days ### Returns - **ds** (Dataset) - Dataset to be returned ``` -------------------------------- ### cubedsphere.open_ascii_dataset() Source: https://cubedsphere.readthedocs.io/en/latest/genindex.html Opens a dataset from an ASCII file. ```APIDOC ## Function open_ascii_dataset ### Description Opens a dataset from an ASCII file. ### Module cubedsphere ``` -------------------------------- ### open_mnc_dataset Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/utils.html Wrapper that opens simulation outputs from mnc outputs. This function is not tested and may not work as expected. ```APIDOC ## open_mnc_dataset ### Description Wrapper that opens simulation outputs from mnc outputs. ### Parameters #### Path Parameters - **outdir** (string) - Required - Output directory - **iternumber** (integer) - Required - iteration number of output file #### Query Parameters - **fname_list** (list) - Optional - List of NetCDF file prefixes to read (no need to specify grid files here). Defaults to ["state"]. ### Returns - **ds** (xarray Dataset) - Dataset of simulation output ``` -------------------------------- ### cubedsphere.open_mnc_dataset() Source: https://cubedsphere.readthedocs.io/en/latest/genindex.html Opens a dataset from an MNC file. ```APIDOC ## Function open_mnc_dataset ### Description Opens a dataset from an MNC file. ### Module cubedsphere ``` -------------------------------- ### Create Conda Environment Source: https://cubedsphere.readthedocs.io/en/latest/installation.html Use this command to create a new conda environment named 'mitgcm'. ```bash conda create -n mitgcm ``` -------------------------------- ### Initialize Cubed Sphere Regridder Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Class to wrap the xESMF regridder for cubed sphere geometry. It creates output grid and weight files for regridding. ```python cubedsphere.Regridder(_ds_ , _cs_grid_ , _input_type ='cs'_, _d_lon =5_, _d_lat =4_, _concat_mode =False_, _filename ='weights'_, _method ='conservative'_, _** kwargs_) ``` -------------------------------- ### Regrid and Post-process Dataset Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Initializes a Regridder object, applies it to a dataset, and then performs optional post-processing. Ensure the dataset and grid objects are properly defined before use. ```python # regrid dataset regrid = cs.Regridder(ds_ascii, grid) ds = regrid() # (optional) converts wind, temperature and stuff ds = cs.exorad_postprocessing(ds, outdir=outdir_ascii) ``` -------------------------------- ### Open ASCII Simulation Dataset Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/utils.html Wrapper function to open simulation outputs from standard MITgcm ASCII NetCDF format. It uses xmitgcm.open_mdsdataset and can optionally return a grid generated with xmitgcm.get_grid_from_input. Handles potential errors during vertical coordinate swapping. ```python def open_ascii_dataset(outdir, return_grid=True, **kwargs): """ Wrapper that opens simulation outputs from standard mitgcm outputs. Parameters ---------- outdir: string Output directory return_grid: Boolean Return a grid generated with xmitgcm.get_grid_from_input **kwargs everything else that is passed to xmitgcm Returns ---------- ds: xarray Dataset Dataset of simulation output grid: xarray Dataset Only if return_grid is True Grid generated with xmitgcm.get_grid_from_input. """ extra_variables = kwargs.pop("extra_variables", {}) extra_variables.update(c.extra_exorad_variables) ds = xmitgcm.open_mdsdataset(data_dir=outdir, grid_vars_to_coords=True, geometry="cs", extra_variables=extra_variables, **kwargs).load() try: ds = _swap_vertical_coords(ds) except (ValueError, KeyError): print("vertical dimensions could not be swapped. Keeping logical dimensions.") if return_grid: # Note: This needs https://github.com/MITGCM/xmitgcm/pull/246 to work em = xmitgcm.utils.get_extra_metadata(domain='cs', nx=ds["XC"].shape[0]) grid = xmitgcm.utils.get_grid_from_input( f'{outdir}/grid_cs32.face.bin', geometry='cs', extra_metadata=em, outer=True).load() ``` -------------------------------- ### Clone Cubedsphere Repository Source: https://cubedsphere.readthedocs.io/en/latest/installation.html Clone the cubedsphere repository from GitHub and navigate into the cloned directory. ```bash git clone https://github.com/AaronDavidSchneider/cubedsphere.git cd cubedsphere ``` -------------------------------- ### Building Output Grid Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/regrid.html This internal method constructs a global latitude-longitude grid, often used as the output grid for regridding operations from a cubed sphere grid. ```APIDOC ## Build Output Grid ### Description Constructs a global latitude-longitude (ll) grid with specified longitude and latitude step sizes. This is commonly used as the target grid when regridding from a cubed sphere input. ### Method `_build_output_grid(self, d_lon, d_lat)` ### Parameters - **d_lon** (int): The desired step size for longitude in degrees. - **d_lat** (int): The desired step size for latitude in degrees. ### Returns - **grid_LL** (dict): A dictionary containing the latitude, longitude, and boundary latitude/longitude arrays for the generated global grid. ``` -------------------------------- ### Define Extra Variables for User-Specific Files Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Defines a dictionary for extra variables, such as bolometric planetary flux, to be loaded from user-specific simulation outputs. ```python # Note: Not needed, since already part of cubedsphere package, this is shown only to demonstrate how it works extra_variables = dict(EXOBFPla=dict(dims=['k_p1', 'j', 'i'], attrs=dict(standard_name='EXOBFPla', long_name='Bolometric Planetary Flux', units='W/m2'))) ``` -------------------------------- ### Initialize Lat/Lon xgcm Grid Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/grid.html Use this function to initialize an xgcm grid for a lat/lon dataset, typically used for regridded data. It supports loading grid files from a directory or using an existing xarray DataSet. The function defines standard latitude, longitude, time, and Z coordinates. ```python import numpy as np import os import xarray as xr import xgcm import cubedsphere as cs import cubedsphere.const as c def init_grid_LL(ds=None, grid_dir=None, **kwargs): """ Init a xgcm grid for a latlon dataset. Useful for regridded datasets Parameters ---------- grid_dir: string direction where the grid can be found (optional) ds: xarray DataSet dataset that contains the grid (optional) Returns ---------- grid: xgcm.grid xgcm grid """ if grid_dir is not None: grid_files = os.path.join(grid_dir, "grid.t{:03d}.nc") grid_list = [xr.open_dataset(grid_files.format(i)) for i in range(1, 7)] grid_nc = xr.concat(grid_list, dim=range(6)) elif ds is not None: grid_nc = ds else: raise TypeError("you need to specify ds or grid_dir") coords = {c.lon: {'center': c.lon}, c.lat: {'center': c.lat}, c.time: {'center': c.time}, c.Z: {'center': c.Z, 'right': c.Z_u, 'left': c.Z_l, 'outer': c.Z_p1}} boundary = {c.i: None, c.j: None, c.time: 'extrapolate', c.Z: 'extrapolate'} grid = xgcm.Grid(grid_nc, periodic=[c.i, c.j], coords=coords, boundary=boundary, **kwargs) return grid ``` -------------------------------- ### Initialize Cubed-Sphere xgcm Grid Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/grid.html Use this function to initialize an xgcm grid for a cubed-sphere dataset. It can load grid files from a directory or use an existing xarray DataSet. Ensure the dataset contains the necessary grid information, including face connections and coordinate definitions. ```python import numpy as np import os import xarray as xr import xgcm import cubedsphere as cs import cubedsphere.const as c def init_grid_CS(ds=None, grid_dir=None, **kwargs): """ Init a xgcm grid for a cubedsphere dataset. Useful for raw datasets. Parameters ---------- grid_dir: string direction where the grid can be found (optional) ds: xarray DataSet dataset that contains the grid (optional) Returns ---------- grid: xgcm.grid xgcm grid """ if grid_dir is not None: grid_files = os.path.join(grid_dir, "grid.t{:03d}.nc") grid_list = [xr.open_dataset(grid_files.format(i)) for i in range(1, 7)] grid_nc = xr.concat(grid_list, dim=range(6)) grid_nc = cs.utils._swap_vertical_coords(grid_nc) elif ds is not None: grid_nc = ds else: raise TypeError("you need to specify ds or grid_dir") face_connections = {c.FACEDIM: {0: {c.i: ((4, c.j, False), (1, c.i, False)), c.j: ((5, c.j, False), (2, c.i, False))}, 1: {c.i: ((0, c.i, False), (3, c.j, False)), c.j: ((5, c.i, False), (2, c.j, False))}, 2: {c.i: ((0, c.j, False), (3, c.i, False)), c.j: ((1, c.j, False), (4, c.i, False))}, 3: {c.i: ((2, c.i, False), (5, c.j, False)), c.j: ((1, c.i, False), (4, c.j, False))}, 4: {c.i: ((2, c.j, False), (5, c.i, False)), c.j: ((3, c.j, False), (0, c.i, False))}, 5: {c.i: ((4, c.i, False), (1, c.j, False)), c.j: ((3, c.i, False), (0, c.j, False))}}} if np.all(grid_nc[c.i].shape == grid_nc[c.i_g].shape) and grid_nc[c.i_g].attrs.get("c_grid_axis_shift") == -0.5: # We might have left values here coords = {c.i: {'center': c.i, 'left': c.i_g}, c.j: {'center': c.j, 'left': c.j_g}, c.time: {'center': c.time}, c.Z: {'center': c.Z, 'right': c.Z_u, 'left': c.Z_l, 'outer': c.Z_p1}} elif np.all(grid_nc[c.i].shape == grid_nc[c.i_g].shape) and grid_nc[c.i_g].attrs.get("c_grid_axis_shift") == +0.5: # We might have left values here coords = {c.i: {'center': c.i, 'right': c.i_g}, c.j: {'center': c.j, 'right': c.j_g}, c.time: {'center': c.time}, c.Z: {'center': c.Z, 'right': c.Z_u, 'left': c.Z_l, 'outer': c.Z_p1}} else: coords = {c.i: {'center': c.i, 'outer': c.i_g}, c.j: {'center': c.j, 'outer': c.j_g}, c.time: {'center': c.time}, c.Z: {'center': c.Z, 'right': c.Z_u, 'left': c.Z_l, 'outer': c.Z_p1}} grid_nc[c.drW] = grid_nc[c.HFacW] * grid_nc[c.drF] # vertical cell size at u point grid_nc[c.drS] = grid_nc[c.HFacS] * grid_nc[c.drF] # vertical cell size at v point grid_nc[c.drC] = grid_nc[c.HFacC] * grid_nc[c.drF] # vertical cell size at tracer point metrics = { (c.i,): [c.dxC, c.dxG], # X distances (c.j,): [c.dyC, c.dyG], # Y distances (c.Z,): [c.drW, c.drS, c.drC], # Z distances (c.i, c.j): [c.rA, c.rAz, c.rAs, c.rAw] # Areas } boundary = {c.i: None, c.j: None, c.time: 'extrapolate', c.Z: 'extrapolate'} grid = xgcm.Grid(grid_nc, face_connections=face_connections, coords=coords, periodic=[c.i, c.j], metrics=metrics, boundary=boundary, **kwargs) return grid ``` -------------------------------- ### Initialize Cubed Sphere Grid Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/regrid.html Initializes the cubed sphere grid for interpolation. This is used when the input type is 'cs'. ```python grid = init_grid_CS(ds=self._ds) ``` -------------------------------- ### Open MNC Dataset Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Wrapper to open simulation outputs from mnc (NetCDF) files. This function is not tested and may be deprecated. ```python cubedsphere.open_mnc_dataset(_outdir_ , _iternumber_ , _fname_list =['state']_) ``` -------------------------------- ### Open MNC Simulation Dataset Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/utils.html Wrapper function to open simulation outputs from MNC (Model NetCDF) format. It reads specified NetCDF files, concatenates them, merges with grid files, renames coordinates, and swaps vertical coordinates. Note: This function is not tested and may not work as expected. ```python def open_mnc_dataset(outdir, iternumber, fname_list=["state"]): """ Wrapper that opens simulation outputs from mnc outputs. NOT TESTED. Parameters ---------- outdir: string Output directory iternumber: integer iteration number of output file fname_list: list List of NetCDF file prefixes to read (no need to specify grid files here) Returns ---------- ds: xarray Dataset Dataset of simulation output """ # read_parameters(outdir) print("WARNING: This function is not being tested and likely does not work.") dataset_list = [] for fname in fname_list: dataset = [xr.open_dataset("{}/{}.{:010d}.t{:03d}.nc".format(outdir, fname, iternumber, i)) for i in range(1, 7)] dataset_list.append(xr.concat(dataset, dim=range(6))) dataset_list = [ds_i.reset_coords(["XC", "YC"]) if "XC" in ds_i.coords else ds_i for ds_i in dataset_list] dataset_list = [ds_i.reset_coords(["iter"]) if "iter" in ds_i.coords else ds_i for ds_i in dataset_list] grid = [xr.open_dataset("{}/{}.t{:03d}.nc".format(outdir, "grid", i)) for i in range(1, 7)] dataset_list.append(xr.concat(grid, dim=range(6))) ds = xr.merge(dataset_list, compat="override") _rename_dict = {'XC': c.lon, 'XG': c.lon_b, 'YC': c.lat, 'YG': c.lat_b, 'X': c.i, 'Xp1': c.i_g, 'Y': c.j, 'Yp1': c.j_g, 'AngleCS': c.AngleCS, 'AngleSN': c.AngleSN, 'concat_dim': c.FACEDIM, 'HFacC': c.HFacC, 'HFacW': c.HFacW, 'HFacS': c.HFacS, 'RC': c.Z, 'RF': c.Z_p1, 'RU': c.Z_u, 'RL': c.Z_l, 'Z': c.k, 'Zu': c.k_u, 'Zl': c.k_l, 'Zp1': c.k_p1, 'T': c.time, 'drF': c.drF, 'drC': c.drC, 'dxC': c.dxC, 'dxG': c.dxG, 'dyC': c.dyC, 'dyG': c.dyG, 'dxF': c.dxF, 'dyU': c.dyU, 'dxV': c.dxV, 'dyF': c.dyF, 'rA': c.rA, 'rAz': c.rAz, 'rAs': c.rAs, 'rAw': c.rAw, 'Temp': c.T } ds = ds.rename(_rename_dict) ds = _swap_vertical_coords(ds) return ds ``` -------------------------------- ### Open MNC Dataset Source: https://cubedsphere.readthedocs.io/en/latest/usage.html Opens simulation outputs from MNC outputs. This function is not tested. ```APIDOC ## cubedsphere.open_mnc_dataset ### Description Wrapper that opens simulation outputs from mnc outputs. NOT TESTED. ### Parameters - **outdir** (string) - Output directory - **iternumber** (integer) - iteration number of output file - **fname_list** (list) - List of NetCDF file prefixes to read (no need to specify grid files here) ### Returns - **ds** (xarray Dataset) - Dataset of simulation output ``` -------------------------------- ### Import Packages Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Imports necessary libraries including numpy, cubedsphere, matplotlib, and optionally cartopy for plotting. ```python import numpy as np import cubedsphere as cs import matplotlib.pyplot as plt import matplotlib.colors as mcolors import cartopy.crs as ccrs # optional, only needed for nicer projections ``` -------------------------------- ### Calculate Global Average Temperature Profile Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Calculates and plots the globally averaged temperature as a function of pressure. Uses log-log scale. ```python plt.figure() T_global = (ds.T.isel(time=-1)*ds.area_c).sum(dim=['lon','lat'])/ds.area_c.sum(dim=['lon','lat']) plt.loglog(T_global, ds.Z) plt.ylim(700,1e-4) plt.title('globally averaged temperature pressure profile') plt.ylabel('p / bar') plt.xlabel('T / K') plt.show() ``` -------------------------------- ### Create Face Visualization Data Source: https://cubedsphere.readthedocs.io/en/latest/_modules/cubedsphere/regrid.html Creates a visualization DataArray for the faces of the cubed sphere grid. This is specific to 'cs' input type. ```python face_vis_data = np.zeros((len(self._ds[c.FACEDIM]), len(self._ds[c.i]), len(self._ds[c.j]))) for i in self._ds[c.FACEDIM]: face_vis_data[i] = i self._ds["face_vis"] = xr.DataArray(face_vis_data, coords=[self._ds[c.FACEDIM], self._ds[c.i], self._ds[c.j]], dims=[c.FACEDIM, c.i, c.j]) ``` -------------------------------- ### Update xmitgcm from GitHub Source: https://cubedsphere.readthedocs.io/en/latest/installation.html Update the xmitgcm package to the latest version directly from its GitHub repository using pip. ```bash pip install git+https://github.com/MITgcm/xmitgcm.git ``` -------------------------------- ### Plotting with Cartopy Source: https://cubedsphere.readthedocs.io/en/latest/notebooks/example.html Generates a plot using Cartopy for a more sophisticated map projection. Requires cartopy. ```python plt.figure() ax = plt.axes(projection=ccrs.Robinson()) # Plot temperature: data.T.plot(transform = ccrs.PlateCarree(), ax=ax) # Overplot winds: cs.overplot_wind(ds, data.U.values, data.V.values, ax=ax, transform=ccrs.PlateCarree(), stepsize=2) ax.set_title('time: {:.0f} d, Z={:.1e} bar'.format(data.time.values,data.Z.values)) plt.show() ```