oceans.ocfis

oceans.ocfis.alphanum_key(s)[source]
oceans.ocfis.bin_dates(self, freq, tz=None)[source]

Take a pandas time Series and return a new Series on the specified frequency.

Examples

>>> import numpy as np
>>> from pandas import Series, date_range
>>> n = 24 * 30
>>> sig = np.random.rand(n) + 2 * np.cos(2 * np.pi * np.arange(n))
>>> dates = date_range(start="1/1/2000", periods=n, freq="h")
>>> series = Series(data=sig, index=dates)
>>> new_series = bin_dates(series, freq="D", tz=None)
oceans.ocfis.binave(datain, r)[source]

Averages vector data in bins of length r. The last bin may be the average of less than r elements. Useful for computing daily average time series (with r=24 for hourly data).

Parameters:
  • data (array_like)

  • r (int) – bin length

Returns:

bindata – bin-averaged vector

Return type:

array_like

Notes

Original from MATLAB AIRSEA TOOLBOX.

Examples

>>> from oceans.ocfis import binave
>>> data = [
...     10.0,
...     11.0,
...     13.0,
...     2.0,
...     34.0,
...     21.5,
...     6.46,
...     6.27,
...     7.0867,
...     15.0,
...     123.0,
...     3.2,
...     0.52,
...     18.2,
...     10.0,
...     11.0,
...     13.0,
...     2.0,
...     34.0,
...     21.5,
...     6.46,
...     6.27,
...     7.0867,
...     15.0,
...     123.0,
...     3.2,
...     0.52,
...     18.2,
...     10.0,
...     11.0,
...     13.0,
...     2.0,
...     34.0,
...     21.5,
...     6.46,
...     6.27,
...     7.0867,
...     15.0,
...     123.0,
...     3.2,
...     0.52,
...     18.2,
...     10.0,
...     11.0,
...     13.0,
...     2.0,
...     34.0,
...     21.5,
...     6.46,
...     6.27,
...     7.0867,
...     15.0,
...     123.0,
...     3.2,
...     0.52,
...     18.2,
... ]
>>> binave(data, 24)
array([16.564725 , 21.1523625, 22.4670875])

References

03/08/1997: version 1.0 09/19/1998: version 1.1 (vectorized by RP) 08/05/1999: version 2.0

oceans.ocfis.binavg(x, y, db)[source]

Bins y(x) into db spacing. The spacing is given in x units. y = np.random.random(20) x = np.arange(len(y)) xb, yb = binavg(x, y, 2) plt.figure() plt.plot(x, y, ‘k.-‘) plt.plot(xb, yb, ‘r.-‘)

oceans.ocfis.cart2pol(x, y)[source]

Convert from Cartesian to polar coordinates.

Examples

>>> x = [+0, -0.5]
>>> y = [+1, +0.5]
>>> cart2pol(x, y)
(array([1.57079633, 2.35619449]), array([1.        , 0.70710678]))
oceans.ocfis.complex_demodulation(series, f, fc, axis=-1)[source]

Perform a Complex Demodulation It acts as a bandpass filter for f.

series => Time-Series object with data and datetime f => inertial frequency in rad/sec fc => normalized cutoff [0.2]

math : series.data * np.exp(2 * np.pi * 1j * (1 / T) * time_in_seconds)

oceans.ocfis.del_eta_del_x(U, f, g, balance='geostrophic', R=None)[source]

Calculate :mat: frac{partial eta} {partial x} for different force balances

Parameters:
  • U (array_like) – velocity magnitude [m/s]

  • f (float) – Coriolis parameter

  • d (float) – Acceleration of gravity

  • balance (str, optional) – geostrophic [default], gradient or max_gradient

  • R (float, optional) – Radius

oceans.ocfis.despike(self, n=3, recursive=False)[source]

Replace spikes with np.nan. Removing spikes that are >= n * std. default n = 3.

oceans.ocfis.get_profile(x, y, f, xi, yi, mode='nearest', order=3)[source]

Interpolate regular data.

Parameters:
  • x (two dimensional np.ndarray) – an array for the \(x\) coordinates

  • y (two dimensional np.ndarray) – an array for the \(y\) coordinates

  • f (two dimensional np.ndarray) – an array with the value of the function to be interpolated at \(x,y\) coordinates.

  • xi (one dimension np.ndarray) – the \(x\) coordinates of the point where we want the function to be interpolated.

  • yi (one dimension np.ndarray) – the \(y\) coordinates of the point where we want the function to be interpolated.

  • order (int) – the order of the bivariate spline interpolation

