xgrads package

xgrads.core module

Created on 2020.03.02

@author: MiniUFO Copyright 2018. All rights reserved. Use is subject to license terms.

class xgrads.core.Coordinate(name, samples)

Bases: object

Discrete sampled coordinate

This is a simple wrapper for np.array for a coordinate.

Attributes

isLinear: bool

Steps are even or uneven

isIncre: int

Is increasing or decreasing

name: str

The name of the coordinate

samples: str

Discretized coordinate samples

delSamples: str

Finite difference between samples

isPeriodic(period)
length()
class xgrads.core.CtlDescriptor(encoding='GBK', **kwargs)

Bases: object

A class for a ctl file

This class represents a descriptor file like the .ctl file for GrADS. It generally includes a multi-dimensional dataset on the Earth.

Attributes

dsetPath: str

dataset file

descPath: str

descriptor file

indxPath: str

index file (for GRIB file)

stnmPath: str

station map file (for station file)

pdef: PDEF

Projection-definition

tdef: Coordinate

time coordinate definition

zdef: Coordinate

z-coordinate definition

ydef: Coordinate

y-coordinate definition

xdef: Coordinate

x-coordinate definition

vdef: list of CtlVar

Variables definition

edef: list of str

Ensemble definition

comments: list of str

list of global string comments

zrev: bool

z-dimension reverse (i.e., from north to south)

yrev: bool

y-dimension reverse (i.e., from upper to lower levels)

hasData: bool

whether the corresponding binary data file exist

vcount: int

variable count

dtype: numpy.dtype

data type

periodicX: bool

whether xdef is periodic

cal365Days: bool

whether the calendar is always 365 days (no leap year)

template: bool

whether it is a template for multiple binary files

sequential: bool

whether it is a sequential file (Fortran style)

byteOrder: str

byte order, [‘little’, ‘big’] for little-endian or big-endian

storage: str

storage type, ‘99’ or ‘-1,20’ or others

totalZCount: int

total number of horizontal slice

zRecLength: int

record length of a single horizontal slice

tRecLength: int

record length of a single time (including all variables)

parse(fileContent)

Parse file content as a multi-line str

class xgrads.core.CtlVar(oneLineStr)

Bases: object

A simple variable class used in .ctl file

Attributes

tcount: int

T grid points

zcount: int

Z grid points

ycount: int

Y grid points

xcount: int

X grid points

undef: float

Undefined values

dependZ: bool

Whether the var depends on z

unit: str

Unit of the variable

name: str

Name of the variable

comment: str

A short comment

index: str

Index of this variable

strPos: str

Start position (in bytes) of this variable in the binary file

xgrads.core.GrADS_increment_to_timedelta64(incre)

Convert GrADS time increment string to numpy.timedelta64

Parameters

incre: str

Grads time increment in str format e.g., 1dy.

Returns

timedelta64

GrADS time in datetime64 format

xgrads.core.GrADStime_to_datetime(gradsTime)

Convert GrADS time string e.g., 00:00z01Jan2000 to datetime

Parameters

gradsTime: str

Grads time in str format e.g., 00:00z01Jan2000.

Returns

datetime

GrADS time in datetime format

xgrads.core.GrADStime_to_datetime64(gradsTime)

Convert GrADS time string e.g., 00:00z01Jan2000 to numpy.datetime64

Parameters

gradsTimestr

Grads time in str format e.g., 00:00z01Jan2000.

Returns

datetime64

GrADS time in datetime64 format

class xgrads.core.PDEF(oneline)

Bases: object

PDEF class

Parse necessary info in PDEF.

Reference: http://cola.gmu.edu/grads/gadoc/pdef.html

Attributes

isize: int

size of native grid in x direction

jsize: int

size of native grid in y direction

proj: str

type of projection

lonref: str

reference longitude

xgrads.io module

Created on 2020.04.11

@author: MiniUFO Copyright 2018. All rights reserved. Use is subject to license terms.

xgrads.io.open_CtlDataset(desfile, returnctl=False, encoding='GBK')

Open a single ctl dataset

Open a 4D dataset with a descriptor file end with .ctl and return a xarray.Dataset. This also uses the dask to chunk very large dataset, which is similar to the xarray.open_dataset.

Parameters

desfile: string

Path to the descriptor file end with .ctl or .cts

returnctl: bool

Return dset and ctl as a tuple

Returns

dset: xarray.Dataset

Dataset object containing all coordinates and variables.

ctl: xgrads.CtlDescriptor

Ctl descriptor file if returnctl == True.

xgrads.io.open_mfdataset(paths, parallel=False, encoding='GBK')