Returns:

fi – the value of the interpolating spline at \(xi,yi\)

Return type:

one dimension np.ndarray

Examples

>>> import numpy as np
>>> from oceans.ocfis import get_profile
>>> x, y = np.meshgrid(range(360), range(91))
>>> f = np.array(range(91 * 360)).reshape((91, 360))
>>> Paris = [2.4, 48.9]
>>> Rome = [12.5, 41.9]
>>> Greenwich = [0, 51.5]
>>> xi = Paris[0], Rome[0], Greenwich[0]
>>> yi = Paris[1], Rome[1], Greenwich[1]
>>> get_profile(x, y, f, xi, yi, order=3)
array([17606, 15096, 18540])
oceans.ocfis.lagcorr(x, y, M=None)[source]

Compute lagged correlation between two series. Follow emery and Thomson book “summation” notation.

Parameters:
  • y (array) – time-series

  • y – time-series

  • M (integer) – number of lags

Returns:

Cxy – normalized cross-correlation function

Return type:

array

Examples

TODO: Implement Emery and Thomson example.

oceans.ocfis.mld(SA, CT, p, criterion='pdvar')[source]

Compute the mixed layer depth.

Parameters:
  • SA (array_like) – Absolute Salinity [g/kg]

  • CT (array_like) – Conservative Temperature [\(^\circ\) C (ITS-90)]

  • p (array_like) – sea pressure [dbar]

  • criterion (str, optional) – MLD Criteria

  • are (Mixed layer depth criteria)

  • 'temperature' (Computed based on constant temperature difference)

  • criterion

  • C. (0.5 degree)

  • 'density' (computed based on the constant potential density difference)

  • criterion

  • units. (pd[0] - pd[mld] = 0.125 in sigma)

  • 'pdvar' (computed based on variable potential density criterion)

  • var(T[0] (pd[0] - pd[mld] =)

  • S[0])

  • potential (where var is a variable)

  • of (density difference which corresponds to constant temperature difference)

  • C.

Returns:

  • MLD (array_like) – Mixed layer depth

  • idx_mld (bool array) – Boolean array in the shape of p with MLD index.

References

Monterey, G., and S. Levitus, 1997: Seasonal variability of mixed layer depth for the World Ocean. NOAA Atlas, NESDIS 14, 100 pp. Washington, D.C.

oceans.ocfis.pcaben(u, v)[source]

Principal components of 2-d (e.g. current meter) data calculates ellipse parameters for currents.

Parameters:
  • u (array_like) – zonal wind velocity [m s -1]

  • v (array_like) – meridional wind velocity [m s -1]

Returns:

  • major axis (majrax)

  • minor axis (minrax)

  • major azimuth (majaz)

  • minor azimuth (minaz)

  • ellipticity (elptcty)

Examples

>>> import matplotlib.pyplot as plt
>>> from oceans.ocfis import pcaben, uv2spdir
>>> u = np.r_[(0.0, 1.0, -2.0, -1.0, 1.0), np.random.randn(10)]
>>> v = np.r_[(3.0, 1.0, 0.0, -1.0, -1.0), np.random.randn(10)]
>>> (mjrax, mjaz, mirax, miaz, el), (x1, x2, y1, y2) = pcaben(u, v)
>>> fig, ax = plt.subplots()
>>> _ = ax.plot(x1, y1, "r-", x2, y2, "r-")
>>> ax.set_aspect("equal")
>>> _ = ax.set_xlabel("U component")
>>> _ = ax.set_ylabel("V component")
>>> _ = ax.plot(u, v, "bo")
>>> _ = ax.axis([-3.2, 3.2, -3.2, 3.2])
>>> mdir, mspd = uv2spdir(u.mean(), v.mean())
>>> _ = ax.plot([0, u.mean()], [0, v.mean()], "k-")
>>> flatness = 1 - mirax / mjrax
>>> if False:
...     print("Mean u = {}".format(u.mean()))
...     print("Mean v = {}".format(v.mean()))
...     print("Mean magnitude: {}".format(mspd))
...     print("Direction: {}".format(mdir))
...     print("Axis 1 Length: {}".format(mjrax))
...     print("Axis 1 Azimuth: {}".format(mjaz))
...     print("Axis 2 Length: {}".format.format(mirax))
...     print("Axis 2 Azimuth: {}".format(miaz))
...     print("ellipticity is : {}".format(el))
...     print("Negative (positive) means clockwise (anti-clockwise)")
...     print("Flatness: {}".format(flatness))
...