Open multiple ctl files as a single dataset

This is similar to xarray.open_mfdataset() that can simutaneously open a series of ctl files that are in similar spatial ranges but of different temporal ranges.

Parameters

paths: str or sequence

Either a string glob in the form "path/to/my/files/*.ctl" or an explicit list of files to open. Paths can be given as strings or as pathlib Paths.

parallel: bool, optional

If True, the open and preprocess steps of this function will be performed in parallel using dask.delayed. Default is False.

encoding: str

Encoding for the ctl file content e.g., [‘GBK’, ‘UTF-8’].

Returns

re: xarray.Dataset

A dataset.

Notes

open_mfdataset opens files with read-only access. When you modify values of a Dataset, even one linked to files on disk, only the in-memory copy you are manipulating in xarray is modified: the original file on disk is never touched.

xgrads.utils module

Created on 2020.08.01

@author: MiniUFO Copyright 2018. All rights reserved. Use is subject to license terms.

xgrads.utils.get_coordinates_from_PDEF(ctl, latlon=True, Rearth=6371200)

Calculate coordinates based on the PDEF information.

Parameters

ctl: str or CtlDescriptor

Either a string representing a ctl file or a CtlDescriptor.

latlon: boolean

Return lat/lon coordinates on PDEF grids if True, from PDEF grids; Return PDEF coordinates if False, from lat/lon grids.

Rearth: float

Radius of the earth, default is 6371200m, consistent with GrADS. But this function is usually used in WRF data, then one should use 6370000m, consistent with WRF model. Thanks to singledoggy at https://github.com/miniufo/xgrads/issues/32 https://github.com/miniufo/xgrads/issues/37

Returns

y, x: xarray.DataArray, xarray.DataArray

A tuple of (y, x) or (lat, lon)

xgrads.utils.get_data_projection(ctl, globe=None, Rearth=6371200)

Get Projection

Return the data projection indicated in PDEF for plot using cartopy.

Parameters

ctl: str or CtlDescriptor

Either a string representing a ctl file or a CtlDescriptor.

globe: ccrs.Globe

Default Globe parameter (None) in cartopy uses ellipse=WGS84. Some regional numerical model like WRF use a spherical earth with a radius of 6370 km. If one want to plot the data output from WRF with PDEF, one uses a default spherical globe with a radius of 6370000 and then provided this globe to this function for an accurate plot.

Thanks to singledoggy at https://github.com/miniufo/xgrads/issues/32 https://github.com/miniufo/xgrads/issues/37

Returns

re: cartopy.ccrs

Cartopy coordinate reference system object for plotting.

xgrads.utils.interp_to_latlon(var, ctl)

Interpolate PDEF data onto lat/lon grids

Interpolate the preprojected data onto lat/lon grids defined by ctl.

Parameters

ctl: str or CtlDescriptor

Either a string representing a ctl file or a CtlDescriptor.

var: DataArray

A variable defined at preprojected coordinates and need to be interpolated onto lat/lon grids.

Returns

re: xarray.DataArray

Interpolated variable

xgrads.utils.oacressman(dataS, lonS, latS, dimS, lonG, latG, rads=[10, 7, 4, 2, 1], undef=-999000000.0, method='cressman')

Objective analysis using Cressmen method [1]

The function tries to reproduce oacres in GrADS. Note that:

  1. The oacres function can be quite slow to execute, depending on grid and station data density;

  2. The scaling of the grid must be linear in lat-lon;

  3. The Cressman Analysis scheme can be unstable if the grid density is substantially higher than the station data density (ie, far more grid points than station data points). In such cases, the analysis can produce extrema in the grid values that are not realistic. It is thus suggested that you examine the results of oacres and compare them to the station data to insure they meet your needs.

Parameters

dataS: DataArray

A 1D DataArray representing the station data.

lonS: DataArray

A 1D array for longitudes of the stations.

latS: DataArray

A 1D array for latitudes of the stations.

dimS: str

Name of the station dimension.

lonG: DataArray or numpy.array or list

A 1D array for longitudes of the grid (should be linear).

latG: DataArray or numpy.array or list

A 1D array for latitudes of the grid (should be linear).

rads: float or list of floats

Radii at which the analysis is performed. Default rads are the same as those of GrADS.

undef: float

Undefined value is set if a grid has no station nearby.

method: str

Methods of calculating weights, should one of [‘cressman’, ‘exp’].

Returns

dataGrid: xarray.DataArray

Result of the objective analysis.

wei: xarray.DataArray

Normalized total weights.

Module contents