Notes: https://pubs.usgs.gov/of/2002/of02-217/m-files/pcaben.m

oceans.ocfis.pol2cart(theta, radius, units='deg')[source]

Convert from polar to Cartesian coordinates

Examples

>>> pol2cart(0, 1, units="deg")
(np.float64(1.0), np.float64(0.0))
oceans.ocfis.series_spline(self)[source]

Fill NaNs using a spline interpolation.

oceans.ocfis.shiftdim(x, n=None)[source]

Matlab-like shiftdim in python.

Examples

>>> import oceans.ocfis as ff
>>> a = np.random.rand(1, 1, 3, 1, 2)
>>> print("a shape and dimension: %s, %s" % (a.shape, a.ndim))
a shape and dimension: (1, 1, 3, 1, 2), 5
>>> # print(range(a.ndim))
>>> # print(np.roll(range(a.ndim), -2))
>>> # print(a.transpose(np.roll(range(a.ndim), -2)))
>>> b = ff.shiftdim(a)
>>> print("b shape and dimension: %s, %s" % (b.shape, b.ndim))
b shape and dimension: (3, 1, 2), 3
>>> c = ff.shiftdim(b, -2)
>>> c.shape == a.shape
True
oceans.ocfis.spdir2uv(spd, ang, deg=False)[source]

Computes u, v components from speed and direction.

Parameters:
  • spd (array_like) – speed [m s -1]

  • ang (array_like) – direction [deg]

  • deg (bool) – option, True if data is in degrees. Default is False

Returns:

  • u (array_like) – zonal wind velocity [m s -1]

  • v (array_like) – meridional wind velocity [m s -1]

oceans.ocfis.spec_rot(u, v)[source]

Compute the rotary spectra from u,v velocity components

Parameters:
  • u (array_like) – zonal wind velocity [m s -1]

  • v (array_like) – meridional wind velocity [m s -1]

Returns:

  • cw (array_like) – Clockwise spectrum [TODO]

  • ccw (array_like) – Counter-clockwise spectrum [TODO]

  • puv (array_like) – Cross spectra [TODO]

  • quv (array_like) – Quadrature spectra [ TODO]

Notes

The spectral energy at some frequency can be decomposed into two circularly polarized constituents, one rotating clockwise and other anti-clockwise.

Examples

TODO: puv, quv, cw, ccw = spec_rot(u, v)

References

  1. Gonella Deep Sea Res., 833-846, 1972.

oceans.ocfis.strip_mask(arr, fill_value=nan)[source]

Take a masked array and return its data(filled) + mask.

oceans.ocfis.uv2spdir(u, v, mag=0, rot=0)[source]

Computes speed and direction from u, v components. Converts rectangular to polar coordinate, geographic convention Allows for rotation and magnetic declination correction.

Parameters:
  • u (array_like) – zonal wind velocity [m s -1]

  • v (array_like) – meridional wind velocity [m s -1]

  • mag (float, array_like, optional) – Magnetic correction [deg]

  • rot (float, array_like) – Angle for rotation [deg]

Returns:

  • ang (array_like) – direction [deg]

  • spd (array_like) – speed [m s -1]

Notes

Zero degrees is north.

Examples

>>> import matplotlib.pyplot as plt
>>> from oceans.ocfis import uv2spdir
>>> u = [+0, -0.5, -0.50, +0.90]
>>> v = [+1, +0.5, -0.45, -0.85]
>>> wd, ws = uv2spdir(u, v)
>>> fig, ax = plt.subplots(subplot_kw=dict(polar=True))
>>> kw = dict(arrowstyle="->")
>>> wd = np.deg2rad(wd)
>>> lines = [
...     ax.annotate("", xy=(d, s), xytext=(0, 0), arrowprops=kw)
...     for d, s in zip(wd, ws)
... ]
>>> _ = ax.set_ylim(0, np.max(ws))
oceans.ocfis.wrap_lon180(lon)[source]
oceans.ocfis.wrap_lon360(lon)[source]