tflow package
Contents
tflow package
Processing modules
tflow.davis2hdf5 module
Convert DaVis txt outputs into hdf5
- tflow.davis2hdf5.davis2hdf5(datadir, use_chunks, savedir=None, savepath=None, header='B', scale=1000.0, chunks=None, fps=1.0, mode='piv', start=0, end=None)
- tflow.davis2hdf5.davis2hdf5_dirbase(dirbase, use_chunks, savedir=None, header='B', scale=1000.0, fps=1.0, mode='piv', start=0, end=None)
Convert multiple davis outputs into hdf5 files
- Parameters
dirbase –
savedir –
- tflow.davis2hdf5.davis2hdf5_piv(datadir, use_chunks, savedir=None, savepath=None, header='B', scale=1000.0, chunks=None, fps=1.0, start=0, end=None)
Convert multiple DaVis output (PIV) into a hdf5 file
- Parameters
dirbase –
savedir –
- tflow.davis2hdf5.davis2hdf5_stb(datadir, use_chunks, savedir=None, savepath=None, header='B', scale=1000.0, chunks=None, fps=1.0, start=0, end=None)
Convert multiple DaVis output (PIV) into a hdf5 file
- Parameters
dirbase –
savedir –
- tflow.davis2hdf5.main(args)
- tflow.davis2hdf5.natural_sort(arr)
- tflow.davis2hdf5.write_hdf5_dict(filepath, data_dict, chunks=None)
Stores data_dict :param filepath: file path where data will be stored. (Do not include extension- .h5) :type filepath: str :param data_dict: data should be stored as data_dict[key]= data_arrays :type data_dict: dictionary
Core modules
tflow.velocity module
- tflow.velocity.FFTOutput2CFTOutput_1d(gf, t)
Approximates the FFT of a 1D signal to the Continuous Fourier Transform (CFT)
- Parameters
gf (1d array, FFT output of a 1d sample g(t)) –
t (1d array, a variable (time, space, etc) of the original function g(t)) –
- Returns
gf_cft
- Return type
1d array, Appriximated continuous fourier transform
- tflow.velocity.FFTOutput2CFTOutput_nd(gf, dxs, x0s, axes=None, return_freq=True)
Approximates the DFT output into Continuous Fourier Transform output … Power -> Spectral Density … The input “gf” is assumed to be the shifted, raw DFT output of a ND signal.
i.e. The variable is frequency not angular frequency (wavenumber)
- Parameters
gf (ND array (complex)) – … shifted, raw FFT output … It assumes the output of the function “fft_nd(signal, axes)”
dxs (array-like) –
- … Sampling intervals of the signal in the spacial/temporal domain
i.e. (x, y, z, t) not (1/Lx, 1/Ly, 1/Lz. 1/T)
… Must have the same length as gf
x0s (array-like) –
- … The minimum value of the spatial/temporal domain
i.e. X0, Y0, Z0, T0- the edge coordinates of the data and the initial moment when the data was recorded
… Must have the same length as gf
axes (array-like, e.g.- [0, 1]) – … axes along which FFT was conducted … If None, it assumes that FFT was conducted along all axes of gx
return_freq (bool, default: True) – … If True, it returns a list of the frequencies along the axes FFT was conducted
- tflow.velocity.add_data2udatapath(udatapath, datadict, attrdict=None, grpname=None, overwrite=False, verbose=True)
Writes a data stored in a dictionary into a hdf5 at udatatapth … datadict = {“name1”: value1, “name2”:value2, …} will be stored like /name1, /name2 in the hdf5 file … datadict = {“grp1”: {“name1”: value1, “name2”:value2, …},
“grp1”: {“name1”: value1, “name2”:value2, …}, … }
will be stored like /grp1/name1, /grp1/name2, /grp2/name1, /grp2/name2, …
- Parameters
udatapath (str, a path to the hdf5 file) –
datadict (dictionary, or a nested dictionary (up to level 2)) – … data must be stored like {“name1”: value1, “name2”: value2, …}
grpname (str) –
- … if given, it saves the datadict like
/grpname/name1, /grpname/name2
overwrite (bool, if True, it overwrite the data in the target hdf5 file) –
verbose (bool, if True, it prints out details during saving the data) –
- Returns
- Return type
None
- tflow.velocity.band_limited_noise2d(min_freq=None, max_freq=None, nsamples=1024, samplerate=1.0, exponent=- 1.6666666666666667)
Generates a 2D array of noise with a specific spectral distribution function (k^exponent) … the output noise could be bandlimited [min_freq, max_freq] … the output noise could have a simple frequency dependence ……exponent=0: White, exponent=-1, Pink, exponent=-5/3: Kolmogorov, etc.
- Parameters
min_freq (float, the bandwidth of the noise is [min_freq, max_freq]) –
max_freq (float, the bandwidth of the noise is [min_freq, max_freq]) –
nsamples (int, number of samples in 1D (length of the field)) –
samplerate (float, spacing of the field) –
exponent (float, frequency dependence of the noise... f^exponent) – … This should be [-7.5, 0]
- Returns
noise
- Return type
2d array with shape (nsamples, nsamples)
- tflow.velocity.cart2cyl(x, y, z)
Transformation: cartesian to cylindrical coord z = z y = rho sin phi x = rho cos phi
- Parameters
x (numpy array, cartesian x-coord) –
y (numpy array, cartesian y-coord) –
z (numpy array, cartesian z-coord) –
- Returns
rho, phi, z
- Return type
cylindrical coordinates
- tflow.velocity.cart2cyl_2d(xx, yy, a=0, b=0, x0=None, signed=False)
Transforms Cartesian (x, y) to Cylindrical (z’, rho’) coordinates … This function is useful when an axisymmetry is present in the data. … Cartesian-to-Cylindrical coordinate transformation is a mapping between R3 and R3.
Axisymmetry makes a number of necessary variables to 2 from 3. This function transforms (x, y) to (z’, rho’) … The axis of symmetry is defined by y = a*x + b … If a=b=0, z=x, rho=y
- Parameters
xx (numpy array, x-coord) –
yy (numpy array, y-coord) –
a (float, the axis of symmetry is given by y = a*x + b) –
b (float, the axis of symmetry is given by y = a*x + b) –
x0 (float, This shifts the origin of the cylindrical coordinate system along the symmetry axis.) –
signed (bool, if True, the function returns the signed distance from the axis of symmetry.) –
- Returns
zz, rrho
- Return type
numpy arrays, cylindrical coordinates
- tflow.velocity.cart2cyl_2d_udata(udata, xx, yy, a=0, b=0, x0=None, signed=False)
Transforms a velocity field from the Cartesian (x, y) to Cylindrical (z’, rho’) basis … This function is useful when an axisymmetry is present in the data. … Cartesian-to-Cylindrical coordinate transformation is a mapping between R3 and R3.
Axisymmetry makes a number of necessary variables to 2 from 3. This function transforms (x, y) to (z’, rho’) … The axis of symmetry is defined by y = a*x + b … If a=b=0, z=x, rho=y
- Parameters
xx (numpy array, x-coord) –
yy (numpy array, y-coord) –
a (float, the axis of symmetry is given by y = a*x + b) –
b (float, the axis of symmetry is given by y = a*x + b) –
x0 (float, This shifts the origin of the cylindrical coordinate system along the symmetry axis.) –
signed (bool, if True, the function returns the signed distance from the axis of symmetry.) –
- Returns
udata_cyl
- Return type
numpy arrays, velocity field in cylindrical coordinates
- tflow.velocity.cart2pol(x, y)
Transformation: Cartesian coord to polar coord
- Parameters
x (numpy array, x-coord (Cartesian)) –
y (numpy array, y-coord (Cartesian)) –
- Returns
r (numpy array, radius (polar))
phi (numpy array, angle (polar))
- tflow.velocity.cart2pol_udata(x, y, udata)
Transformation: Cartesian coord to polar coord (x, y, (ux, uy)) -> (r, phi, (ur, uphi)) … Returns polar coordiantes AND velocity field in the polar basis
- Parameters
x (numpy array, x-coord (Cartesian)) –
y (numpy array, y-coord (Cartesian)) –
udata –
array (nd) –
field (velocity) –
- Returns
r (numpy array, radius (polar))
phi (numpy array, angle (polar))
udata_pol, nd array, velocity field in the polar basis (ur, uphi)
- tflow.velocity.cart2sph(x, y, z)
Transformation: cartesian to spherical z = r cos theta y = r sin theta sin phi x = r sin theta cos phi
- Parameters
x (numpy array, x-coord (Cartesian)) –
y (numpy array, y-coord (Cartesian)) –
z (numpy array, z-coord (Cartesian)) –
- Returns
r (radial distance)
theta (polar angle [-pi/2, pi/2] (angle from the z-axis))
phi (azimuthal angle [-pi, pi] (angle on the x-y plane))
- tflow.velocity.cart2sph_velocity(ux, uy, uz, xx, yy, zz, xc=0, yc=0, zc=0)
Transformation: cartesian to spherical (x, y, z, (ux, uy, uz)) -> (r, theta, phi, (ur, utheta, uphi)) … Returns a velocity field in the spherical basis :param ux: :type ux: numpy array, x-component of velocity field (Cartesian) :param uy: :type uy: numpy array, y-component of velocity field (Cartesian) :param uz: :type uz: numpy array, z-component of velocity field (Cartesian) :param xx: :type xx: numpy array, x-coord (Cartesian) :param yy: :type yy: numpy array, y-coord (Cartesian) :param zz: :type zz: numpy array, z-coord (Cartesian) :param xc: :type xc: float, x-coord of the origin of the spherical cordinate system :param yc: :type yc: float, y-coord of the origin of the spherical cordinate system :param zc: :type zc: float, z-coord of the origin of the spherical cordinate system
- Returns
ur (numpy array, radial component of velocity field in the spherical basis)
utheta (numpy array, polar component of velocity field in the spherical basis)
uphi (numpy array, azimuthal component of velocity field in the spherical basis)
- tflow.velocity.cft_1d(g, f)
Numerically evaluate the Fourier Transform of a function ‘g’ for given frequencies
- Parameters
g (function) –
f (array-like, frequencies at which Fourier coefficients are calculated) –
- Returns
result
- Return type
Fourier coefficients at given frequency
- tflow.velocity.change_of_basis_mat_cart2sph(theta, phi)
Returns a change-of-basis matrix from a cartesian basis to a spherical basis :param theta: :type theta: float, polar angle [-pi/2, pi/2] (angle from the z-axis) :param phi: :type phi: float, azimuthal angle [-pi, pi] (angle on the x-y plane)
- Returns
Mc2s
- Return type
3d array, change-of-basis matrix from cartesian to spherical
Example
[ar, atheta, aphi] = np.matmul(Ms2c, [ax, ay, az]) # Convert from cartesian to spherical coordinates
- tflow.velocity.change_of_basis_mat_sph2cart(theta, phi)
Returns a change-of-basis matrix from a spherical basis to a cartesian basis
- Parameters
theta (float, polar angle [-pi/2, pi/2] (angle from the z-axis)) –
phi (float, azimuthal angle [-pi, pi] (angle on the x-y plane)) –
- Returns
Ms2c
- Return type
3d array, change-of-basis matrix from spherical to cartesian
Example
[ax, ay, az] = np.matmul(Ms2c, [ar, atheta, aphi]) # Convert from spherical to cartesian coordinates
- tflow.velocity.clean_data(data_org, mask=None, method='nn', max_iter=5, tol=0.05, kernel_radius=2, kernel_sigma=2, replace_val=None, cutoff=inf, fill_value=0, verbose=False, notebook=True, makecopy=True, median_filter=True, showtqdm=True)
- This fills missing values (np.nan) in an array by one of the listed procedures below.
The options are 1. nearest neighbor filling (method = “nn”)- fast 2. filling with some constant (method = “fill”)- fast 3. filling with local mean (method = “localmean”)- slow 4. filling with an idw kernel (method = “idw”) - slow
- Parameters
data_org (nd array, array to be cleaned) –
mask (nd array) –
method (str, choose from 'fill', 'nn', 'localmean', 'idw') – … computation is more expensive as it gets more right. … fill: it filles
max_iter (int, number of iterations conducted for the direct convolution methods) – … When the method uses direct convolution, it repeats the operation until certain smoothness is achieved. … relevant parameter for method==localmean or idw’
tol (relevant parameter for method==localmean or idw') –
kernel_radius (float, size of the kernel is 2 * kernel_radius + 1, relevant parameter for method==localmean') –
kernel_sigma (float, std of a gaussian kernel, relevant parameter for method==idw') –
replace_val (float, default: None. If not None, it replaces the values of the array with np.nan if value=replac_val.) –
… This feature could be useful if the scalar data assigns a specific value instead of np.nans. … This is certainly the case whenever DaVis outputs pressure. It outputs 0 instead of nan. This causes a problem as 0 could be physically meaningful while DaVis assigned that value solely because STB did not have sufficient tracks to
infer the actual (intrinsic) value. In this case, simply replace all 0s with np.nan, then replace nans with nn, localmean, etc.
cutoff (float, default: np.inf. If not np.inf, it will invalidate values above cutoff.) –
fill_value (float, default: 0. If not 0, it will replace values above cutoff with fill_value) – … relevant parameter for method==’fill’
verbose (bool, default: False. If True, it will print out the mean square difference between iterations) –
notebook (bool, default: True. If True, it will use tqdm_notebook instead of tqdm to show progress bar) –
- Returns
data
- Return type
nd array with the same shape as data_org
- tflow.velocity.clean_data_interp1d(y, x=None, thd=None, p=0.98)
This function interpolates the missing and erroneous data using 1D interpolation. … errorneous data points are identified by the rate of change of the data.
- Parameters
y (1/2d array with shape (n,) or (n, duration)) –
x (1/2d array with shape (n,) or (n, duration) (optional)) – … MUST have the same shape as y
thd (float) – … threshold on the slope (dy/dx) used to spot the spurious values … If np.abs( dy/dx ) / y) < thd, the points in y will be removed, and will be interpolated as well as np.nan in y.
p (float, 0 < p < 1) – … if thd is None, it will remove (1-p) of the data points in y, and replaces with the interpolated values
Returns –
---------- –
x_output (nd array with shape (n, 1) or (n, duration)) – … new x for new y
y_output (nd array with shape (n, 1) or (n, duration)) – … interpolated y
- tflow.velocity.clean_udata(udata, mask=None, method='nn', max_iter=10, tol=0.05, kernel_radius=2, kernel_sigma=2, fill_value=0, cutoff=inf, median_filter=True, replace_zeros=True, showtqdm=True, verbose=False, notebook=True, make_copy=True)
Cleans up the velocity field udata. … 1. Thresholding to spot unphysical values … 2. Mask unphysical values, np.nan, and np.inf … 3. ND interpolation over space (but NOT time) using direct convolution (replace_nan(…)) …… No interpolation over time is done because udata at two different frames do not have to be related in principle. … 4. Median filter (optional) with kernel size = 2 * kernel_radius + 1
- Parameters
udata (nd array, velocity field data with shape (no of components, y, x, (z), t) or (no of components, y, x, (z))) –
mask (nd array, same shape as udata, default: None) – … If it were not None, this function interpolates the
method (str- options are 'fill', 'nn', 'local mean', 'idw') – … ‘fill’ (fill by a constant “fill_value”) … ‘nn’ (nearest neighbor filling), … ‘local mean’, relevant arg: kernel_radius=2 … ‘idw’ (convolution with a Gaussian kernel, relevant arg: “kernel_sigma”)
max_iter (int, default: 10) – … Number of iterations for inpainting until tolerance is reached
tol (float, default: 0.05, tolerance for inpainting) –
kernel_radius (int, default: 2, radius of the kernel for inpainting and median filter) –
kernel_sigma (float, default: 2, sigma of the Gaussian kernel for inpainting if method == 'idw) –
fill_value (float, If method=='fill', the errorneous valeus are replaced by this fill_value.) –
cutoff (float, a positive real number- Any velocity vector whose norm is greater than this cutoff is subject to cleaning.) –
median_filter (bool, default: True. If True, a median filter is applied to the velocity field after inpainting/nearest-neighbor filling) –
replace_zeros (bool default: True) – … Some softwares assign 0 as a velocity instead of na or np.nan
showtqdm (bool, default: True) – … If True, show tqdm for the processes: 1. removing np.nan 2. applying a median filter
verbose (bool, default: False) – … If True, it shows a tqdm progress bar for the iterations of the direct convolution method
notebook (bool, If True, it uses tqdm_notebook instead of tqdm) –
make_copy (bool, default: True) –
- … If True, it creates a copy of the given udata, then modify the copied array.
Without copying, it modifies the given array directly. (Why?- it should create a new copy
- Returns
udata_i
- Return type
nd array, same shape as udatawith unphysical values replaced
- tflow.velocity.clean_udata_cheap(udata, cutoffU=2000, fill_value=nan, verbose=True)
ONLY WORKS FOR THE 2D data Conducts a cheap bilinear interpolation for missing data. … literally, computes the average of the values interpolated in the x- and y-directions … griddata performs a better interpolation but this method is much faster but not necessarily accurate. … values near the edges must not be trusted.
- Parameters
udata –
cutoffU –
fill_value –
verbose –
- tflow.velocity.coarse_grain_2darr(arr, nrows_sub, ncolumns_sub)
Coarse-grain a 2D array … Coarse-graining a MxN array means a following procedure.
1. Divide an MxN array into blocks of (m x n) arrays … m=nrows_sub, n=ncolumns_sub 2. Replace each block by an average of the values in the block
… If you are not familiar with coarse-graining, consult with Kadanoff’s block-spin renormalization group.
- Parameters
arr (2d array) –
nrows_sub (int, Number of rows of blocks (over which values are averaged)) –
ncolumns_sub (int, Number of columns of blocks) –
- Returns
arr_coarse
- Return type
coarse-grained 2d arr
- tflow.velocity.coarse_grain_2darr_overwrap(arr, nrows_sub, ncolumns_sub, overwrap=0.5)
Coarse-grain 2D arrays with overwrap (mimics how PIVLab processes a velocity field)
- arr= [[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23] [24 25 26 27 28 29] [30 31 32 33 34 35]]
-> Make a new array. (nrows_sub=4, ncolumns_sub=4, overwrap=0.5)
- array([[ 0., 1., 2., 3., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 8., 9., 10., 11.], [ 12., 13., 14., 15., 14., 15., 16., 17.], [ 18., 19., 20., 21., 20., 21., 22., 23.], [ 12., 13., 14., 15., 14., 15., 16., 17.], [ 18., 19., 20., 21., 20., 21., 22., 23.], [ 24., 25., 26., 27., 26., 27., 28., 29.], [ 30., 31., 32., 33., 32., 33., 34., 35.]])
-> Coarse-grain (output)
- array([[ 10.5, 12.5],
[ 22.5, 24.5]])
- Parameters
arr (2d array) –
nrows_sub (int, Number of rows of blocks (over which values are averaged)) –
ncolumns_sub (int, Number of columns of blocks) –
overwrap (fraction of overwrap, default=0.5, [0, 1]) –
- Returns
arr_coarse
- Return type
coarse-grained 2d arr
- tflow.velocity.coarse_grain_3darr(arr, nrow_sub, ncol_sub, ndep_sub, overwrap=0, showtqdm=True, notebook=True, verbose=False)
Coarse-grain a 3d array … The idea is to split the original array into many subcells, and average over each subcell … The cell size is (nrow_sub, ncol_sub, ndep_sub)
- Parameters
arr (3d array to be coarse-grained) –
nrow_sub (int, number of rows of the subcell) –
ncol_sub (int, number of columns of the subcell) –
ndep_sub (int, number of depths(steps) of the subcell) –
overwrap (float, [0, 1)) –
showtqdm (bool) –
- Returns
new_arr
- Return type
coarse-grained 3d array
- tflow.velocity.coarse_grain_3dudata(udata_3d, nrow_sub, ncol_sub, ndep_sub, overwrap=0, showtqdm=False, notebook=True)
Coarse-grain a 3d udata … 3d udata has a shape (dim=3, nrows, ncols, ndeps, duration) or (dim=3, nrows, ncols, ndeps) … The idea is to split the original array into many subcells, and average over each subcell … The cell size is (nrow_sub, ncol_sub, ndep_sub)
- Parameters
udata_3d (4d or 5d array, udata) – … udata is just a nd array.
nrow_sub (int, number of rows of the subcell) –
ncol_sub (int, number of columns of the subcell) –
ndep_sub (int, number of depths(steps) of the subcell) –
overwrap (float, [0, 1)) –
showtqdm (bool) –
- Returns
udata_cg
- Return type
coarse-grained ud
- tflow.velocity.coarse_grain_udata(udata, nrows_sub, ncolumns_sub, overwrap=0.5, xx=None, yy=None, notebook=True)
Returns a coarse grained udata … so far, this can handle only 2D udata :param udata: :type udata: nd array, velocity field :param nrows_sub: :type nrows_sub: int, number of rows in the sub-grid :param ncolumns_sub: :type ncolumns_sub: int, number of columns in the sub-grid :param overwrap: :type overwrap: float, fraction of the sub-grid that is overlapped with the original grid, [0, 1] :param xx: :type xx: nd array, x-coordinates of the original grid :param yy: :type yy: nd array, y-coordinates of the original grid
- Returns
udata_sub
- Return type
nd array, coarse grained velocity field
- tflow.velocity.computeImageDistanceUsingHuMoments(img1, img2, method=2)
Returns the image distance between two images :param img1: :type img1: 2d array- the elements must be between 0 and 255. :param img2: :type img2: 2d array- the elements must be between 0 and 255. :param method: :type method: this method gets passed to cv2.matchShapes (e.g.- cv2.CONTOURS_MATCH_I1, cv2.CONTOURS_MATCH_I2, cv2.CONTOURS_MATCH_I3)
- Returns
- Return type
imgDist- a scalar quantity which represents a distance between two images based on the (logarithmic) Hu moments.
- tflow.velocity.compute_circulation(udata, xx, yy, zz=None, contour=None, rs=[10.0], xc=0, yc=0, zc=0, n=100, return_contours=False)
- Returns circulation along a given contour (if None, a circular contour by default) with udata and spatial grids as inputs
- … it is compatible with spatially 2D/3D udata
Yet, 2D udata is probably easier to handle. If you need a sliced velocity field from a volumetric udata, consider using slice_udata_3d()
… For 3D udata, you probably want to pass a contour manually. … Default contour is a circle(s) with radius of 10 and its center at (xc, yc) or (xc, yc, zc).
If you want the contours with multiple radii, try something like rs = [10, 20, 25, …]
… if you want to draw contours later, you can output pts on the contours by setting return_contours True.
- How it works:
It computes a Riemann sum of addends defined by velocity cdot dl at each point on the contour. … In case of
a part of the contour were out of the plane / volume
udata contains nans at a point on the contour
this function first computes the average of the addends, then multiples the avg by the number of pts along the contour. This way, it still computes the correct value of circulation if these cases occur, and still outputs somewhat meaningful values even if these cases occur.
- Parameters
udata (ndarray, velocity field) –
xx (ndarray, x-coordinates of the grid (real space)) –
yy (ndarray, y-coordinates of the grid (real space)) –
zz (ndarray, z-coordinates of the grid (real space)) –
contour (2d array with shape (n, dim), default: None) –
- … contour must be closed but it is not necessary to pass a closed contour.
The contour will be closed by connecting the first and last pts in this array. (It is also okay to pass a contour with an array of a closed contour to this function)
… A default contour is circular with a radius (or radii) of 10 around the center (xc, yc, zc) … contour[:, 0]- x-coords of pts on the contour
contour[:, 1]- y-coords of pts on the contour contour[:, 2]- z-coords of pts on the contour
rs (list, radii in the same units as xx/yy/zz) – … only relevant if “contours” is None
xc (float, x-coordinate of the center of a circular contour(s), default:0.) – … only relevant if “contours” is None
yc (float, y-coordinate of the center of a circular contour(s), default:0.) – … only relevant if “contours” is None
zc (float, z-coordinate of the center of a circular contour(s), default:0.) – … only relevant if “contours” is None
n (number of sampled pts on the circular contour) – … only relevant if “contours” is None
return_contours (bool, default: False) – … If True, it returns pts on the contour(s) … This feature could be handy if you’d like to plot the contour(s) later
- Returns
gammas (nd array with shape (duration, ) or (len(rs), duration), circulation values)
contours (nd array (optional))
- tflow.velocity.compute_energy_current_from_path(udatapath, xc, yc, zc, rho=0.000997, flux_density=False, maxr=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, clean=True, cutoff=inf, verbose=False)
- tflow.velocity.compute_energy_flux(udata, xx, yy, zz, xc, yc, zc, rho=0.000997, n=50, ntheta=100, nphi=100, flux_density=False)
Returns the energy flux (int (Energy current density) dS in nW … If flux_density is True, it returns the energy flux per unit area in nW / mm^2 … Units guide: [udata], [xx] = L/T, L.
The dimension of the energy flux is [e_flux] = [rho * udata**3 * dS] = ML^2/T^3 = [W=J/s] … This represents the amount of energy flow through the surface per unit time.
- … If flux_density is True, this returns the energy flux density- simply energy flux divided by the surface area
The dimension of the energy flux DENSITY is [e_flux density] = M/T^3 = [W] / L^2 … This represents the amount of energy flow through the surface per unit time.
- … Sample case: [udata], [xx] = mm/s, mm
… The dimension of energy flux: ML^2/T^3 = g mm^2/s^3 = nW … The dimension of energy flux density: nW / mm^2
n: number of gaussian surfaces considered
- tflow.velocity.compute_energy_flux_from_path(udatapath, xc, yc, zc, rho=0.000997, flux_density=False, maxr=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, clean=True, cutoff=inf, verbose=False)
- tflow.velocity.compute_form_no(stroke_length, orifice_d=25.6, piston_d=160.0, num_orifices=8, setting=None)
Returns a formation number with stroke length as an input … Old box (small): orifice_d=20, piston_d=125 … New box (3D printed): orifice_d=25.6, piston_d=160
- Parameters
stroke_length (float/1d array, stroke length in mm) –
orifice_d (float, orifice diameter in mm) –
piston_d (float, piston diameter in mm) –
num_orifices (int, number of orifices) –
- Returns
LD
- Return type
float/1d array, formation number
- tflow.velocity.compute_kolmogorov_lengthscale_simple(epsilon, nu)
Return Kolmogorov length scale for a given set of dissipation rate and viscosity :param epsilon: :type epsilon: float, dissipation rate :param nu: :type nu: float, viscosity
- Returns
- Return type
eta, float, Kolmogorov length scale
- tflow.velocity.compute_line_integral(*args, **kwargs)
A wrapper for compute_circulation_along_contour()
- tflow.velocity.compute_mass_flux(udata, xx, yy, zz, xc, yc, zc, rho=0.000997, ntheta=100, nphi=100, flux_density=False)
Returns the energy flux (int (mass current density) dS in M/T … If flux_density is True, it returns the energy flux per unit area in M/(L^2 T) … Units guide: [udata], [xx] = L/T, L.
The dimension of the energy flux is [mass_flux] = [rho * udata * dS] = M/T … This represents the amount of energy flow through the surface per unit time.
- … If flux_density is True, this returns the energy flux density- simply energy flux divided by the surface area
The dimension of the energy flux DENSITY is [mass_flux density] = M/(L^2 T) … This represents the amount of energy flow through the surface per unit time.
- … Sample case: [udata], [xx] = mm/s, mm
… The dimension of energy flux: M/T = g /s … The dimension of energy flux density: M/(L^2 T)
- tflow.velocity.compute_net_energy_current(udata, xx, yy, zz, xc, yc, zc, rho=0.000997, flux_density=False, maxr=None)
- Returns the integral of energy flux (Net energy current inside the Gaussian sphere)
Net energy current = int_0^{R} (energy current density) cdot dS dr
- tflow.velocity.compute_ring_circulation_from_master_curve(l, veff, dp=160.0, do=25.6, N=8, setting='medium')
Given a stroke length, this function returns circulation of a vortex ring in a vortex ring collider … well tested over time … units: mm2/s e.g.-
r = compute_ring_radius_from_master_curve(8.2, setting=’small’) v = compute_ring_velocity_from_master_curve(8.2, estimate_veff(8.2, 200), setting=’small’)
- Parameters
l (float/array) – … stroke length in mm
veff (float/array) – … effective piston velocity- (<vp>^2 / <vp> ) … this quantitty can be estimated from estimate_veff(commanded_stroke_length, commanded_stroke_velocity)
dp (float) – …. piston diameter in mm
float (do) – … orfice diameter in mm
N (int/float) – … number of oricies
lowerGamma (float) – … experimental constant, default: 2.2 … This represents the ratio of semi-major to semi-minor radius when a vortex bubble is approximated as an ellipsoid
setting (str) – … vortex ring collider versions … choose from ‘medium’ or ‘small’ … ‘medium’ refers to the chamber configuration to create D=10cm blobs … ‘small’ refers to the chamber configuration to create D=5cm blobs
- Returns
velocity
- Return type
float/array, velocity of the ring
- tflow.velocity.compute_ring_radius_from_master_curve(l, dp=160.0, do=25.6, N=8, lowerGamma=2.2, setting='medium')
Given a stroke length, this function returns a radius of a vortex ring in a vortex ring collider … well tested over time … units: mm e.g.-
r = compute_ring_radius_from_master_curve(8.2, setting=’small’) v = compute_ring_velocity_from_master_curve(8.2, estimate_veff(8.2, 200), setting=’small’)
- Parameters
l (float/array) – … stroke length in mm
dp (float) – …. piston diameter in mm
float (do) – … orfice diameter in mm
N (int/float) – … number of oricies
lowerGamma (float) – … experimental constant, default: 2.2 … This represents the ratio of semi-major to semi-minor radius when a vortex bubble is approximated as an ellipsoid
setting (str) – … vortex ring collider versions … choose from ‘medium’ or ‘small’ … ‘medium’ refers to the chamber configuration to create D=10cm blobs … ‘small’ refers to the chamber configuration to create D=5cm blobs
- Returns
radius
- Return type
float/array, radius of the rings
- tflow.velocity.compute_ring_velocity_from_master_curve(l, veff, dp=160.0, do=25.6, N=8, setting='medium')
Given a stroke length, this function returns self-induced velocity of a vortex ring in a vortex ring collider … well tested over time … units: mm/s e.g.-
r = compute_ring_radius_from_master_curve(8.2, setting=’small’) v = compute_ring_velocity_from_master_curve(8.2, estimate_veff(8.2, 200), setting=’small’)
- Parameters
l (float/array) – … stroke length in mm
veff (float/array) – … effective piston velocity- (<vp>^2 / <vp> ) … this quantitty can be estimated from estimate_veff(commanded_stroke_length, commanded_stroke_velocity)
dp (float) – …. piston diameter in mm
float (do) – … orfice diameter in mm
N (int/float) – … number of oricies
lowerGamma (float) – … experimental constant, default: 2.2 … This represents the ratio of semi-major to semi-minor radius when a vortex bubble is approximated as an ellipsoid
setting (str) – … vortex ring collider versions … choose from ‘medium’ or ‘small’ … ‘medium’ refers to the chamber configuration to create D=10cm blobs … ‘small’ refers to the chamber configuration to create D=5cm blobs
- Returns
velocity
- Return type
float/array, velocity of the ring
- tflow.velocity.compute_rms(qty, axes=None)
Returns the root mean square of qty
- Parameters
qty (nd array, quantity) –
axes (list of ints, axes to compute rms over) –
- Returns
rms
- Return type
float, root mean square of qty
- tflow.velocity.compute_signal_loss_due_to_windowing(xx, yy, window, x0=0, x1=None, y0=0, y1=None)
Returns the inverse of the signal-loss factor by the window Signal loss factor: 1 (rectangle… no loss), 0.2-ish (flattop)
- Parameters
xx (2d/3d numpy array) – x grid
yy (2d/3d numpy array) – y grid
window (str) – name of the window: flattop, hamming, blackman, etc.
x0 (int) – index to specify the region to which the window applies: xx[y0:y1, x0:x1], yy[y0:y1, x0:x1]
x1 (int) – index to specify the region to which the window applies: xx[y0:y1, x0:x1], yy[y0:y1, x0:x1]
y0 (int) – index to specify the region to which the window applies: xx[y0:y1, x0:x1], yy[y0:y1, x0:x1]
y1 (int) – index to specify the region to which the window applies: xx[y0:y1, x0:x1], yy[y0:y1, x0:x1]
- Returns
gamma – inverse of the signal-loss factor
- Return type
float
- tflow.velocity.compute_spatial_autocorr(ui, x, y, roll_axis=1, n_bins=None, x0=0, x1=None, y0=0, y1=None, t0=None, t1=None, coarse=1.0, coarse2=0.2, notebook=True)
[DEPRICATED] Use get_two_point_vel_corr() instead.
Compute spatial autocorrelation (two-point correlation) function of 2D velocity field using np.roll Spatial autocorrelation function:
f = <u_j(
ec{x}) u_j( ec{x}+rhat{x_i})> / <u_j( ec{x})^2>
where velocity vector u = (u1, u2). If i = j, f is called longitudinal autocorrelation function. Otherwise, f is called transverse autocorrelation function.
- Example:
u = ux # shape(height, width, duration) x_, y_ = range(u.shape[1]), range(u.shape[0]) x, y = np.meshgrid(x_, y_)
# LONGITUDINAL AUTOCORR FUNC rrs, corrs, corr_errs = compute_spatial_autocorr(u, x, y, roll_axis=1) # roll_axis is i in the description above
# TRANSVERSE AUTOCORR FUNC rrs, corrs, corr_errs = compute_spatial_autocorr(u, x, y, roll_axis=0) # roll_axis is i in the description above
ui: numpy array, one-component velocity field i.e. shape: (height, width, duration) x: numpy array, 2d grid y: numpy array, 2d grid roll_axis: int, axis index to compute correlation… 0 for y-axis, 1 for x-axis n_bins: int, number of bins to compute statistics x0: int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. x1: int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. y0: int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. y1: int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. t0: int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. t1: int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. coarse: float (0, 1], This parameter determines the bin width (int(1. / coarse)) of the spatial autocorrelation function. coarse2: float (0, 1], This parameter is used to control the number of data points to compute a correlation value at a particular distance.
… 1: all data points are used … 0.5: only a half of data points are used
rr: 2d numpy array, (distance, time) corr: 2d numpy array, (autocorrelation values, time) corr_err: 2d numpy array, (std of autocorrelation values, time)
- tflow.velocity.compute_spatial_autocorr3d(ui, x, y, z, roll_axis=1, n_bins=None, x0=None, x1=None, y0=None, y1=None, z0=None, z1=None, t0=None, t1=None, coarse=1.0, coarse2=0.2, periodic=False, Lx=None, Ly=None, Lz=None, notebook=True)
[DEPRICATED] Use get_two_point_vel_corr instead.
Compute spatial autocorrelation function of 2+1 velocity field using np.roll() Spatial autocorrelation function:
f = <u_j(
ec{x}) u_j( ec{x}+rhat{x_i})> / <u_j( ec{x})^2>
where velocity vector u = (u1, u2). If i = j, f is called longitudinal autocorrelation function. Otherwise, f is called transverse autocorrelation function.
- Example:
u = ux # shape(height, width, duration) x_, y_ = range(u.shape[1]), range(u.shape[0]) x, y = np.meshgrid(x_, y_)
# LONGITUDINAL AUTOCORR FUNC rrs, corrs, corr_errs = compute_spatial_autocorr(u, x, y, roll_axis=1) # roll_axis is i in the description above
# TRANSVERSE AUTOCORR FUNC rrs, corrs, corr_errs = compute_spatial_autocorr(u, x, y, roll_axis=0) # roll_axis is i in the description above
ui: numpy array, 3 + 1 scalar field. i.e. shape: (height, width, duration) x: numpy array, 3d grid y: numpy array, 3d grid z: numpy array, 3d grid roll_axis: int, axis index to compute correlation… 0 for y-axis, 1 for x-axis, 2 for z-axis n_bins: int, number of bins to compute statistics x0: int, index to specify a portion of data in which autocorrelation funciton is computed. Will use data u[y0:y1, x0:x1, z0:z1, t0:t1]. x1: int, index to specify a portion of data in which autocorrelation funciton is computed. y0: int, index to specify a portion of data in which autocorrelation funciton is computed. y1: int, index to specify a portion of data in which autocorrelation funciton is computed. z0: int, index to specify a portion of data in which autocorrelation funciton is computed. z1: int, index to specify a portion of data in which autocorrelation funciton is computed. t0: int, index to specify a portion of data in which autocorrelation funciton is computed. t1: int, index to specify a portion of data in which autocorrelation funciton is computed. coarse: float (0, 1], Process coarse * possible data points. This is an option to output coarse results. coarse2: float (0, 1], Rolls matrix Returns ——- rr: 2d numpy array, (distance, time) corr: 2d numpy array, (autocorrelation values, time) corr_err: 2d numpy array, (std of autocorrelation values, time)
- tflow.velocity.compute_streamfunction_direct(udata, xx, yy, xref=0, yref=0, inc=1, nctrs=1, nsample=100, nkinks=10, noise=None, return_sampled_grid=False, coordinate_system='cartesian', notebook=True)
- Returns a streamfunction of a given udata in a ND array by computing
psi = int_A^B udy - vdx (cartesian) psi = int_A^B
ho uz drho - urho dz (cyindrical)
… udata must be non-divergent
udata xx: 2d array, a positional grid (x)
… If coordinate_system == ‘cylindrical’, this will be interpreted as a grid of z
- yy: 2d array, a positional grid (y)
… If coordinate_system == ‘cylindrical’, this will be interpreted as a grid of rho=np.sqrt(x**2 + y**2)
- xref: float, default: 0
… reference point of a streamfunction … The contour integral will be calculated between (xref, yref) and (xp, yp)
(xp, yp) will be sampled from the given positinal grid.
- yref: float, default: 0
… reference point of a streamfunction … The contour integral will be calculated between (xref, yref) and (xp, yp)
(xp, yp) will be sampled from the given positinal grid.
inc: int, sampling frequency of (xp, yp) out of the positional grid (xx and yy) nctrs: int, must be greater than or equal to 1
… number of contours used to compute the streamfunction value at the given point … the streamfunction values could be different depending on the contour due to discreteness of data
… divergent field will also result in such a discrepancy udata must be non-divergent in order for the streamfunction to exist
- nsample: int, default: 100
… number of sampled points on each contour to compute the integral,
- nkinks: int, must be greater or equal to 2
… this controls how wiggly contours are if the contours were not given by the user
- noise: array-like with two elements, default: None
… This controls the maximum amplitude of the wiggle.
- return_sampled_grid: bool, default: False
- … If True, this will return positional grids (xx_s, yy_s) used to sample the streamfunction values.
This becomes handy if inc is not equal to 1. You can always plot the result as ax.pcolormesh(xx_s, yy_s, psi)
- coordinate_system: str, default: ‘cartesian’
- … the form of the contour integral to compute the stream function depends on the coordinate system
psi = int u dy - v dx (Cartesian, 2D) psi = int
- ho (u_z drho - u_rho dz) (Cylindrical, 3D-axisymmetric)
- notebook: bool, default: True
- … If True, it uses tqdm.tqdm_notebook for a progress bar.
(a natural choise if you run the code on Jupyter notebooks)
… If False, it uses tqdm.tqdm for a progress bar.
psi_master, psi_err_master, xx_sampled (Optional), yy_sampled (Optional)
- tflow.velocity.compute_streamfunction_values(udata, xx, yy, x, y, xref=0, yref=0, contours=None, nctrs=4, nsample=100, nkinks=5, noise=None, return_contours=False)
Returns a streamfunction value at a point (x, y) for 2D incompressible flows with respect to the value at the reference (xref, yref)
… Computes a contour integral int_A^B udy - vdx … Requires bezier module
- Parameters
udata –
xx –
yy –
x –
y –
xref –
float –
point (... y coordinate of the reference) –
yref –
float –
point –
contours (3d array with shape (number of contours, number of points on each contour, 2), default: None) –
E.g. (x, y) on the 3rd contour is stored as (contours[2, :, 0], contours[2, :, 1]) … By default, it generates nctrs contours connecting (xref, yref) and (x, y)
It generates non-selfintersecting, smooth conours. It could be non-smooth if (xref, yref) == (x, y)
nctrs (int, must be greater than or equal to 1) –
… number of contours used to compute the streamfunction value at the given point … the streamfunction values could be different depending on the contour due to discreteness of data
… divergent field will also result in such a discrepancy udata must be non-divergent in order for the streamfunction to exist
nsample (int, default: 100) – … number of sampled points on each contour to compute the integral,
nkinks (int, must be greater or equal to 2) – … this controls how wiggly contours are if the contours were not given by the user
noise (array-like with two elements, default: None) – … This controls the maximum amplitude of the wiggle.
return_contours – … If True, it returns contours used to compute the integral.
- Returns
psis (nd array with shape=(nctrs, udata.shape[-1))
contours (optional) (points on the contours used to compute the streamfunction value)
- tflow.velocity.compute_streamfunction_values_cylindrical(udata_cylindrical, zz, rrho, z, rho, zref=0, rhoref=0, contours=None, nctrs=4, nsample=100, nkinks=10, noise=None, return_contours=False)
Returns a streamfunction value at a point (x, y) for 3D, axisymmetric flows with respect to the value at the reference (xref, yref)
… Computes a contour integral int_A^B rho (u_z drho - u_rho dz) … Requires bezier module
- Parameters
udata_cylindrical (nd array, (u_z, u_rho)) –
zz –
rrho –
z –
rho –
zref –
float –
rhoref –
float –
contours (3d array with shape (number of contours, number of points on each contour, 2), default: None) –
E.g. (x, y) on the 3rd contour is stored as (contours[2, :, 0], contours[2, :, 1]) … By default, it generates nctrs contours connecting (xref, yref) and (x, y)
It generates non-selfintersecting, smooth conours. It could be non-smooth if (xref, yref) == (x, y)
nctrs (int, must be greater than or equal to 1) –
… number of contours used to compute the streamfunction value at the given point … the streamfunction values could be different depending on the contour due to discreteness of data
… divergent field will also result in such a discrepancy udata must be non-divergent in order for the streamfunction to exist
nsample (int, default: 100) – … number of sampled points on each contour to compute the integral,
nkinks (int, must be greater or equal to 2) – … this controls how wiggly contours are if the contours were not given by the user
noise (array-like with two elements, default: None) – … This controls the maximum amplitude of the wiggle.
return_contours – … If True, it returns contours used to compute the integral.
- Returns
psis (nd array with shape=(nctrs, udata.shape[-1))
contours (optional) (points on the contours used to compute the streamfunction value)
- tflow.velocity.convertNDto1D(ef_nd, freqs, nkout=None, mode='linear', cc=1.0)
Returns a shell-to-shell contribution from ND array Converts ND array into 1D array (primarily used for Energy spectrum computation)
- Parameters
ef_nd (ND array, assuming energy density in the frequency space) –
freqs (ND array, frequency grid) – … assuming np.stack((fxx, fyy)) or np.stack((fxx, fyy, fzz)) … fxx is a 2D/3D grid of 1/x.
nkout (int) – … Number of points to be sampled in the radial direction
mode (str, ['linear', 'log']) – … This determines whether sampling is evenly done in the linear or log scale. … For energy spectrum computation, one might prefer to get statistics at frequency/wavenumber evenly spaced in the log scale
- Returns
- Return type
fr_binned, ef1d, ef1d_err
- tflow.velocity.convert_dat2h5files(dpath, savedir=None, verbose=False, overwrite=True, start=0)
Converts tecplot data files (.data format) to a set of hdf5 files … Used for DaVis STB Lagrangian data
- Parameters
dpath (str, path to tecplot data file (data)) –
savedir (str, default: None) – … directories where hdf5 files are going to be saved
verbose (bool, default: False) –
overwrite (bool, default: True) – … boolean which determines whether hdf5 files will be overwritten
start (int, default:10) – … this will be used to name the h5 files
- tflow.velocity.count_nans(arr)
Returns the number of nans in the given array
- tflow.velocity.count_nans_along_axis(udatapath, axis='z', x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, inc=100)
Count the number of nans in udata along an axis
- Parameters
udatapath (str, path to udata) –
axis (str, 'x', 'y', 'z', an axis along which the number of nans gets calculated) –
inc (int, time increment to count the number of nans in a udata) – … if one wants complete statistics, use inc=1 but this is overkill.
- Returns
nans
- Return type
1d array, (number of nans in udata) / udata.size along the specified axis
- tflow.velocity.cross(udata, vdata)
Returns an cross poduct of udata with vdata
- Parameters
udata (nd array with shape (dim, height, width, (depth), (duration))) –
vdata (nd array with shape (dim, height, width, (depth), (duration))) –
- Returns
vecData
- Return type
nd array with (dim, height, width, (depth), (duration)) if dim==3 OR (height, width, (depth), (duration)) if dim==2
- tflow.velocity.curl(udata, dx=1.0, dy=1.0, dz=1.0, xyz_orientations=array([1, - 1, 1]), xx=None, yy=None, zz=None, verbose=False)
Computes curl of a velocity field using a rate of strain tensor … if you already have velocity data as ux = array with shape (m, n) and uy = array with shape (m, n),
udata = np.stack((ugrid1, vgrid1)) omega = vec.curl(udata)
- Parameters
udata ((ux, uy, uz) or (ux, uy)) –
dx (float, spatial spating of a 2D/3D grid) –
dy (float, spatial spating of a 2D/3D grid) –
dz (float, spatial spating of a 2D/3D grid) –
xyz_orientations (1d array) – … differentiation in the index space and the physical space must be conducted properly. tflow convention is to treat the row, column, and the depth (i,j,k) are parallel to x, y, z in the physical space; however, this does not specify the direction of the axes. (+i direction is only equal to EITHER +x or -x). This ambiguity causes a problem during differentiation, and the choice is somewhat arbitrary to the users. This function offers a solution by two ways. One way is to give a 2d/3d array of the positional grids. If xx, yy, zz are given, it would automatically figures out how +i,+j,+k are aligned with +x,+y,+z. The second way is give delta x/ delta_i, dy/delta_j, dz/delta_k. This argument is related to this method. … e.g. xyz_orientations = [1, 1, 1]… means +x // +i, +y//+j, +z//+k xyz_orientations = [-1, -1, -1]… means +x // -i, +y//-j, +z//-k xyz_orientations = [1, -1, 1]… means +x // +i, +y//-j, +z//+k
xx (2d/3d array, positional grid) –
- … If given, it would automatically figure out whether +x and +i point at the same direction,
and the curl is computed based on that
yy (2d/3d array, positional grid) –
- … If given, it would automatically figure out whether +y and +j point at the same direction,
and the curl is computed based on that
zz (2d/3d array, positional grid) –
- … If given, it would automatically figure out whether +z and +k point at the same direction,
and the curl is computed based on that
- Returns
omega – shape: (height, width, duration) (2D) or (height, width, depth, duration) (3D)
- Return type
numpy array
- tflow.velocity.curl_2d(ux, uy, dx=1.0, dy=1.0, xyz_orientations=array([1, - 1]), xx=None, yy=None, zz=None)
Calculate curl of 2D (or 2D+1) field
- Parameters
ux (2D array) – x component of a 2D field
uy (2D array) – y component of a 2D field
dx (float) – data spacing (mm/px)
dy (float) – data spacing (mm/px)
- Returns
omega – vorticity field
- Return type
2D numpy array
- tflow.velocity.cyl2cart(rho, phi, z, x0=0, y0=0)
Transformation from cylindrical to cartesian coords :param rho: :type rho: numpy array, radial distance (cylindrical) :param phi: :type phi: numpy array, polar angle [-pi, pi] (angle on the x-y plane) :param z: :type z: numpy array, z-coord :param x0: :type x0: float, (x0, y0, 0) is the origin of the coordinate system :param y0: :type y0: float, (x0, y0, 0) is the origin of the coordinate system
- Returns
x, y, z
- Return type
cartesian coordinates
- tflow.velocity.decompose_duidxj(sij)
Decompose a duidxj tensor into a symmetric and an antisymmetric parts Returns symmetric part (eij) and anti-symmetric part (gij)
- Parameters
sij –
(x (j) or) –
y –
t –
i –
(x –
y –
z –
t –
i –
j) –
- Returns
eij (5d or 6d numpy array, symmetric part of rate-of-strain tensor.) – 5d if spatial dimensions are x and y. 6d if spatial dimensions are x, y, and z.
gij (5d or 6d numpy array, anti-symmetric part of rate-of-stxxain tensor.) – 5d if spatial dimensions are x and y. 6d if spatial dimensions are x, y, and z.
- tflow.velocity.default_analysis_piv(dpath, inc=1, overwrite=False, time=None, t0=0, t1=None)
A function to perform default analysis on 2D PIV data.
- Parameters
dpath (str, path to the h5 file where a velocity field is stored) –
inc (int, increment of the time index to be used to perform analysis) – … inc==1: use all v-field data … inc==n: use every n-th frame of the v-field data
overwrite (bool, whether to overwrite existing analysis results) –
time (1d array, time that corresponds to the measurement) – … if provided, it writes this data to the h5 file at /t
t0 (int, index of the first frame to be used to compute the statistics, [t0, t1)) –
t1 (int, index of the first frame to be used to compute the statistics, [t0, t1)) –
- tflow.velocity.default_analysis_stb(dpath, inc=1, overwrite=False, time=None)
A function which adds some basic results such as time-averaged energy (FOR 3D DATA) … Suggestive indices of the volume to load:’x0’, ‘x1’, ‘y0’, ‘y1’, ‘z0’, ‘z1’ … Velocity statistics: ‘abs_ui_median’, ‘abs_ui_avg’, ‘abs_ui_99’, ‘abs_ui_99p9’, ‘u_cutoff’ … Temporally/spatially averaged energy and enstrophy: ‘etavg’, ‘esavg’, ‘esavg_err’, ‘enst_tavg’, ‘enst_savg’, ‘enst_savg_err’ … Center of energy: ‘xc’, ‘yc’, ‘zc’ … Center of enstrophy: ‘xc_enst’, ‘yc_enst’, ‘zc_enst’ … Radial energy profile (The center is (xc, yc, zc): r_energy’, ‘eTimeThetaPhi_avg’, ‘eTimeThetaPhi_avg_err … Radial enstrophy profile (The center is (xc, yc, zc): r_energy’, ‘eTimeThetaPhi_avg’, ‘eTimeThetaPhi_avg_err
- Parameters
dpath (str, path to the h5 file where udata is stored.) – … the h5 file must include 3D+1 array of ‘ux’, ‘uy’, ‘uz’ and 3D arrays of ‘x’, ‘y’, ‘z’ … this is a default data format
inc (int, default: 1) –
energy (... increment used to compute time-sensitive quantities such as spatial-averaged) – … If inc==10, for example, this function computes the spatially-averaged energy every 10 time steps.
overwrite (bool, whether to overwrite existing analysis results) –
time (1d array, time that corresponds to the measurement) – … if provided, it writes this data to the h5 file at /t
- Returns
- Return type
None
- tflow.velocity.derive_all(udata, dx, dy, savepath, udatapath='none', **kwargs)
A shortcut function to derive major quantities of turbulence
- Parameters
udata (nd array, velocity field) –
dx (float, spacing along x) –
dy (float, spacing along y) –
savepath (str, path where the derived quantities are saved) –
kwargs (kwargs that are passed to both derive_easy() and derive_hard()) – … e.g. x0, x1, y0, y1, z0, z1, t0, t1
- tflow.velocity.derive_easy(udata, dx, dy, savepath, time=None, inc=1, dz=None, nu=1.004, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, reynolds_decomp=False, udatapath='none', notebook=True, overwrite=True)
Function to derive quantities which are (relatively) computationally cheap … energy spectra, energy, enstrophy, skewness etc. :param udata: :type udata: nd array, velocity field :param dx: :type dx: float, spacing along x :param dy: :type dy: float, spacing along y :param savepath: :type savepath: str, path where the derived quantities are saved :param time: :type time: 1d array, time in physical units :param inc: … if inc=1, then it uses the whole time series to derive various quantities (default)
… if inc=n, then it uses every nth time point to derive various quantities (this speeds up the process)
- Parameters
dz (float, spacing along z (3d data only)) –
nu (float, kinematic viscosity) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
reynolds_decomp (bool, default: False) – … if True, then it uses the fluctuating velocity instead of raw velocity to compute various quantities
notebook (bool, default: True) – … if True, then it uses the tqdm_notebook instead of tqdm to display a progress bar
overwrite (bool, default: True) – … if True, then it overwrites the existing data in savepath
- Returns
- Return type
None
- tflow.velocity.derive_hard(udata, dx, dy, savepath, time=None, inc=1, dz=None, nu=1.004, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, reynolds_decomp=False, coarse=1.0, coarse2=1.0, notebook=True, overwrite=True)
Function to derive quantities which are (relatively) computationally expensive … structure function, two_point correlation function,
taylor microscale as a curvature of the long. autocorr. func. etc.
- Parameters
udata (nd array, velocity field) –
dx (float, spacing along x) –
dy (float, spacing along y) –
savepath (str, path where the derived quantities are saved) –
time (1d array, time in physical units) –
inc (int, increment along time) – … if inc=1, then it uses the whole time series to derive various quantities (default) … if inc=n, then it uses every nth time point to derive various quantities (this speeds up the process)
dz (float, spacing along z (3d data only)) –
nu (float, kinematic viscosity) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
reynolds_decomp (bool, default: False) – … if True, then it uses the fluctuating velocity instead of raw velocity to compute various quantities
coarse (float, default: 1.0) – … parameter for get_structure_function
coarse2 (float, default: 1.0) – … parameter for get_structure_function … The higher the value, the more data points are used to evaluate the statistics to get the structure function
notebook (bool, default: True) – … if True, then it uses the tqdm_notebook instead of tqdm to display a progress bar
overwrite (bool, default: True) – … if True, then it overwrites the existing data in savepath
- Returns
- Return type
None
- tflow.velocity.div(udata, dx=1.0, dy=1.0, dz=1.0, xyz_orientations=array([1, - 1, 1]), xx=None, yy=None, zz=None)
Computes divergence of a velocity field
- Parameters
udata (numpy array) – … (ux, uy, uz) or (ux, uy) … ui has a shape (height, width, depth, duration) or (height, width, depth) (3D) … ui may have a shape (height, width, duration) or (height, width) (2D)
- Returns
div_u – … div_u has a shape (height, width, depth, duration) (3D) or (height, width, duration) (2D)
- Return type
numpy array
- tflow.velocity.dot(udata, vdata)
Returns a dot poduct of udata with vdata
- Parameters
udata (nd array with shape (dim, height, width, (depth), (duration))) –
vdata (nd array with shape (dim, height, width, (depth), (duration))) –
- Returns
scaData
- Return type
nd array with (height, width, (depth), (duration))
- tflow.velocity.estimate_cirulation_vring_collider(sl, sv)
Returns the circulation of a vortex ring created in the vortex ring collider (setting 1- 10cm blob creation)
- Parameters
sl (float/array) – commanded stroke length in mm
sv (float/array) – commanded stroke velocity in mm/s
- Returns
gammaT, gammaB
- Return type
tuple of float values/arrays, circulation of the top and the bottom rings
- tflow.velocity.estimate_radius_vring_collider(sl, sv)
Returns the radius of a vortex ring created in the vortex ring collider (setting 1- 10cm blob creation)
- Parameters
sl (float/array) – commanded stroke length in mm
sv (float/array) – commanded stroke velocity in mm/s
- Returns
rrT, rrB
- Return type
tuple of float values/arrays, radius of the top and the bottom rings
- tflow.velocity.estimate_ringVRratio(sl, sv, dp=160.0, do=25.6, norfices=8, lowerGamma=2.2, setting='medium', method='master_curve', return_err=False, return_V_R=False)
Estimates the V/R ratio of a ring created in a vortex ring collider … V/R ratio: ring velocity / ring radius … Two methods are possible.
By Using a master curve to infer ring velocity and radius
By interpolating the experimental measurements in the past
- Parameters
sl (float/array) – commanded stroke length in mm
sv (float/array) – commanded stroke velocity in mm/s
dp (float) – …. piston diameter in mm
float (do) – … orfice diameter in mm
norifices (int/float) – … number of oricies
lowerGamma (float) – … experimental constant, default: 2.2 … This represents the ratio of semi-major to semi-minor radius when a vortex bubble is approximated as an ellipsoid
setting (str) – … vortex ring collider versions … choose from ‘medium’ or ‘small’ … ‘medium’ refers to the chamber configuration to create D=10cm blobs … ‘small’ refers to the chamber configuration to create D=5cm blobs
method (str, choose from "master_curve" and "measurement") –
return_err (bool) – … Only applicable to method==”master_curve”
- Returns
vrRatio, (vrRatio_err) – … Self-induced velocity / radius of a vortex ring(s) created by (stroke length, stroke velocity) … Error of V/R ratio due to the discrepancy between the rings created at the top and bottom orifices
- Return type
float/arrays, float/arrays
- tflow.velocity.estimate_ring_energy(sl, sv, dp=160.0, do=25.6, N=8, lowerGamma=2.2, setting='medium', rho=0.001, veff=None, a=1.0, alpha=None, beta=None, core_type='viscous', circulation_option='master curve', model='thin_core', verbose=False)
Given a stroke length, this function estimates energy of a vortex ring in a vortex ring collider in nJ … units: nJ
- Parameters
sl (float/1d array, stroke length in mm) –
sv (float/1d array, stroke velocity in mm/s) –
dp (float, piston diameter) –
do (float, orifice diameter) –
N (number of orifices) –
lowerGamma (float) – … experimental constant, default: 2.2 … This represents the ratio of semi-major to semi-minor radius when a vortex bubble is approximated as an ellipsoid
setting (str, options are 'medium' and 'small') – … if setting == ‘small’, it uses dp, do, N = 56.7, 12.8, 8. … if setting == ‘medium’, it uses dp, do, N = 160, 25.6, 8.
rho (float, mass density of medium in g/mm3, default: 1e-3 (water)) –
a (float, a core size of a vortex ring) –
alpha (float, a vortex ring core parameter, see Sullivan et. al. 2008) –
beta (float, a vortex ring core parameter, see Sullivan et. al. 2008) –
core_type (str, defalut: 'viscous') – … if specified, it uses the values of alpha and beta for each core model- taken from Sullivan et. al. 2008 … options are ‘viscous’, ‘solid_const_volume’, ‘hollow_const_volume’,’hollow_const_pressure’, ‘hollow_surface_tension’
- Returns
energy
- Return type
vortex ring energy in nJ
- tflow.velocity.estimate_veff(sl, sv)
Returns effective velocity from a given commanded stroke length and velocity … This function interpolates values based on the measurements in the past
- Parameters
sl (int/float/1d array) –
Commanded stroke length in mm
sv (int/float/1d array) –
Commanded stroke velocity in mm/s
- Returns
veff –
Effective velocity in mm/s
Velocity program factor * mean speed
Velocity program factor P = Mean of the second moment / Square of the mean of the first moment (average)
- Return type
1d array
- tflow.velocity.estimate_velocity_vring_collider(sl, sv)
Returns the velocity of a vortex ring created in the vortex ring collider (setting 1- 10cm blob creation)
- Parameters
sl (float/array) – commanded stroke length in mm
sv (float/array) – commanded stroke velocity in mm/s
- Returns
vrT, vrB
- Return type
tuple of float values/arrays, velocity of the top and the bottom rings
- tflow.velocity.expand_dim(arr)
Returns arr[…, np.newaxis] … shape of arr changes from arr.shape to (arr.shape, 1)
- Parameters
arr (nd array) –
- Returns
- Return type
arr[…, np.newaxis]
- tflow.velocity.export_raw_file(data2save, savepath, dtype='uint32', thd=inf, interpolate=None, fill_value=nan, contrast=True, contrast_value=None, log10=False, notebook=True, **kwargs)
Exports a raw file from a numpy array with inteprolation features … The intended use is to convert the numpy array to a raw file which can be loaded to Dragonfly … np.nan in the given array could be filled by the following interpolating methods:
‘nn’: fills nans with the nearest neighbors (fast) ‘localmean’: fills nans with the local mean (kernel size of 3 by default
the kernel size can be changed by passing an extra kwargs to the method called replace_nan_w_nn) (slow)
- ‘idw’: fills nans with the (inverse distancing weighting) Gaussian kernel
the kernel size can be changed by passing an extra kwargs to the method called replace_nan_w_nn) (slow)
- Parameters
data2save (nd array, shape (Ny, Nx, Nz, Nt)) –
savepath (str, path where the raw file is saved) –
dtype (str, default: 'uint32', data type of the raw file) –
thd (float default: np.inf) – … data > thd will be replaced by fill_value
interpolate (str, default None) –
- … choose from ‘idw’ and ‘localmean’, ‘nn
… if specified, it replaces np.nan in array using replace_nan(…)
fill_value (float, default: np.nan) – … value that is used to fill in data where data value > thd
kwargs (passed to replace_nan(...)) –
- Returns
- Return type
None
- tflow.velocity.export_raw_file_from_dpath(udatapath, func=<function get_energy>, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, savedir=None, dtype='uint32', thd=None, interpolate=None, notebook=True, running_avg=1, **kwargs)
Exports a raw file of the output of a given function (default: get_energuy) at each time step. (Intended for 4D visualization. e.g. use ORS Dragonfly for visualiztion)
… Argument: path to udata … Philosophy: Load 3D data at an instant of time, compute the quantity of interest. Export the 3D array. Repeat.
- Parameters
udatapath (str, a path to the udata file) –
func (function, a function that takes in a 3D array and returns a 3D array) – … default: get_energy()- returns the instantaneous energy field of the flow
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
x1 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
y0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
y1 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
z0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
z1 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
t0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
t1 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
inc (int, default: 1) – … exports the raw data every “inc”-th time step
savedir (str, default: None) – … a path of the directory where raw data will be saved
dtype (str, default: 'uint32') – … data type of the raw data
thd (float, default: None) – … values above this threshold are set to 0.
interpolate (str, default None) – … choose from ‘idw’ and ‘localmean’ …… Inverse distance weighting (IDW) - gaussian mean …… localmean - assigns mean of the surrounding values at the missing points
notebook (bool, default: True,) – …. if True, use tqdm_notebook instead of tqdm to show a progress bar
running_avg (int, default: 1) – … if running_avg>1, it exporsts the running average of the computed quantity
kwargs (additional arguments for func) –
- Returns
- Return type
None
- tflow.velocity.extend_2darray_fill(arr, newarrshape, fill_value=nan)
Resize a 2d array while keeping the physical shape of the original array and fill the rest with something e.g.- arr =
- array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]])
- -> arr_ext with newarrshape = (6,6)
- array([[ 0., 1., 2., 3., 4., nan],
[ 5., 6., 7., 8., 9., nan], [ 10., 11., 12., 13., 14., nan], [ 15., 16., 17., 18., 19., nan], [ nan, nan, nan, nan, nan, nan], [ nan, nan, nan, nan, nan, nan]])
- Parameters
arr (2d numpy array) –
newarrshape (tuple, new array shape ... (nrows, ncols)) –
fill_value (float, default=np.nan, value to fill the rest of the array with) –
- Returns
arr_ext
- Return type
extended/padded 2d array
- tflow.velocity.fft_1d(gt)
Returns the shifted FFT of a 1D signal
- Parameters
gt (1d array) –
- Returns
gf
- Return type
1d complex array
- tflow.velocity.fft_nd(gx, axes=None)
Conducts FFT along specified axes … If axes were not given, it FFT along all axes … Returns shifted FFT output
… FFT is a fast DFT algorithm, meaning that it does computation in Frequency space (1/x) instead of the Angular Frequency (wavenumber) space. … It is recommended to do the change of variables at the end of the process because it becomes increasingly hard to keep track of the factor of 2pi as the computation becomes more complex.
- Parameters
gx (ND-array, Signal) –
axes (array-like, e.g.- [0, 1]) – … axes along which FFT is conducted … Default is doing FFT along all axes … If you want to do 1D FFT using a 3D data, you may provide a 3D data with axes=[0] etc.
- Returns
- Return type
np.fft.fftshift(np.fft.fftn(gx, axes=axes))
- tflow.velocity.fftnoise2d(f)
Returns a inverse FT of a given noise after multiplying random phase
- Parameters
f (2d array, frequency of noise) –
- Returns
- Return type
noise = np.fft.ifftn(f*random_phase)real, 2d array
- tflow.velocity.fill_udata(udata, keep, duplicate=True, fill_value=nan)
Replaces values in ~keep with ‘filled_value’ … For actual masking which does not involve replacing values of the array, use a numpy masked array.
- Parameters
udata (nd array of a v-field) –
keep (2/3d boolean array, where True indicates values to keep) –
copy (bool, default: True) –
True (... If) –
untouched. (the given udata remains) –
- Returns
vdata
- Return type
nd array- a masked array
- tflow.velocity.fill_unphysical_with_sth(U, mask, fill_value=nan)
Returns an array whose elements are replaced by fill_value if its mask value is True
- Parameters
U (array-like) –
mask (multidimensional boolean array) –
fill_value (value that replaces masked values) –
- Returns
U_filled
- Return type
numpy array, same shape as U, with masked values replaced by fill_value
- tflow.velocity.find_crop_no(udata, tol=0.2)
Returns a how many pixels should be cropped from the edge if udata contains many nan values near the edge.
- Parameters
udata (nd array, velocity field, shape (ncomp, height, width, (depth),(duration))) –
tol (float, default: 0.2) – … The tolerance for the percentage of nan values near the edge
- Returns
i (int, how many pixels should be cropped from the edge)
Examples
——–
udata = fix_udata_shape(udata)
n = find_crop_no(udata, tol=0.2)
udata_cropped = udata[ (, n:-n, n:-n, …])
- tflow.velocity.find_n_largest_values(arr, n)
Returns n largest values in a given array
- tflow.velocity.find_n_smallest_values(arr, n)
Returns n smallest values in a given array
- tflow.velocity.find_nearest(array, value, option='auto')
Find an element and its index closest to ‘value’ in ‘array’
- Parameters
array (nd array) –
value (float/int) –
option (str, 'auto' or 'less', or 'greater') – … ‘auto’ will return the element closest to ‘value’ … ‘less’ will return the element closest to ‘value’ that is LESS than ‘value’ … ‘greater’ will return the element closest to ‘value’ that is GREATER than ‘value’
- Returns
idx (index of the array where the closest value to ‘value’ is stored in ‘array’)
array[idx] (the closest value in ‘array’)
- tflow.velocity.fix_udata_shape(udata)
Adds a singleton dimension to the shape of udata if it does not have one. It is better to always have udata with shape (3, height, width, depth, duration) (3D) or (2, height, width, duration) (2D) This method fixes the shape of udata whose shape is (3, height, width, depth) or (2, height, width)
- Parameters
udata (nd array,) – … with shape (height, width, depth) (3D) or (height, width, duration) (2D) … OR shape (height, width, depth, duration) (3D) or (height, width, duration) (2D)
- Returns
udata
- Return type
nd array, with shape (height, width, depth, duration) (3D) or (height, width, duration) (2D)
- tflow.velocity.fourier_transform_1d(samples, fs, t0, return_freq=False)
Approximate the Fourier Transform of a time-limited signal by means of the discrete Fourier Transform.
samples: signal values sampled at the positions t0 + n/Fs fs: Sampling frequency of the signal t0: starting time of the sampling of the signal
Returns: FT of the underlying function of given samples frequency: 1d array, frequency in hz (optional)
- tflow.velocity.fourier_transform_nd(gx, dxs, x0s, axes=None, return_freq=True, return_in='freq')
Returns a (Continuous) Fourier Transform of a given signal using FFT (DFT) … This returns the adjusted values of FFT as approximated CFT of the given signal.
If sampling frequency were sufficiently high, there is a simple relation between DFT and CFT of the signal, and DFT can be used to approximate CFT of the signal.
- … Since DFT is conveniently defined using Frequency (not angular frequency), this returns the CFT as a function of frequency, f.
If one desires to convert the spectral density as a function of omega=2pi*f, you may set return_in=’wavenumber’.
- Parameters
gx (ND signal) –
dxs (array-like) –
- … Sampling intervals of the signal in the spacial/temporal domain
i.e. (y, x, z, t) not (1/Ly, 1/Lx, 1/Lz. 1/T)
… The order is (dy, dx, dz) … Must have the same length as gf
x0s (array-like) –
- … The minimum value of the spatial/temporal domain
i.e. Y0, X0, Z0, T0- the edge coordinates of the data and the initial moment when the data was recorded
… The order is (Y0, X0, Z0) … Must have the same length as gf
axes (array-like, e.g.- [0, 1]) – … axes along which FFT was conducted … If None, it assumes that FFT was conducted along all axes of gx
return_freq (bool, default: True) – … If True, it returns a list of the frequencies along the axes FFT was conducted
return_in (str, Choose from ['freq', 'wavenumber', 'angular frequency', 'ang freq', 'k']) –
- … If return_in in [‘wavenumber’, ‘angular frequency’, ‘ang freq’, ‘k’],
it returns the CFT as a function of wavenumber instead of frequency (1/x)
- Returns
gf_cft (Fourier transform of the signal “gx”)
freqs (list, corresponding frequencies along the axes)
- tflow.velocity.gaussian_blur_scalar_field(field, sigma=7, mode='nearest', **kwargs)
Gaussian blur a scalar field with shape=(…, duration) such as udata using scipy.ndimage.filters.gaussian_filter
- Parameters
field (nd array with shape (dim, ..., duration)) –
sigma (int, size of the gaussian kernel) –
- Returns
blurred
- Return type
gaussian blurred field with the same shape as the field
- tflow.velocity.gaussian_blur_vector_field(field, sigma=7, mode='nearest', **kwargs)
Gaussian blur a scalar/vector field with shape=(dim, …, duration) such as udata using scipy.ndimage.filters.gaussian_filter … e.g. udata
udata = fix_udata_shape(udata) gaussian_blur(udata, sigma=5)
- Parameters
field (nd array with shape (dim, ..., duration)) –
sigma (int, size of the gaussian kernel) –
- Returns
blurred
- Return type
gaussian blurred field with the same shape as the field
- tflow.velocity.gen_arb_curves(pt1, pt2, n=5, npts=100, noise=None, allow_self_intersection=False, n_attempt=100)
Generates n arbitrary curves connecting pt1 and pt2 … the obtained curve is not self-intersecting by default
… this can be changed via “allow_self_intersection”
How it works: 1. Sample equally-spaced points on the straight line connecting pt1 and pt2 2. Add noise to each sampled points 3. Draw a Benzier curve with disturbed points (this makes the curve smooth) 4. If Step 3 results a self-intersecting curve, repeat 1-3 untile the curve is not self-intersecting 5. Repeat 1-4 until you obtain n curves
- Parameters
pt1 (1d array-like, e.g.- [0., 0.,]) –
pt2 (1d array-like, e.g.- [1., 1.,]) –
- … pt1 and pt2 could be the same coordinate but one might need to adjust “noise” to obtain a desired curve
However, this would make the curve non-smooth at pt1
n (int, MUST be greater than or equal to 2) –
… number of points used to construct a Benzier curve … The higher n is, the more wiggly/complex a curve becomes … n=2: Line
n=3: 1 kink n=4: 2 kinks …
npts (int) –
- … number of sampled points on the output curves
This essentially defines the number of kinks on the curve
noise – … noise is added to a straight lig
allow_self_intersection (bool, default: False) – … If False, do not allow self-intersection of the generated curves
n_attempt (int, default: 100) –
- Returns
bezier_curve
- Return type
2d array, shape=(n, 2)
- tflow.velocity.gen_bezier_curve(pts, n=100)
Generates a Bezier curve between two given points … pts.shape = (n, 2) … pts[0] = x, pts[1] = y
REQUIRES berzier module
- Parameters
pts (2d array,) – … points used to draw bezier curves. Shape: (number of points, 2)
n (int) – … number of sampled points on the obtained bezier curve
- Returns
bezier_curve – … (x, y) = (bezier_curve[:, 0], bezier_curve[:, 1])
- Return type
2d array, shape=(n, 2)
- tflow.velocity.generate_sample_field(L, n=201, exponent=- 1.6666666666666667, mag=10000.0, return_xy=True)
Returns a square v-field which has the energy spectrum with a given exponent … 1. It prepares a Fourier Transform of the resulting velocitiy field
Add random phase to the array
Inverse Fourier Transform the prepared field
Multilply “mag”
… Known issues: this algorithm fails for exponents outside [-7.5, -0.1]
- Parameters
L (float, size of a field) –
n (int, length of the array) –
exponent (float, [-7.5, -0.1] seems to work.) –
mag (float, this factor is multiplied to the resulting v-field in the end) –
return_xy (bool, if True, returns x and y arrays) –
- Returns
udata (2d array with shape (n, n))
xx (2d array with shape (n, n), optional, x-coordinates of the array)
yy (2d array with shape (n, n), optional, y-coordinates of the array)
- tflow.velocity.getHuMoments(qty, method='binary', thd=100, log=True)
Returns Hu Moments of a 2D array
- Parameters
qty (2d array) –
method ('binary' or 'thresholding') –
thd (int/float, value for binarization or thresholding) –
log –
- Returns
huMoments_
- Return type
1d array of hu moments (h0-h6), h6 flips a sign under reflection
- tflow.velocity.get_1d_energy_spectrum(udata, k='kx', x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, window=None, correct_signal_loss=True, debug=False, verbose=True)
Returns 1D energy spectrum from velocity field data
- Parameters
udata (nd array) –
k (str, default: 'kx') – string to specify the direction along which the given velocity field is Fourier-transformed
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of available window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
- Returns
eiis (numpy array) – eiis[0] = E11, eiis[1] = E22 … 1D energy spectra with argument k=”k” (kx by default)
eii_errs (numpy array:) – eiis[0] = E11_error, eiis[1] = E22_error
k (1d numpy array) – Wavenumber with shape (number of data points, ) … Unlike get_energy_spectrum(…), this method NEVER outputs the wavenumber array with shape (number of data points, duration)
- tflow.velocity.get_1d_energy_spectrum_old(udata, k='kx', x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, window=None, correct_signal_loss=True, debug=True)
Returns 1D energy spectrum from velocity field data
- Parameters
udata (nd array) –
k (str, default: 'kx') – string to specify the direction along which the given velocity field is Fourier-transformed
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of available window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
- Returns
eiis (numpy array) – eiis[0] = E11, eiis[1] = E22 … 1D energy spectra with argument k=”k” (kx by default)
eii_errs (numpy array:) – eiis[0] = E11_error, eiis[1] = E22_error
k (1d numpy array) – Wavenumber with shape (number of data points, ) … Unlike get_energy_spectrum(…), this method NEVER outputs the wavenumber array with shape (number of data points, duration)
- tflow.velocity.get_1d_rescaled_energy_spectrum(udata, epsilon=None, nu=1.0034, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=1, dy=1, dz=1, notebook=True, window='flattop', correct_signal_loss=True)
Returns SCALED 1D energy spectra (E11 and E22) … Applies the flattop window function by default … Uses dissipation rate estimated by the rate-of-strain tensor unless given]
- Parameters
udata (nd array) –
epsilon (nd array or float, default: None) – dissipation rate used for scaling energy spectrum If not given, it uses the values estimated using the rate-of-strain tensor
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of available window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
- Returns
eii_arr_norm (nd array) – Scaled spectral densities (Scaled E11 and Scaled E22)
eii_err_arr_norm (nd array) – Scaled errors for (Scaled E11 and Scaled E22)
k_norm (nd array) – Scaled wavenumber
- tflow.velocity.get_angular_impulse(udata, xx, yy, zz=None, rho=0.001, crop=2, keep=None, R=None, xc=0, yc=0, zc=0)
Returns the total angular impulse inside the region defined by xx, yy, zz … it returns an array of a shape (duration, ) … If return_bulk_surface is True, it returns hydrodynamic impulse, its bulk term, and surface term
- Parameters
udata (4d/5d array, v-field data with shape (3, h, w, d) or (3, h, w, d, t)) –
xx (3d array, positional grid about x) –
yy (3d array, positional grid about y) –
zz (3d array, positional grid about z) –
rho (fluid density, default 1e-3 g/mm3) –
crop (int, crop the domain near the edge to remove the boundary effects) –
keep (boolean array, indices of the points to keep) –
R (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
xc (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
yc (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
zc (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
- Returns
hydrodynamic angular impulse
- Return type
2d array (components, duration)
- tflow.velocity.get_angular_impulse_density(udata, xx, yy, zz=None, rho=0.001, crop=2)
It returns the density of (hydrodynamic) angular impulse
… It is the moment of the impulsive force which generates the motion from the rest … Angular impulse is defined as
- A = 1/3 int r imes (r imes omega) dV (Lamb, 1932, Sect. 152, Saffman. Sect. 3.5, Eq.5)
= - 1/2 int r^2 omega dV - 1/6 r^2 r imes (omega cdot n) dS (Batchelor, 1967, Sect. 7.2) = int r imes u dV + 1/2 int r^2 (n imes u) dS (Saffman. Sect. 3.5, Eq.7)
- … If all the vorticity is contained inside the control volume,
A = int r imes u dV
- Parameters
udata (4d/5d array, v-field data with shape (3, h, w, d) or (3, h, w, d, t)) –
xx (3d array, positional grid about x) –
yy (3d array, positional grid about y) –
zz (3d array, positional grid about z) –
rho (fluid density, default 1e-3 g/mm3) –
crop (int, crop the domain near the edge to remove the boundary effects) –
- Returns
ai
- Return type
nd array, angular impulse density
- tflow.velocity.get_autocorr_functions(r_long, f_long, r_tran, g_tran, time)
Return interpolated functions using the outputs of get_two_point_vel_corr_iso() … arguments: r, t
- Parameters
r_long (numpy array) – output of get_two_point_vel_corr_iso()
f_long (numpy array) – output of get_two_point_vel_corr_iso()
r_tran (numpy array) – output of get_two_point_vel_corr_iso()
g_tran (numpy array) – output of get_two_point_vel_corr_iso()
time (numpy array) – time corresponding to the given autocorrelation functions
- Returns
f, g
- Return type
long./trans. autocorrelation functions with argument (distance, time)
- tflow.velocity.get_autocorr_functions_int_list(r_long, f_long, r_tran, g_tran)
Returns lists of INTERPOLATED autocorrelation functions … an element of the list is a spline interpolating function at an instant in time
- Parameters
r_long (numpy array with shape (n_bins, duration)) – … distance for the long. autocorrelation function output of get_two_point_vel_corr_iso()
f_long (numpy array) – … long. autocorrelation function output of get_two_point_vel_corr_iso()
r_tran (numpy array) – … distance for the trans. autocorrelation function output of get_two_point_vel_corr_iso()
g_tran (numpy array) – … trans. autocorrelation function output of get_two_point_vel_corr_iso()
- Returns
fs (list, length = duration = f_long.shape[-1]) – list of interpolated longitudinal structure functions
gs (list, length = duration = g_long.shape[-1]) – list of interpolated transverse structure functions
- tflow.velocity.get_autocorrelation_tensor_iso(r_long, f_long, r_tran, g_tran, time)
Returns an autocorrelation tensor, assuming isotropy of the flow … not recommended for practical use due to long convergence time
- Parameters
r_long (numpy array) – output of get_two_point_vel_corr_iso()
f_long (numpy array) – output of get_two_point_vel_corr_iso()
r_tran (numpy array) – output of get_two_point_vel_corr_iso()
g_tran (numpy array) – output of get_two_point_vel_corr_iso()
time (numpy array) – time corresponding to the given autocorrelation functions
- Returns
rij – technically a function with arguments: i, j, r, t, udata (tensor indices, separation distance, time index, udata)
- Return type
autocorrelation tensor
- tflow.velocity.get_azimuthal_average(ef_nd, freqs, nkout=None, statistic='mean', mode='linear', cc=1.0)
Computes an azimuthal average of an nd array ef_nd …
- Parameters
ef_nd (nd array) –
freqs (a list/tuple of nd array) – … r = sqrt(freqs[0]**2 + freqs[1]**2 + … + freqs[-1]**2)
nkout (number of bins used to take statistsics) –
mode (str, choose from 'linear' or 'log') –
… this determines the width of the bins to be evenly spaced in a linear space or logarithmic space … i.e. bin edges will be like 0, 1, 2, 3, 4, … for the linear mode
bin edges will be like 10^0, 10^1, 10^2, 10^3, … for the logarithmic mode
cc (constant to be multiplied to the output) –
- Returns
fr_binned, ef1d, ef1d_err
- Return type
radius r, azimuthal average of e(r, theta, phi), standard deviation as a function of r
- tflow.velocity.get_binned_stats(arg, var, n_bins=100, mode='linear', statistic='mean', bin_center=True, return_std=False)
Make a histogram out of a pair of 1d arrays. … Returns arg_bins, var_mean, var_err … The given arrays could contain nans and infs. They will be ignored.
- Parameters
arg (1d array, controlling variable) –
var (1d array, data array to be binned) –
n_bins (int, default: 100) –
mode (str, deafult: 'linear') – If ‘linear’, var will be sorted to equally spaced bins. i.e. bin centers increase linearly. If ‘log’, the bins will be not equally spaced. Instead, they will be equally spaced in log. … bin centers will be like… 10**0, 10**0.5, 10**1.0, 10**1.5, …, 10**9
return_std (bool) – If True, it returns the STD of the statistics instead of the error = STD / np.sqrt(N)
- Returns
arg_bins (1d array, bin centers)
var_mean (1d array, mean values of data in each bin)
var_err (1d array, error of data in each bin) – … If return_std=True, it returns the STD of the statistics instead of the error = STD / np.sqrt(N)
- tflow.velocity.get_binned_stats2d(x, y, var, n_bins=100, nx_bins=None, ny_bins=None, bin_center=True, xmin=None, xmax=None, ymin=None, ymax=None)
Make a histogram out of a pair of 1d arrays. … Returns arg_bins, var_mean, var_err … The given arrays could contain nans and infs. They will be ignored.
- Parameters
x (2d array, control variable) –
y (2d array, control variable) –
var (2d array, data array to be binned) –
n_bins (int, default: 100) –
mode (str, deafult: 'linear') – If ‘linear’, var will be sorted to equally spaced bins. i.e. bin centers increase linearly. If ‘log’, the bins will be not equally spaced. Instead, they will be equally spaced in log. … bin centers will be like… 10**0, 10**0.5, 10**1.0, 10**1.5, …, 10**9
- Returns
xx_binned (2d array, bin centers about x)
yy_binned (2d array, bin centers about y)
var_mean (2d array, mean values of data in each bin)
var_err (2d array, standard error of data in each bin)
- tflow.velocity.get_binned_stats3d(x, y, z, var, n_bins=100, nx_bins=None, ny_bins=None, nz_bins=None, bin_center=True, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, return_count=False)
Make a histogram out of a trio of 1d arrays. … Returns arg_bins, var_mean, var_err … The given arrays could contain nans and infs. They will be ignored.
- Parameters
arg (1d array, controlling variable) –
var (1d array, data array to be binned) –
n_bins (int, default: 100) –
mode (str, deafult: 'linear') – If ‘linear’, var will be sorted to equally spaced bins. i.e. bin centers increase linearly. If ‘log’, the bins will be not equally spaced. Instead, they will be equally spaced in log. … bin centers will be like… 10**0, 10**0.5, 10**1.0, 10**1.5, …, 10**9
- Returns
xx_binned (3d array, bin centers about x)
yy_binned (3d array, bin centers about y)
var_mean (3d array, mean values of data in each bin)
var_err (3d array, standard error of data in each bin)
- tflow.velocity.get_center_of_energy(dpath, inc=10, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None)
Returns the center of energy (essentially the center of the blob)- (xc, yc, zc) using the TIME-AVERAGED ENERGY FIELD. - It computes the time-averaged energy from udatapath - Then, it computes the center of energy like the center of mass. (i.e. the energy density serves as a weight function)
- Parameters
dpath (str, path where velocity field data is stored) –
inc (int, it uses every inc-th frame of the data to compute the center of energy) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (z1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
- Returns
center_of_energy
- Return type
numpy array, center of energy for the time-avg-energy field
- tflow.velocity.get_center_of_vorticity(udata, xx, yy, sigma=5, sign='auto', x0=0, x1=None, y0=0, y1=None, thd=0)
Get the center of vorticity field … This computes the normalized, first moment of the vorticity field. … The center of field is not well-defined if values can be positive and negative …… To avoid this, the sign of the vorticity field must be specified. …… If sign=’auto’, the sign is automatically determined based on the average vorticity in the field. …… Otherwise, the sign must be specified as ‘positive’ or ‘negative’ …… The opposite vorticity will be considered to be zero.
- Parameters
udata (nd array, velocity field) –
xx (nd array, x-coordinates) –
yy (nd array, y-coordinates) –
sigma (int, default: 5, std of the gaussian kernel that is passed to ndimage.gaussian_filter()) –
sign (str, default: 'auto', 'positive' or 'negative') –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (y1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
thd (float, default: 0) – … |vorticity| < thd will be considered to be zero
- Returns
centers – … centers[0, t] = x-coordinate of the center of energy … centers[1, t] = y-coordinate of the center of energy
- Return type
nd array with shape (dim, duration), center of energy for each instantenous vorticity field
- tflow.velocity.get_characteristic_velocity(udata)
Return 1-component RMS velocity, u’ … energy = dim / 2 * u’^2
- Parameters
udata (nd array, velocity field) –
- Returns
u_irms
- Return type
1d array, 1-component RMS velocity
- tflow.velocity.get_confidence_levels_on_energy_spectrum(iw_wrt_eta, keta, alpha_min=0.1, slope=1.0, alpha_max=1.0, simple=True)
Returns the alpha values which reflects the confidence levels of the energy spectrum obtained from a velocity field generated by PIV experiments … Returned array can be used as alpha values. To plot values with varying alpha, use plt.scatter or graph.plot_with_varying_alphas. The latter allows to draw lines with different alpha values.
… path/to/module_dir/reference_data/error_functions_of_ek_args_iweta_keta.pkl contains an function which gives LOGARITHMIC ERROR of the spectrum (log10[Observed E(k) / True E(k)]) with arguments (interrogation window size / eta, keta)
- Parameters
iw_wrt_eta (float) –
- … interrogation window size with respect to Kolmogorov scale
i.e. (interrogation window size) / (Kolmogorov scale)
… here we assume that the interrogation window was a square.
keta (float) – … dimensionless waveumber of the energy spectrum (k times Kolmogorov scale)
simple (bool) –
- … If True, the returning alphas will be
[alpha_max, …, alpha_max, alpha_min, …, alpha_min, ]; alpha changes at keta = keta_c =2.*np.pi / (iw_wrt_eta * 2.)
- Returns
alphas
- Return type
list of alpha values
- tflow.velocity.get_confidence_levels_on_structure_function(iw_wrt_eta, reta, alpha_min=0.1, slope=2.0, alpha_max=1.0, simple=True)
Returns the alpha values which reflects the confidence levels of the second order longitudinal structure function obtained from a velocity field generated by PIV experiments … Returned array can be used as alpha values. To plot values with varying alpha, use plt.scatter or graph.plot_with_varying_alphas. The latter allows to draw lines with different alpha values.
… path/to/module_dir/reference_data/error_functions_of_dll_args_iweta_keta.pkl contains an function which gives a SIGNED RELATIVE ERROR of the spectrum (log10[Observed E(k) / True E(k)]) with arguments (interrogation window size / eta, keta) … You should non-dimensionalize the distance r and the two-pt correlation function by the most plausible dissipation rate!
You have two choices in experiments. … 1. Compute epsilon from the rate-of-strain tensor
… However, low resolution PIV could lead to poor estimation of epsilon 2. Compute epsilon such that the structure function exhibits a plateau at y=2.1 … The dissipation rate estimated by this method is more robust than the first method. (It also has its limitaions)
- Parameters
iw_wrt_eta (float) –
- … interrogation window size with respect to Kolmogorov scale
i.e. (interrogation window size) / (Kolmogorov scale)
… here we assume that the interrogation window was a square.
reta (float) – … dimensionless distance of the second-order structure function (r / Kolmogorov scale)
- Returns
alphas
- Return type
list of alpha values
- tflow.velocity.get_data_size_in_GB(data)
Returns the data size in GB
- tflow.velocity.get_dissipation_spectrum(udata, nu, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, nkout=None, window='flattop', correct_signal_loss=True, notebook=True)
Returns dissipation spectrum D(k) = 2 nu k^2 E(k) where E(k) is the 1d energy spectrum
- Parameters
udata (nd array) –
epsilon (nd array or float, default: None) – dissipation rate used for scaling energy spectrum If not given, it uses the values estimated using the rate-of-strain tensor
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of available window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
- Returns
D_k (numpy array) – Dissipation spectrum with shape (number of data points, duration)
D_k_err (numpy array) – Dissipation spectrum error with shape (number of data points, duration)
k1d (numpy array) – Wavenumber with shape (number of data points, duration)
- tflow.velocity.get_duidxj_tensor(udata, dx=1.0, dy=1.0, dz=1.0, xyz_orientations=array([1, - 1, 1]), xx=None, yy=None, zz=None)
Assumes udata has a shape (d, nrows, ncols, duration) or (d, nrows, ncols) … one can easily make udata by np.stack((ux, uy))
Important Warning: … udata is np.stack((ux, uy, uz)) … udata.shape = dim, nrows, ncols, duration :param udata: … assumes ux/uy/uz has a shape (nrows, ncols, duration) or (nrows, ncols, nstacks, duration)
… can handle udata without a temporal axis
- Parameters
dx (float, x spacing) –
dy (float, y spacing) –
dz (float, z spacing) –
xyz_orientations (1d array-like with shape (3,)) –
… xyz_orientations = [djdx, didy, dkdz] … HOW TO DETERMINE xyz_orientations:
- Does the xx[0, :] (or xx[0, :, 0] for 3D) monotonically increase as the index increases?
If True, djdx = 1 If False, djdx = -1
- Does the yy[:, 0] (or yy[:, 0, 0] for 3D) monotonically increase as the index increases?
If True, didy = 1 If False, didy = -1
- Does the zz[0, 0, :] monotonically increase as the index increases?
If True, dkdz = 1 If False, dkdz = -1
… If you are not sure what this is, use
… Factors between index space (ijk) and physical space (xyz)
- … This factor is necessary since the conventions used for the index space and the physical space are different.
Consider a 3D array a. a[i, j, k]. The convention used for this module is to interpret this array as a[y, x, z]. (In case of udata, udata[dim, y, x, z, t]) All useful modules such as numpy are written in the index space, but this convention is not ideal for physicists for several reasons. 1. many experimental data are not organized in the index space. 2. One always requires conversion between the index space and physical space especially at the end of the analysis. (physicists like to present in the units of physical units not in terms of ijk)
- … This array is essentially a Jacobian between the index space basis (ijk) and the physical space basis (xyz)
All information needed is just dx/dj, dy/di, dz/dk because ijk and xyz are both orthogonal bases. There is no off-diagonal elements in the Jacobian matrix, and one needs to supply only 3 elements for 3D udata. If I strictly use the Cartesian basis for xyz (as it should), then I could say they are both orthonormal. This makes each element of the Jacobian array to be either 1 or -1, reflecting the directions of +x/+y/+z with respect to +j/+i/+k
- Returns
sij –
- … idea is… sij[spacial coordinates, time, tensor indices]
e.g.- sij(x, y, t) = sij[y, x, t, i, j]
… sij = d ui / dxj
- Return type
numpy array with shape (nrows, ncols, duration, 2, 2) (dim=2) or (nrows, ncols, nstacks, duration, 3, 3) (dim=3)
- tflow.velocity.get_energy(udata)
Returns energy(
- ec{x}, t) of udata
… energy = np.nansum(udata**2, axis=0) / 2
udata: nd array
energy: nd array
- tflow.velocity.get_energy_spectra_jhtd()
Returns values to plot energy spectrum from JHTD, computed by Takumi in 2019 Call get_rescaled_energy_spectra_jhtd for scaled energy spectra.
- Returns
datadict – data stored is stored in ‘/reference_data/jhtd_e_specs.h5’
- Return type
dict
- tflow.velocity.get_energy_spectrum(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, nkout=None, window=None, correct_signal_loss=True, remove_undersampled_region=True, cc=1, notebook=True, mode='linear', dealiasing=True, padding_mode='edge', padding_kwargs={}, debug=False)
Returns an energy spectrum from velocity field data … The algorithm implemented in this function is VERY QUICK because it does not use the two-point autorcorrelation tensor. … Instead, it converts u(kx, ky, kz)u*(kx, ky, kz) into u(kr)u*(kr). (here * dentoes the complex conjugate) … CAUTION: Must provide udata with aspect ratio ~ 1 …… The conversion process induces unnecessary error IF the dimension of u(kx, ky, kz) is skewed. …… i.e. Make udata.shape like (800, 800), (1024, 1024), (512, 512) for accurate results. … KNOWN ISSUES: …… This function returns a bad result for udata with shape like (800, 800, 2)
- Parameters
udata (nd array) –
epsilon (nd array or float, default: None) – dissipation rate used for scaling energy spectrum If not given, it uses the values estimated using the rate-of-strain tensor
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
window (str, a name of the windowing function) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of applying window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool, default: True) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
cc (float, default: 1.75) – A numerical factor to compensate for the signal loss due to approximations. … cc=1.75 was obtained from the JHTD data.
- Returns
e_k (numpy array) – Energy spectrum with shape (number of data points, duration)
e_k_err (numpy array) – Energy spectrum error with shape (number of data points, duration)
kk (numpy array) – Wavenumber with shape (number of data points, duration)
- tflow.velocity.get_energy_spectrum_nd(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, window=None, correct_signal_loss=True, return_in='wavenumber', dealiasing=True, padding_mode='edge', padding_kwargs={})
Returns ukdata * np.conjugate(ukdata) where ukdata is the ND-Fourier Transform of udata … :param udata: :type udata: nd array that contains a velocity field with a shape (dim, y, x, (z), duration) :param x0: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type x0: int, default: 0 :param x1 int: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type x1 int: None :param default: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type default: None :param y0 int: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type y0 int: 0 :param default: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type default: 0 :param y1 int: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type y1 int: None :param default: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type default: None :param z0 int: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type z0 int: 0 :param default: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type default: 0 :param z1 int: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type z1 int: None :param default: … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1]) :type default: None :param dx: :type dx: float, spacing of the x-grid :param dy: :type dy: float, spacing of the y-grid :param dz: :type dz: float, spacing of the z-grid :param window: :type window: str, :param correct_signal_loss: :param return_in: … wavenumber:=2pi/L, freq:=1/L :type return_in: str, Choose from ‘wavenumber’ and ‘freq’
- Returns
… If return_in=’’wavenumber’, it returns norm of ND-CFT of velocity field as a function of wavenumber (2pi/x) instead of frequency (1/x)
- Return type
ef_nd, np.asarray([fxx, fyy, fzz])
- tflow.velocity.get_energy_spectrum_nd_old(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, window=None, correct_signal_loss=True)
DEPRECATED: TM cleaned up the code, and improved the literacy and transparency of the algorithm- TM (Sep 2020) … Please use the updated function: get_energy_spectrum_nd() … the new function correctly returns the SPECTRAL DENSITY. T …… This code might contain minor errors (like a factor of 2pi). The new code has no such ambiguity.
Returns nd energy spectrum from velocity data (FFT of a velocity field)
- Parameters
udata (nd array) –
dx (float) –
dy (float) –
dz (float) –
dx – spacing in x
dy – spacing in y
dz – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of applying window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool, default: True) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
- Returns
energy_fft (nd array with shape (height, width, duration) or (height, width, depth, duration))
ks (nd array with shape (ncomponents, height, width, duration) or (ncomponents, height, width, depth, duration))
Example
nx, ny = 100, 100 x = np.linspace(0, 2*np.pi, nx) y = np.linspace(0, 4*np.pi, ny) dx, dy = x[1]- x[0], y[1]-y[0]
# Position grid xx, yy = np.meshgrid(x, y)
# In Fourier space, energy will have a peak at (kx, ky) = (+/- 5, +/- 2) ux = np.sin(2.5*xx + yy) uy = np.sin(yy) * 0 udata_test = np.stack((ux, uy)) ek, ks = get_energy_spectrum_nd(udata_test, dx=dx, dy=dy) graph.color_plot(xx, yy, (ux**2 + uy**2 ) /2., fignum=2, subplot=121) fig22, ax22, cc22 = graph.color_plot(ks[0], ks[1], ek.real[…, 0], fignum=2, subplot=122, figsize=(16, 8)) graph.setaxes(ax22, -10, 10, -10, 10)
- tflow.velocity.get_energy_spectrum_nd_ver2(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, window=None, correct_signal_loss=True, return_in='spectral density')
Returns ND energy spectrum from velocity data (FFT of a velocity field) … Returns the SPECTRUM DENSITY not power (integrated spectral density) … Few Important Tips:
- … np.fft.fft() returns POWER not spectrum density
- … If you want to check Parseval’s theorem, you must use the POWER not SPECTRAL DENSITY
- Parseval’s theorem:
ukdata = np.fft.fft(udata, axis=(1, dim+1) 1/n_samples * np.nansum( ukdata * np.conjucate(ukdata)) ) = np.nansum(udata ** 2)
… np.fft.fft() returns the DFT in frequency space (NOT ANGULAR FREQUENCY space) … To convert the power (DFT output) to spectral density, one must do following.
ukdata /= (dfx * dfy * dfz) * n_samples
… where dfx = 1 / dx, etc. and n_samples is the number of samples actually discrete-fourie transformed.
- Parameters
udata (nd array) –
dx (float) –
dy (float) –
dz (float) –
dx – spacing in x
dy – spacing in y
dz – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of applying window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool, default: True) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
- Returns
energy_fft (nd array with shape (height, width, duration) or (height, width, depth, duration))
ks (nd array with shape (ncomponents, height, width, duration) or (ncomponents, height, width, depth, duration))
Example
nx, ny = 100, 100 x = np.linspace(0, 2*np.pi, nx) y = np.linspace(0, 4*np.pi, ny) dx, dy = x[1]- x[0], y[1]-y[0]
# Position grid xx, yy = np.meshgrid(x, y)
# In Fourier space, energy will have a peak at (kx, ky) = (+/- 5, +/- 2) ux = np.sin(2.5*xx + yy) uy = np.sin(yy) * 0 udata_test = np.stack((ux, uy)) ek, ks = get_energy_spectrum_nd(udata_test, dx=dx, dy=dy) graph.color_plot(xx, yy, (ux**2 + uy**2 ) /2., fignum=2, subplot=121) fig22, ax22, cc22 = graph.color_plot(ks[0], ks[1], ek.real[…, 0], fignum=2, subplot=122, figsize=(16, 8)) graph.setaxes(ax22, -10, 10, -10, 10)
- tflow.velocity.get_energy_spectrum_old(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, nkout=None, window=None, correct_signal_loss=True, remove_undersampled_region=True, cc=1.75, notebook=True)
DEPRECATED: TM cleaned up the code, and improved the literacy and transparency of the algorithm- TM (Sep 2020)
Returns 1D energy spectrum from velocity field data … The algorithm implemented in this function is VERY QUICK because it does not use the two-point autorcorrelation tensor. … Instead, it converts u(kx, ky, kz)u*(kx, ky, kz) into u(kr)u*(kr). (here * dentoes the complex conjugate) … CAUTION: Must provide udata with aspect ratio ~ 1 …… The conversion process induces unnecessary error IF the dimension of u(kx, ky, kz) is skewed. …… i.e. Make udata.shape like (800, 800), (1024, 1024), (512, 512) for accurate results. … KNOWN ISSUES: …… This function returns a bad result for udata with shape like (800, 800, 2)
- Parameters
udata (nd array) –
epsilon (nd array or float, default: None) – dissipation rate used for scaling energy spectrum If not given, it uses the values estimated using the rate-of-strain tensor
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of applying window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool, default: True) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
remove_undersampled_region (bool, default: True) – If True, it will not sample the region with less statistics.
cc (float, default: 1.75) – A numerical factor to compensate for the signal loss due to approximations. … cc=1.75 was obtained from the JHTD data.
- Returns
e_k (numpy array) – Energy spectrum with shape (number of data points, duration)
e_k_err (numpy array) – Energy spectrum error with shape (number of data points, duration)
kk (numpy array) – Wavenumber with shape (number of data points, duration)
- tflow.velocity.get_energy_spectrum_ver2(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, nkout=None, window=None, correct_signal_loss=True, remove_undersampled_region=True, cc=1, notebook=True, debug=False)
Returns 1D energy spectrum from velocity field data … The algorithm implemented in this function is VERY QUICK because it does not use the two-point autorcorrelation tensor. … Instead, it converts u(kx, ky, kz)u*(kx, ky, kz) into u(kr)u*(kr). (here * dentoes the complex conjugate) … CAUTION: Must provide udata with aspect ratio ~ 1 …… The conversion process induces unnecessary error IF the dimension of u(kx, ky, kz) is skewed. …… i.e. Make udata.shape like (800, 800), (1024, 1024), (512, 512) for accurate results. … KNOWN ISSUES: …… This function returns a bad result for udata with shape like (800, 800, 2)
- Parameters
udata (nd array) –
epsilon (nd array or float, default: None) – dissipation rate used for scaling energy spectrum If not given, it uses the values estimated using the rate-of-strain tensor
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of applying window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool, default: True) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
remove_undersampled_region (bool, default: True) – If True, it will not sample the region with less statistics.
cc (float, default: 1.75) – A numerical factor to compensate for the signal loss due to approximations. … cc=1.75 was obtained from the JHTD data.
- Returns
e_k (numpy array) – Energy spectrum with shape (number of data points, duration)
e_k_err (numpy array) – Energy spectrum error with shape (number of data points, duration)
kk (numpy array) – Wavenumber with shape (number of data points, duration)
- tflow.velocity.get_enstrophy(udata, dx=1.0, dy=1.0, dz=1.0, xx=None, yy=None, zz=None)
Returns enstrophy(
- ec{x}, t) of udata
… enstropy = omega ** 2 … omega = curl(udata)
udata: nd array dx: float
data spacing along x
- dy: float
data spacing along y
- dz: float
data spacing along z
enstrophy: nd array
- tflow.velocity.get_enstrophy_spectrum(udata, sigma=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, xx=None, yy=None, zz=None, nkout=None, window=None, correct_signal_loss=True, cc=1, notebook=True, mode='linear', dealiasing=True, padding_mode='edge', padding_kwargs={}, debug=False)
Compute the enstrophy spectrum from a velocity field (udata)
… CAUTION: Must provide udata with aspect ratio ~ 1 …… The conversion process induces unnecessary error IF the dimension of u(kx, ky, kz) is skewed. …… i.e. Make udata.shape like (800, 800), (1024, 1024), (512, 512) for accurate results. … KNOWN ISSUES: …… This function returns a bad result for a highly skewed udata with shape like (dim, 800, 800, 2, duration)
- Parameters
udata (ndarray, a velocity field) –
sigma (float, the standard deviation of the Gaussian kernel) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
window (str, a name of the windowing function) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of applying window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool, default: True) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
cc (float, default: 1) – … an arbitrary constant to scale the enstrophy spectrum … this is used to mimic 1D enstrophy spectrum from a 3D spectrum.
xx (ndarray, x-coordinates of the data, used to compute vorticity (Passng xx/yy/zz is recommended rather than passing dx, dy, dz)) –
yy (ndarray, y-coordinates of the data, used to compute vorticity (Passng xx/yy/zz is recommended rather than passing dx, dy, dz)) –
zz (ndarray, z-coordinates of the data, used to compute vorticity (Passng xx/yy/zz is recommended rather than passing dx, dy, dz)) –
notebook –
mode (str, default: 'linear') – … ‘linear’ or ‘log’ … sampling of the energy spectrum will be conducted with bins that are linearly/logarithmically spaced
dealiasing (if True, it pads the data with zeros to make the array square to mitigate aliasing effects..) –
padding_mode (str, default: 'edge') – … arguments are passed to np.pad(array, pad_width, padding_mode, **kwargs)
padding_kwargs – … keyword arguments for np.pad()
debug (bool, default: False) – … If True, it prints out the result of a sanity check based on the Parseval’s theorem. … It checks identity at t=0: <omega_i omega_i> = int_0^infty P(k)dk at t0=0
- Returns
enst_k (2d array, 3D enstrophy spectrum) – … (nkout, duration)
enst_k_err (2d array, standard error of enstrophy spectrum) – … (nkout, duration)
kk (1d array) – … k-values of the enstrophy spectrum
- tflow.velocity.get_enstrophy_spectrum_nd(udata, sigma=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, xx=None, yy=None, zz=None, window=None, correct_signal_loss=True, return_in='wavenumber', dealiasing=True, padding_mode='edge', padding_kwargs={})
- Compute enstrophy spectrum of a 2/3D data.
… omegak * np.conjugate(omegak)
- Parameters
udata (nd array, velocity field (dim, height, width, (depth), duration)) –
sigma (float, Standard deviation for Gaussian kernel) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
window (str, a name of the windowing function) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of applying window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool, default: True) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
return_in (str, default: 'wavenumber') –
- … the returning power will be in the units of
’wavenumber’:(1/s^2) * (rad/m)^3 ‘frequency’: (1/s^2) * (1/m)^3
… ‘wavenumber’: 2pi / L … ‘frequency’: 1 / L
dealiasing (if True, it pads the data with zeros to make the array square to mitigate aliasing effects..) –
padding_mode (str, default: 'edge') – … arguments are passed to np.pad(array, pad_width, padding_mode, **kwargs)
padding_kwargs – … keyword arguments for np.pad()
- Returns
ef_nd (nd array, enstrophy power density(dim, ky, kx, kz, duration)) – … If return_in=’’wavenumber’, it returns norm of ND-CFT of velocity field as a function of wavenumber (2pi/x) instead of frequency (1/x)
OPTIONAL
ky, kx, kz (nd array, wavenumber(ky, kx, kz) = 2pi/L) – or
fy, fx, fz (nd array, frequency(fy, fx, fz) = 1/L)
- tflow.velocity.get_epsilon_from_1d_spectrum(udata, k='kx', dx=1.0, dy=1.0, c1=0.491, r=(1.0, inf), **kwargs)
Returns a dissipation rate from a 1D energy spectrum How it works:
- Since
E11=c1 epsilon^(2/3) k^(-5/3) in the inertial subrange,
- then
epsilon = (E11/ (c1 k^(-5/3)))^(3/2)
- Parameters
udata (nd array with shape (dim, nrows, ncols, duration)) –
k (str, 'kx' or 'ky', the direction along which the 1D spectrum is computed) –
dx (float, spacing along x) –
dy (float, spacing along y) –
c1 (kolmogorov constant for E11=c1 epsilon^(2/3) k^(-5/3)) –
r (tuple, (r0, r1)) – … (r0, r1) defines a inertial subrange
kwargs (keyword arguments passed to get_1d_energy_spectrum()) –
- Returns
epsilons (1d array with shape (duration, ))
epsilon_stds (1d array with shape (duration, ), std of the dissipation rate (std of the n largest values of f(r)))
- tflow.velocity.get_epsilon_iso(udata, x=None, y=None, lambda_f=None, lambda_g=None, nu=1.004, x0=0, x1=None, y0=0, y1=None, **kwargs)
Return dissipation rate (epsilon) computed by isotropic formula involving Taylor microscale Isotropic formula: … epsilon = 30. * nu * u2_irms / (lambda_f ** 2) … epsilon = 15. * nu * u2_irms / (lambda_g ** 2)
How it works: … if Taylor microscales (lambdas) are not provided, then it attempts to compute them from udata. … If either or both of lambda_f and lambda_g are provided, then it uses them.
- Parameters
udata (nd array, a velocity field (dim, nrows, ncols, nstacks, duration)) –
x (2d array, x coordinates- get x from get_udata_from_path(dpath, return_xy=True)) –
y (2d array, y coordinates- get y from get_udata_from_path(dpath, return_xy=True)) –
lambda_f (float/1d array, longitudinal two-point correlation function) –
lambda_g (float/1d array, transverse two-point correlation function) –
nu (float, viscosity, default: 1.004) –
x0 (int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]) –
x1 (int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]) –
y0 (int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]) –
y1 (int, index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]) –
kwargs (dict, optional) –
provided (... passed to get_two_point_vel_corr_iso() if lambda_f and lambda_g are not) –
- Returns
epsilon (float/1d array with shape (duration,))
… dissipation rate
- tflow.velocity.get_epsilon_local_using_sij(udata, dx=None, dy=None, dz=None, nu=1.004, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, xx=None, yy=None)
Returns the local dissipation rate computed using the rate-of-strain tensor … epsilon(x, y, z, t) = 2 * nu * sij(x, y, z, t) sij(x, y, z, t)
sij: numpy array with shape (nrows, ncols, duration, 2, 2) (dim=2) or (nrows, ncols, nstacks, duration, 3, 3) (dim=3) … sij[spacial coordinates, time, tensor indices]
e.g.- sij(x, y, t) can be accessed by sij[y, x, t, i, j]
… sij = d ui / dxj
- … To compute epsilon, it uses a formula from Hinze (1975)
… epsilon_spatial = 6. * nu * (epsilon_0 + epsilon_1 + epsilon_2) # Hinze, 1975, eq. 3-98
- Parameters
udata (nd array) –
nu (flaot, kinematic viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
xx (2d/3d array, x-coordinate of the data) –
yy (2d/3d array, y-coordinate of the data) –
zz (2d/3d array, z-coordinate of the data) –
- Returns
epsilon_spatial – … dissipation rate with shape (nrows, ncols, (nstacks), duration)
- Return type
numpy array
- tflow.velocity.get_epsilon_using_diss_spectrum(udata, nu=1.0034, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=1, dy=1, dz=1, nkout=None, notebook=True)
Returns dissipation rate computed by integrated the dissipation specrtrum … must have a fully resolved spectrum to yield a reasonable result
- Parameters
udata (nd array) –
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
- Returns
epsilon – dissipation rate
- Return type
numpy array
- tflow.velocity.get_epsilon_using_sij(udata, dx=None, dy=None, dz=None, nu=1.004, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None)
Returns the dissipation rate computed using the rate-of-strain tensor
sij: numpy array with shape (nrows, ncols, duration, 2, 2) (dim=2) or (nrows, ncols, nstacks, duration, 3, 3) (dim=3) … idea is… sij[spacial coordinates, time, tensor indices]
e.g.- sij(x, y, t) can be accessed by sij[y, x, t, i, j]
… sij = d ui / dxj :param udata: :type udata: nd array :param nu: :type nu: flaot, viscosity :param x0: index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. :type x0: int :param x1: index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. :type x1: int :param y0: index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. :type y0: int :param y1: index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. :type y1: int :param t0: index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. :type t0: int :param t1: index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1]. :type t1: int :param dx: spacing in x :type dx: float :param dy: spacing in y :type dy: float :param dz: spacing in z :type dz: float
- Returns
epsilon – dissipation rate
- Return type
numpy array
- tflow.velocity.get_epsilon_using_struc_func(dll, r_dll, c=2.1, p=2.0, n=5)
Estimates dissipation rate based on the plateau of the rescaled structure funciton … Structure function D = c(epsilon r)^{p/3} in the inertial subrage, ignoring the intermittency correction
Let f be f(r)=(D/c)^{3/p} / r. Then, f(r)= epsilon where r is in the inertial subrange. This is essentially the value at the plateau. … This function grabs the n largest values of f(r), and considers its average as a dissipation rate.
- Parameters
dll (nd array with shape (m, duration)) – … the p-th order structure function … one of the outputs of get_structure_function()
r_dll (nd array with shape (m, duration)) – … separation length for the structure function (correlation function of the velocity difference)
c (float, default:2.1 (applicable to p=2)) – … Kolmogorov constant for the p-th order structure function … c=2.1 (p=2, experiment), c=-4/5 (p=3, theory)
p (float, order of the structure function) – … the order of the structure function
n (int) – … number of structure peaks of f(r) used to estimate the dissipation rate
- Returns
epsilons (1d array with shape (duration, ), dissipation rate (mean of the n largest values of f(r)))
epsilon_stds (1d array with shape (duration, ), std of the dissipation rate (std of the n largest values of f(r)))
- tflow.velocity.get_epsilon_using_struc_func_old(rrs, Dxxs, epsilon_guess=100000, r0=1.0, r1=10.0, p=2, method='Nelder-Mead')
[DEPRICATED] Returns the values of estimated dissipation rate using a long. structure function
- Parameters
rrs (numpy array) – separation length for long. transverse function
Dxxs (numpy array) – values of long. transverse function
epsilon_guess (numpy array) – initial guess for dissipation rate
r0 (float) – The scaled structure function is expected to have a plateau [r0, r1]
r1 (float) – The scaled structure function is expected to have a plateau [r0, r1]
p (float/int) – order of structure function … smaller order is better due to intermittency
method (str, default: 'Nelder-Mead') – method used to find the minimum of the test function
- Returns
epsilons – estimated dissipation rate
- Return type
numpy array
- tflow.velocity.get_equally_spaced_grid(udata, d=1)
Returns an evenly spaced grid for the given udata
- Parameters
udata (nd array, v-field data) –
d (spacing of the grid) –
- Returns
xx, yy, (zz)
- Return type
2D or 3D numpy arrays
- tflow.velocity.get_equally_spaced_kgrid(udata, d=1)
Returns a equally spaced grid to plot FFT of udata
- Parameters
udata –
dx (spacing of the grid in the real space) –
- Returns
kxx, kyy, (kzz)
- Return type
2D or 3D numpy arrays
- tflow.velocity.get_flow_about_a_lifting_cylinder(xx, yy, xc=0, yc=0, u=1, a=1, beta=- 0.7853981633974483, return_in_xy_basis=True)
Returns a flow (udata) about a lifting cylinder
- Parameters
xx (2d array, x-coordinates) –
yy (2d array, y-coordinates) –
xc (float, default: 0, x-coordinate of cylinder) –
yc (float, default: 0, y-coordinate of cylinder) –
u (float, default: 1, magnitude of the stream velocity) –
a (radius of cylinder) –
beta (angle of the stream) –
return_in_xy_basis (bool, default: True, if True, returns udata in cartesian coordinates) – … if return_in_xy_basis=False, returns udata in polar coordinates
- Returns
psi
- Return type
2d array, streamfunction values
- tflow.velocity.get_flow_past_a_circular_cylinder(xx, yy, xc=0, yc=0, u=1.0, a=1.0, return_in_xy_basis=True)
Returns udata (ux, uy) of a flow past a circular cylinder in Stokes limit
- Parameters
xx (2d array, x-coordinates) –
yy (2d array, y-coordinates) –
xc (float, default: 0, x-coordinate of cylinder) –
yc (float, default: 0, y-coordinate of cylinder) –
U (float, default: 1, magnitude of the stream velocity) –
a (radius of cylinder) –
return_in_xy_basis (bool, default: True, if True, returns udata in cartesian coordinates) – … if return_in_xy_basis=False, returns udata in polar coordinates
- Returns
psi
- Return type
2d array, streamfunction values
- tflow.velocity.get_grid_spacing(xx, yy, zz=None)
Returns the spacing of the grid
Index i, j, k corresponds to physical space y, x, z … x = xx[0, :, (0, optional)] … y = yy[:, 0, (0, optional)] … z = zz[0, 0, :]
- Parameters
xx (2d/3d array, a grid of x-coordinates) –
yy (2d/3d array, a grid of y-coordinates) –
zz (2d/3d array, a grid of z-coordinates) –
- Returns
dx, dy, dz
- Return type
floats, spacing of the grid along each axis
- tflow.velocity.get_h5_keys(dpath)
Returns a list of dataset names in h5- only the datasets stored under the top … /Dataset1, /Dataset2, … -> Returns [“Dataset1”, “Dataset2”]
- tflow.velocity.get_h5_subkeys(dpath, key)
Returns a list of dataset names in h5- only the datasets stored under /key … key/Dataset1, key/Dataset2, … -> Returns [“Dataset1”, “Dataset2”]
- tflow.velocity.get_hamming_window_radial(xx, yy, zz=None, rmax=None, duration=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None)
- Returns the Hamming window as a function of radius
… r = 0 corresponds to the center of the window.
- Parameters
r (nd array) –
point (... radius from the center) –
rmax (float) –
... –
duration (int) –
None (... if) –
(height (this returns) –
width) –
(height –
width –
depth) –
Otherwise (...) –
(height –
width –
duration) –
(height –
width –
depth –
duration) –
purposes. (... duration = udata.shape[-1] should work for most of) –
- Returns
window/windows (nd array)
… window (hamming window with the shape as xx)
… window (hamming window with the shape (xx.shape[:], duration))
- tflow.velocity.get_helicity(udata, xx, yy, zz, crop=2)
(For 3D velocity field) Returns a scalar field such that u dot omega
- Parameters
udata (4d/5d array, v-field data with shape (3, h, w, d) or (3, h, w, d, t)) –
xx (3d array) –
yy (3d array) –
zz (3d array) –
crop (int, >0 or None) – … it replaces the values near the edges to np.nan because omega often behaves ill near the edges … helicity_density[crop:-crop, crop:-crop, crop:-crop, :] = np.nan[crop:-crop, crop:-crop, crop:-crop, :] = np.nan
- Returns
helicity
- Return type
1d array, shape (duration.)
- tflow.velocity.get_helicity_density(udata, xx, yy, zz, crop=2)
Returns helicity density u cdot omega … :param udata: :type udata: (4d or 5d) array, 3d velocity field (components(ux, uy, uz), x, y, z, t) :param xx: :type xx: 3d array :param yy: :type yy: 3d array :param zz: :type zz: 3d array :param crop: … it replaces the values near the edges to np.nan because omega often behaves ill near the edges
… helicity_density[crop:-crop, crop:-crop, crop:-crop, :] = np.nan[crop:-crop, crop:-crop, crop:-crop, :] = np.nan
- Returns
helicity_density
- Return type
4d array (x, y, z, t)
- tflow.velocity.get_impulse(udata, xx, yy, zz=None, rho=0.001, crop=2, keep=None, R=None, xc=0, yc=0, zc=0)
Returns the hydrodynamic impulse inside the region defined by xx, yy, zz … Consider the momentum contained in a simply connected domain G.
(total fluid momentum in G) = (hydrodynamic impulse in G) + (surface terms) … Saffman “Vortex Dynamics” Ch. 3.3 Eq 13
… it returns an array of a shape (duration, )
- Parameters
udata (4d/5d array, v-field data with shape (3, h, w, d) or (3, h, w, d, t)) –
xx (3d array, positional grid about x) –
yy (3d array, positional grid about y) –
zz (3d array, positional grid about z) –
rho (fluid density, default 1e-3 g/mm3) –
crop (int, crop the domain near the edge to remove the boundary effects) –
keep (boolean array, indices of the points to keep) –
R (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
xc (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
yc (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
zc (float, if given, it gives the impulse inside a sphere of radius R centered at (xc, yc, zc)) –
- Returns
hydrodynamic impulse, (optional
- Return type
bulk term, surface term): 2d array (components, duration)
- tflow.velocity.get_impulse_density(udata, xx, yy, zz=None, rho=0.001, crop=2)
It returns the density of hydrodynamic impulse hydrodynamic impulse is defined as … P = 0.5 [ int r imes omega dV + int r imes (n imes u) dS]
= (Bulk term) + (Surface Term)
- … It is best understood when this form is differentiated
dP/dt = (bulk force like gravity) + (surface force: f_i = sigma_ij n_j where sigma is viscous stress tensor)
- Parameters
udata (nd array, a 3D velocity field (3, h, w, d, (t: optional))) –
xx (3d grid, x-coordinate of the udata) –
yy (3d grid, y-coordinate of the udata) –
zz (3d grid, z-coordinate of the udata) –
rho (density of fluid, default: 0.001 (g/mm^3 for water)) –
crop (int, greater or equal to 0) – … Sets the values of omega near the edge to np.nan
- Returns
hi
- Return type
5d array: hydrodynamic impulse density (3, y, x, z, t)
- tflow.velocity.get_instantaneous_center_of_energy(udata, xx, yy, zz=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None)
This function calculates the center of energy from the instantaneous energy field.
- Parameters
udata (nd array with shape (dim, width, height, (depth), (duration))) –
xx (nd array with shape (width, height, (depth))) –
yy (nd array with shape (width, height, (depth))) –
zz (nd array with shape (width, height, (depth)) (optional)) –
x0 (int, index used to define the x-range of the v-field: udata[:, y0:y1, x0:x1, z0:z1, ...]) –
x1 (int, index used to define the x-range of the v-field: udata[:, y0:y1, x0:x1, z0:z1, ...]) –
y0 (int, index used to define the x-range of the v-field: udata[:, y0:y1, x0:x1, z0:z1, ...]) –
y1 (int, index used to define the x-range of the v-field: udata[:, y0:y1, x0:x1, z0:z1, ...]) –
z0 (int, index used to define the x-range of the v-field: udata[:, y0:y1, x0:x1, z0:z1, ...]) –
z1 (int, index used to define the x-range of the v-field: udata[:, y0:y1, x0:x1, z0:z1, ...]) –
- Returns
centers – … centers[0, t] = x-coordinate of the center of energy … centers[1, t] = y-coordinate of the center of energy
- Return type
nd array with shape (dim, duration), center of energy for each instantenous energy field
- tflow.velocity.get_integral_scale_large_eddy(udata, epsilon)
dissipation rate (epsilon) is known to be proportional to u’^3 / L.
Some just define an integral scale L as u’^3 / epsilon. This method just returns this ratio. It is often interpreted as the characteristic scale of large eddies.
- Parameters
udata (numpy array) –
epsilon (numpy array / float) – dissipation rate
- Returns
L – integral length scale (characterisic size of large eddies)
- Return type
numpy array
- tflow.velocity.get_integral_scales(r_long, f_long, r_tran, g_tran, method='trapz')
Returns integral scales computed by using autocorrelation functions … To have a meaningful result, the autocorrelation functions must be fully resolved.
- Parameters
r_long (numpy array) – … output of get_two_point_vel_corr_iso(…)
array (g_tran numpy) – … output of get_two_point_vel_corr_iso(…)
array – … output of get_two_point_vel_corr_iso(…)
array – … output of get_two_point_vel_corr_iso(…)
method (string, default: 'trapz') – … integration method, choose from quadrature or trapezoidal
- Returns
L11 (numpy array) – longitudinal integral length scale
L22 (numpy array) – transverse integral length scale
- tflow.velocity.get_integral_scales_all(udata, dx, dy, dz=None, nu=1.004)
Returns integral scales of turbulence … L = u_irms ** 3 / epsilon … U = u_irms … T = L/U # :param udata: :type udata: numpy array :param dx: data spacing in x :type dx: float :param dy: data spacing in y :type dy: float :param dz: data spacing in z :type dz: float :param nu: viscosity :type nu: float
- Returns
L_le (1d array, integral length scale: u_irms * 3 / epsilon*)
u_L (1d array: characteristic velocity, characteristic velocity)
tau_L (1d array: large eddy turnover time, L_le / u_L)
- tflow.velocity.get_integral_scales_iso_spec(udata, e_k, k)
Integral scale defined through energy spectrum. … Assumes isotropy and a full 1D energy spectrum. Pope 6.260. … To have a meaningful result, the energy spectrum must be fully resolved.
- Parameters
udata –
e_k (numpy array) – output of get_energy_spectrum()
k (numpy array) – output of get_energy_spectrum()
- Returns
L_iso_spec
- Return type
1d array
- tflow.velocity.get_integral_scales_using_rij(udata, Rij, rmax, n=100)
[DEPRICATED- computing the autocorrelation tensor could be time-consuming] Use autocorrelation tensor, Rij to calculate integral length scale
- Parameters
udata –
Rij (numpy array) – two-point velocity autocorrelation tensor … can be obtained by get_two_point_vel_corr_iso(…) but may take a long time
rmax (float) –
n (int) – The higher n is, the integrand function becomes more smooth
- Returns
L11 (nd array) – … longitudinal integral length scale
L22 (nd array) – … transverse integral length scale
- tflow.velocity.get_integral_velocity_scale(udata)
Return integral velocity scale- identical to u’ (characteristic velocity) .. See get_characteristic_velocity() for more details
- Parameters
udata (numpy array) –
- Returns
u_irms
- Return type
See get_characteristic_velocity()
- tflow.velocity.get_intersecting_vertices(xxx, yyy, zzz, a, b, c, x0, y0, z0)
Returns the vertices of intercetion between a plane and a cuboidal volume … the plane is defined by the equation ax + by + cz = a*x0+ b*y0 + c*z0 = d …… Note that the normal of the plane is parallel to (a, b, c) … the cuboidal volume is defined by (xxx, yyy, zzz) :param xxx: :type xxx: 3d array, x coordinates of the cuboidal volume :param yyy: :type yyy: 3d array, y coordinates of the cuboidal volume :param zzz: :type zzz: 3d array, z coordinates of the cuboidal volume :param a: :type a: float, x-coefficient of the plane :param b: :type b: float, y-coefficient of the plane :param c: :type c: float, z-coefficient of the plane :param x0: :type x0: float, x-coordinate of the point on the plane :param y0: :type y0: float, y-coordinate of the point on the plane :param z0: :type z0: float, z-coordinate of the point on the plane
- Returns
verts
- Return type
(n, 3) array, coordinates of the vertices of intersection
- tflow.velocity.get_jacobian_xyz_ijk(xx, yy, zz=None)
Returns diagonal elements of Jacobian between index space basis and physical space … This returns xyz_orientations for get_duidxj_tensor(). … Further details can be found in the docstring of get_duidxj_tensor()
- Parameters
xx (2d/3d array, a grid of x-coordinates) –
yy (2d/3d array, a grid of y-coordinates) –
zz (2d/3d array, a grid of z-coordinates) –
- Returns
jacobian – … expected input of xyz_orientations for get_duidxj_tensor
- Return type
1d array
- tflow.velocity.get_kgrids(height, width, depth=None, dx=1.0, dy=1.0, dz=1.0, shift=True)
Returns 2d/3d wavenumber grids of an array which is FFT-ed
- tflow.velocity.get_kolmogorov_scale(udata, dx, dy, dz=None, nu=1.004)
Returns kolmogorov LENGTH scale … estimates dissipation rate from the rate-of-strain tensor … eta = (nu ** 3 / epsilon) ** 0.25
- Parameters
udata (numpy array, a velocity field) –
dx (float) – data spacing in x
dy (float) – data spacing in y
dz (float, optional) – data spacing in z
nu (float) – viscosity
- Returns
eta – kolmogorov length scale
- Return type
numpy array
- tflow.velocity.get_kolmogorov_scales_all(udata, dx, dy, dz, nu=1.004)
Returns Kolmogorov scales (Length, Velocity, Time) based on udata and dissipation rate
- Parameters
udata (numpy array) –
dx (float) – data spacing in x
dy (float) – data spacing in y
dz (float) – data spacing in z
nu (float) – viscosity
- Returns
eta (1d array)
u_eta (1d array)
tau_eta (1d array)
- tflow.velocity.get_kurtosis(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None)
Computes kurtosis of a given velocity field … DO NOT USE scipy.stats.kurtosis()- which computes skewness in the language of probability … i.e. probabilistic skewness is defined through its probabilistic moments (X-E[X])^n … In turbulence, kurotsis is defined using the DERIVATIVES of turbulent velocity … In turbulence, kurtosis is approximately 7.2 according to Kambe
- Parameters
udata (nd array, a velocity field) –
x0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
x1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
y0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
y1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
z0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
z1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
t0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
t1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
- Returns
kurtosis
- Return type
1d array
- tflow.velocity.get_large_scale_vel_field(udata, kmax, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, window=None, dx=None, dy=None, dz=None)
Returns a velocity field which satisfies k = sqrt(kx^2 + ky^2) < kmax in the original field (udata)
- Parameters
udata (nd array) –
components (... velocity field data with shape (# of) –
depth) (physical dimensions (width x height x) –
duration) –
kmax (float) –
filter (... value of k below which spectrum is kept. i.e. cutoff k for the low-pass) –
x0 (int) –
udata[y0 (... index used to specify a region of a field in which spectrum is computed.) –
x1 (int) –
udata[y0 –
y0 (int) –
udata[y0 –
y1 (int) –
udata[y0 –
z0 (int) –
udata[y0 –
z1 (int) –
udata[y0 –
window (2d/3d nd array) –
FFT (... window used to make input data periodic to surpress spectral leakage in) –
dx (float) –
k (... z spacing. used to compute) –
dy (float) –
k –
dz (float) –
k –
- Returns
udata_ifft (nd array)
… low-pass filtered velocity field data
coords (nd array)
… if dim == 2, returns np.asarray([xgrid, ygrid])
… if dim == 3, returns np.asarray([xgrid, ygrid, zgrid])
- tflow.velocity.get_mask_for_nan_and_inf(U)
Returns a mask for nan and inf values in a multidimensional array U
- Parameters
U (nd array) –
- Returns
mask – … True if an element is nan or inf, False otherwise.
- Return type
nd array, boolean
- tflow.velocity.get_mask_for_unphysical(U, cutoffU=2000.0, fill_value=99999.0, verbose=True)
Returns a mask (N-dim boolean array). If elements were below/above a cutoff, np.nan, or np.inf, then they get masked.
- Parameters
U (array-like, a velocity field (udata)) –
cutoffU (float) – if |value| > cutoff, this function considers such values unphysical.
fill_value (float, default=99999.) –
- Returns
mask
- Return type
nd boolean array
- tflow.velocity.get_mean_flow_field_using_udatapath(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, clean=True, cutoff=inf, method='nn', median_filter=False, verbose=False, replace_zeros=True, notebook=True)
Returns mean_field when a path to udata is provided … recommended to use if udata is large (> half of your memory size) … only a snapshot of data exists on memory while time-averaging is performed
- Parameters
udatapath (str) – … path to udata
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
slicez (int, default: None) – … Option to return a 2D time-averaged field at z=slicez from 4D udata … This is mostly for the sake of fast turnout of analysis
inc (int, default: 1) – … time increment to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
thd (float, default: np.inf) – … energy > thd will be replaced by fill_value. (Manual screening of data)
fill_value (float, default: np.nan) – … value used to fill the data when data value is greater than a threshold
- Returns
udata_m
- Return type
2d or 3d arrya
- tflow.velocity.get_phase_average(x, period_ind=None, time=None, freq=None, nbins=100, axis=- 1, return_std=True, use_masked_array=True)
Returns phase average of a ND array (generalization of get_average_data_from_periodic_data) … Assume x is a periodic data, and you are interested in averaging data by locking the phase.
This function returns time (a cycle), phase-averaged data, std of the data
- … Two methods to do this
1. This is easy IF data is evenly spaced in time … average [x[0], x[period], x[period*2], …],
then average [x[1], x[1+period], x[1+period*2], …], …
- Provide a time array as well as data.
- … For example, one can give unevenly spaced data (ND array) in time
one can take phase average by taking a histogram appropriately
- … Required arguments for each method:
x, period_ind
x, time, freq
- Parameters
x (ND array, data) – … one of the array shape must must match len(time) if time is given
period_ind (int) – … period in the unit of index
time (1d array, default: None) – … time of data
freq (float) – … frequency of the periodicity of the data
nbins (int) – … number of points to probe data in the period
axis (int, default:-1) – … axis number to specify the temporal axis of the data
return_std (bool, default: True) – … If False, it returns the standard error instead of standard deviation
- Returns
t_p (time (a single cycle)) – … For the method 1, it returns np.arange(nbins)
x_pavg (phase-averaged data (N-1)D array)
x_perr (std of the data by phase averaging (N-1)D array or standard error)
- tflow.velocity.get_phase_averaged_udata_from_path(dpath, freq, time, deltaT=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, notebook=True, use_masked_array=True)
Returns the phase-averaged udata (velocity field) without loading the entire udata from dpath
- Parameters
dpath (str, path to the udata (h5)) – … the h5 file must contain ux and uy at /ux and /uy, respectively
freq (float, frequency of the peridocity in data) –
time (1D array, time) – … time unit must be the same as the inverse of the unit of ‘freq’
deltaT (float, default: None) – … time window of a phase used for averaging … data in [T, T+deltaT), [2T, 2(T+deltaT)], [3T, 3(T+deltaT)], … will be considered to be at the same phase
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
- Returns
tp (1D array, time of phase-averaged data) – … tp = [0, period] … phase = tp * freq
udata_pavg (2D array, phase-averaged udata) – … This is a phase-dependent mean flow.
- tflow.velocity.get_pressure(udata, xx, yy, zz, nu=1.003, notebook=True)
Returns pressure from a 3D+1 udata … This is a poisson solver of an incompressible NS equation using FFT … The solvalbility condition is F(p(x))|(kx=0, ky=0, kz=0) = pk(kx=0, ky=0, kz=0) = 0 …… The zeroth term of the Fourier decomposition of the pressure field is zero.
- Parameters
udata (4d/5d array, v-field data with shape (3, h, w, d) or (3, h, w, d, t)) –
xx (3d array, positional grid about x) –
yy (3d array, positional grid about y) –
zz (3d array, positional grid about z) –
nu (float, viscosity) –
- Returns
- Return type
pressure, 4d array with shape (h, w, d, t)
- tflow.velocity.get_radial_enstrophy_dist_from_path(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, notebook=True, xc=None, yc=None, zc=None, n=50, clean=False, clean_kwargs={'median_filter': False, 'method': 'nn', 'u_cutoff': inf})
Returns the radial enstrophy profile (i.e. angular average) … This function loads udata frame by frame.
- Parameters
udatapath (str, path (h5) to udata) –
x0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
x1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
y0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
y1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
z0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, z0:z1, :]) –
z1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, z0:z1, :]) –
t0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, z0:z1, t0:t1]) –
t1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, z0:z1, t0:t1]) –
inc (int, it uses every "inc" frames to compute the radial profile) –
notebook (bool, if True, uses tqdm_notebook instead of tqdm to display progress) –
xc (float, x-coordinate of the origin of the polar/spherical coordinate system) –
yc (float, y-coordinate of the origin of the polar/spherical coordinate system) –
zc (float, z-coordinate of the origin of the polar/spherical coordinate system) –
n (int, number of bins in the radial profile) –
clean (bool, if True, it cleans udata before computing the enstrophy) –
clean_kwargs (dict, kwargs for clean_udata(udata, **clean_kwargs)) –
- Returns
r (1d array, radial coordinate)
enstrophy_vs_r (2d array, average enstrophy at distance r with shape (# of bins about r, duration))
enstrophy_vs_r_err (2d array, standard error for enstrophy_vs_r)
- tflow.velocity.get_radial_profile(*args, **kwargs)
See get_spatial_profile for documentation
- tflow.velocity.get_rescaled_dissipation_spectrum(udata, epsilon=100000, nu=1.0034, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=1, dy=1, dz=1, nkout=None, notebook=True)
Return rescaled dissipation spectra D(k)/(u_eta^3) vs k * eta … convention: k = 2pi/ L
- Parameters
udata (nd array) –
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
- Returns
D_k_norm (nd array) – Scaled dissipation spectrum values with shape (# of data points, duration)
D_k_err_norm (nd array) – Scaled dissipation spectrum error with shape (# of data points, duration)
k_norm (nd array) – Scaled wavenumber with shape (# of data points, duration)
- tflow.velocity.get_rescaled_energy_spectra_jhtd()
Returns values to plot rescaled energy spectrum from JHTD, computed by Takumi in 2019 Call get_energy_spectra_jhtd for dimensionful energy spectra.
- Returns
datadict – data stored in jhtd_e_specs.h5 is stored: Scaled k, Scaled ek
- Return type
dict
- tflow.velocity.get_rescaled_energy_spectrum(udata, epsilon=100000, nu=1.0034, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=1, dy=1, dz=1, nkout=None, window=None, correct_signal_loss=True, notebook=True)
- Returns SCALED energy spectrum E(k), its error, and wavenumber.
E(k) is sometimes called the 3D energy spectrum since it involves 3D FT of a velocity field.
ALWAYS greater than E11(k) and E22(k) which involve 1D FT of the velocity field along a specific direction.
Returns wavenumber with shape (# of data points, duration) instead of (# of data points, ).
… This seems redundant; however, values in the wavenumber array at a given time may fluctuate in principle due to a method how it computes the histogram (spectrum.) It should never fluctuate with the current method but is subject to a change by altering the method of determining the histogram. Therefore, this method outputs the wavenumber array with shape (# of data points, duration).
- Parameters
udata (nd array) –
epsilon (nd array or float, default: None) – dissipation rate used for scaling energy spectrum If not given, it uses the values estimated using the rate-of-strain tensor
nu (flaot, viscosity) –
x0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
x1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
y1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t0 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
t1 (int) – index to specify a portion of data in which autocorrelation funciton is computed. Use data u[y0:y1, x0:x1, t0:t1].
dx (float) – spacing in x
dy (float) – spacing in y
dz (float) – spacing in z
nkout (int, default: None) – number of bins to compute energy/dissipation spectrum
notebook (bool, default: True) – Use tqdm.tqdm_notebook if True. Use tqdm.tqdm otherwise
window (str) –
Windowing reduces undesirable effects due to the discreteness of the data. A wideband window such as ‘flattop’ is recommended for turbulent energy spectra.
For the type of available window function, choose from below: boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction)
correct_signal_loss (bool) – If True, it would compensate for the loss of the signals due to windowing. Always recommended to obtain accurate spectral densities.
- Returns
e_k_norm (numpy array) – Scaled energy spectrum with shape (number of data points, duration)
e_k_err_norm (numpy array) – Scaled energy spectrum with shape (number of data points, duration)
k_norm (numpy array) – Scaled energy spectrum with shape (number of data points, duration)
- tflow.velocity.get_rescaled_energy_spectrum_saddoughi()
Returns values to plot rescaled energy spectrum from Saddoughi (1992)
- Returns
e (numpy array) – spectral energy density: energy stored between [k, k+dk)
k (numpy array) – wavenumber
- tflow.velocity.get_rescaled_structure_function_saddoughi(p=2)
Returns the values of rescaled structure function reported in Saddoughi and Veeravalli 1994 paper: r_scaled, dll … this is a curve about a specific Reynolds number! i.e. there is no universal structure function
p: int … order of the structure function
- Returns
r_scaled (nd array, distance with respect to Kolmogorov length scale)
dll (nd array, rescaled structure function)
- tflow.velocity.get_running_avg_1d(x, t, notebook=True)
Calculate the running average of a 1D array
- Parameters
x (1d array) –
t (float, number of time steps to average over) –
notebook (bool, if True, it uses tqdm_notebook instead of tqdm to show a progress bar) –
- Returns
y
- Return type
1d array, running average of x
- tflow.velocity.get_running_avg_nd(udata, t, axis=- 1, notebook=True)
Calculate the running average of a nD array
- Parameters
udata (nd array, a vector field) –
t (float, number of time steps to average over) –
axis (int, axis along which to average) –
notebook (bool, if True, it uses tqdm_notebook instead of tqdm to show a progress bar) –
- Returns
vdata
- Return type
nd array, running average of udata along the specified axis
- tflow.velocity.get_sample_turb_field_3d(return_coord=True)
Returns udata=(ux, uy, uz) of a slice of isotropic, homogeneous turbulence data (DNS, JHTD)
- Parameters
return_coord (bool, default: True) – … If True, it returns a positional grid (xxx, yyy, zzz)
- Returns
udata (numpy array) – velocity field
xx (numpy array) – x-coordinate of 3D grid
yy (numpy array) – y-coordinate of 3D grid
zz (numpy array) – z-coordinate of 3D grid
- tflow.velocity.get_scalar_data_from_path(udatapath, name='pressure', x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, frame=None, return_xy=False, verbose=True, slicez=None, crop=None, mode='r', reverse_x=False, reverse_y=False, reverse_z=False)
Returns a scalar data from a path of udata … There could be a case that a scalar data such as temperature and pressure is also stored in udata.h5 … This function serves as a reader of such a quantity If return_xy is True, it returns udata, xx(2d grid), yy(2d grid)
- Parameters
udatapath (str, a path to udata) –
name (str, name of the dataset in the udata h5) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
inc (int) – time increment of data to load from udatapath, default: 1
frame (array-like or int, default: None) –
If an integer is given, it returns a velocity field at that instant of time If an array or a list is given, it returns a velocity field at the given time specified by the array/list.
By default, it loads data by a specified increment “inc”. If “frame” is given, it is prioritized over the incremental loading.
return_xy (bool, defualt: False) –
verbose (bool) – If True, return the time it took to load udata to memory
- Returns
pdata (ndarray, scalar data with shape (y, x, (z), t))
xx, yy, zz(if 3D) (ndarray, 2/3d positional grid with shape (y, x, (z)))
- tflow.velocity.get_skewness(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None)
Computes skewness of a given velocity field … DO NOT USE scipy.stats.skew()- which computes skewness in the language of probability … i.e. probabilistic skewness is defined through its probabilistic moments (X-E[X])^n … In turbulence, skewnesss is defined using the DERIVATIVES of turbulent velocity … In turbulence, skewness is approximately -0.4 according according to Kambe
- Parameters
udata (nd array, a velocity field) –
x0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
x1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
y0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
y1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
z0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
z1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
t0 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
t1 (int, index to specify the region of interest in udata; udata[:, y0:y1, x0:x1, (z0:z1), t0:t1]) –
- Returns
skewness
- Return type
1d array
- tflow.velocity.get_spatial_avg_energy(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, use3comp=True)
Returns energy averaged over a spatial region
- Parameters
udata (nd array, velocity field) –
x0 (int, start index along x- udata[:, y0:y1, x0:x1, z0:z1, :]) –
x1 (int, end index along x) –
y0 (int, start index along y) –
y1 (int, end index along y) –
z0 (int, start index along z) –
z1 (int, end index along z) –
use3comp (bool, If udata is 3D v-field, this function returns 3D energy if True, 2D energy (ux^2 + uy^2)/2 if False) –
- Returns
energy_vs_t (nd array, spatially averaged energy)
… shape ((duration, ))
… this array can be plotted against time
energy_vs_t_err (nd array, standard error of spatially averaged energy)
- tflow.velocity.get_spatial_avg_energy_inside_r_from_path(dpath, r, xc=0.0, yc=0.0, x0=0, x1=None, y0=0, y1=None, t0=0, t1=None, notebook=True)
Returns energy averaged inside a circle with radius r at (xc, yc) .. ONLY AVAILABLE TO 2D v-field
- Parameters
dpath (str, a path to the udata) –
r (float, radius) –
xc (float, x-coordinate of the circle (in real space)) –
yc (float, y-coordinate of the circle (in real space)) –
x0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, t0:t1]) –
x1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, t0:t1]) –
y0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, t0:t1]) –
y1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, t0:t1]) –
t0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, t0:t1]) –
t1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, t0:t1]) –
notebook (bool, if True, it uses tqdm_notebook instead of tqdm) –
- Returns
esavg_in (1d array, energy averaged over space inside the circle)
esavg_out (1d array, energy averaged over space outside the circle)
esavg_in_err (1d array, standard error for esavg_in)
esavg_out_err (1d array, standard error for esavg_out)
- tflow.velocity.get_spatial_avg_enstrophy(udata, dx=1.0, dy=1.0, dz=1.0, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, xx=None, yy=None, zz=None)
Returns spatially averaged enstrophy
- Parameters
udata (nd array, v-field) –
dx (float, x-spacing) –
dy (float, y-spacing) –
dz (float, z-spacing) –
x0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
x1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
y0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
y1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, :]) –
z0 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, z0:z1, :]) –
z1 (int, an index used to load udata from dpath- udata[:, y0:y1, x0:x1, z0:z1, :]) –
xx (2/3d array, x-coordinates- this is alternative to passing (dx, dy, dz)) –
yy (2/3d array, y-coordinates- this is alternative to passing (dx, dy, dz)) –
zz (3d array, z-coordinates- this is alternative to passing (dx, dy, dz)) –
- Returns
enstrophy_vs_t (1d array, spatially averaged enstrophy)
enstrophy_vs_t_err (1d array, standard error for enstrophy_vs_t)
- tflow.velocity.get_spatial_profile(xx, yy, qty, xc=None, yc=None, x0=0, x1=None, y0=0, y1=None, n=50, return_center=False, zz=None, zc=None, z0=0, z1=None, method=None, cutoff=inf, notebook=True, showtqdm=True)
Returns a spatial profile (radial distribution) of 3D object with shape (height, width, duration) … Computes a histogram of a given quantity as a function of distance from the center (xc, yc) … If (xc, yc) are not given, it uses the center of the mass of the quantity at the first frame.
- Parameters
xx (2/3d array, x-coordinates of the qty, shape (height, width, (depth))) –
yy (2/3d array, y-coordinates of the qty shape (height, width, (depth))) –
qty (3/4D numpy array) –
energy (...) –
enstrophy –
(height (etc. with shape) –
width –
(depth) –
duration) –
xc (float) –
coordinate (... y-coordinate of the origin of the polar) –
yc (float) –
coordinate –
x0 (int, default: 0) –
xx[y0 (... used to specify a portion of data for computing the histogram) –
x1 (int, default: None) –
y0 (int, default: 0) –
y1 (int, default: None) –
n (int) –
histograms (... number of bins for the computed) –
return_center (bool, default: False) –
zz (2/3d array, z-coordinates of the qty, shape (height, width, (depth))) –
zc (float) –
coordinate –
z0 (int, default: 0) –
xx[y0 –
z1 (int, default: 0) –
xx[y0 –
method (str, default: None, method to clean the "qty" array if it contains nan values) – … ‘nn’ - nearest neighbor interpolation (recommended) … ‘linear’ - linear interpolation … ‘cubic’ - cubic interpolation
cutoff (float, default: np.inf) – … |qty| < cutoff will be ignored from the statistics
notebook (bool, default: True, if True, it will use tqdm_notebook instead of tqdm to display a progress bar) –
showtqdm (bool, default: True, if True, it will display a progress bar) –
- Returns
rs (2d numpy array)
… radial distance with shape (n, duration)
qty_ms (2d numpy array)
… mean values of the quantity between r and r+dr with shape (n, duration)
qty_errs (2d numpy array)
… std of the quantity between r and r+dr with shape (n, duration)- not standard error
- tflow.velocity.get_speed(udata)
Returns the speed of the v-field
- Parameters
udata (nd array, v-field data) –
- Returns
speed
- Return type
(n-1)d array, speed of the v-field
- tflow.velocity.get_streamfunction_about_a_lifting_cylinder(xx, yy, xc=0, yc=0, u=1, a=1, beta=- 0.7853981633974483)
Returns a stream function about a lifting cylinder
Source: http://www-mdp.eng.cam.ac.uk/web/library/enginfo/aerothermal_dvd_only/aero/fprops/poten/node38.html
- Parameters
xx (2d array, x-coordinates) –
yy (2d array, y-coordinates) –
xc (float, default: 0, x-coordinate of cylinder) –
yc (float, default: 0, y-coordinate of cylinder) –
u (float, default: 1, magnitude of the stream velocity) –
a (radius of cylinder) –
beta (angle of the stream) –
- Returns
psi
- Return type
2d array, streamfunction values
- tflow.velocity.get_streamfunction_about_a_rankine_vortex(xx, yy, x0=0, y0=0, gamma=1.0, a=1.0)
Returns a streamfunction about a rankine vortex. Source: http://www-mdp.eng.cam.ac.uk/web/library/enginfo/aerothermal_dvd_only/aero/fprops/poten/node38.html
- Parameters
xx (2d array, x-coordinates) –
yy (2d array, y-coordinates) –
x0 (float, default: 0, x-coordinate of vortex) –
y0 (float, default: 0, y-coordinate of vortex) –
gamma (float, default: 1, circulation of vortex) –
a (float, default: 1, radius of vortex) –
- Returns
psi
- Return type
2d array, streamfunction values
- tflow.velocity.get_streamfunction_hill_spherical_vortex(xx, yy, x0=0, y0=0, u=1, a=1, gamma=None, reference_frame='lab', return_cylindrical_coords=False)
Returns ax streamfunction values for a Hill’s spherical vortex in a lab frame
Source: https://link.springer.com/chapter/10.1007/978-3-319-55164-7_34 (by Emmanuel Branlard, p.413)
Hill’s spherical vortex is an axisymmetric flow. … Radial distance to the extremum of streamfunction inside the bubble is a/sqrt(2)=0.707a. … In the ‘lab’ frame, psi=0 defines the vortex atmosphere. …… The streamfunction has an extremeum at rho=a/sqrt(2)=0.707a. …… The vorticity center (rho weighted by omega(rho, z, theta)) is at rho=0.75a. …… The velocity at the center is -1.5u hat{z}. … In the ‘vortex’ frame, the vortex is at rest. …… The velocity at the center is 0. … In the ‘wind’ or ‘absolute’ frame, the environment is at rest. velocity outside the vortex decays to zero at infinity. …… The velocity at the center is -2.5u hat{z}
- Parameters
xx (2d array, positional grid (x)) –
yy (2d array, positional grid (y)) –
x0 (float, default: 0) – … center of the spherical vortex is at (x0, y0)
y0 (float, default: 0) – … center of the spherical vortex is at (x0, y0)
u (float) – … stream velocity … The center of the vortex moves at (-1.5u, 0) … gamma = 5 * a * u # circulaton of gamma
gamma (float, default: None) – … if given, u will be overwritten
a (float, >0) – … radius of the spherical vortex
reference_frame (str, default- 'lab') – … Choose reference_frame from [lab, wind, vortex] … “lab” refers to the rest frame … “vortex” refers to the frame of reference of the vortex … “wind”/”absolute” refers to a frame of reference such that the -2.5u.
return_cylindrical_coords (bool, default- False) –
- Returns
psi
- Return type
2d array, streamfunction
Examples
import velocity as vel import graph n = 101 L = 200 a=50 x, y = np.linspace(-L/2, L/2, n), np.linspace(0, L/2, n) XX, YY = np.meshgrid(x, y) dx, dy = vel.get_grid_spacing(XX, YY)
- psi, zz, rrho = vel.get_streamfunction_hill_spherical_vortex(XX, YY, x0=0, y0=0, gamma=1, a=50,
return_cylindrical_coords=True, reference_frame=’lab’)
wdata = vel.psi2udata_cylindrical(psi, zz=zz, rrho=rrho, return_cartesian=False) omega = vel.curl(wdata, xx=XX, yy=YY)[…, 0]
fig, ax, Q = graph.quiver(XX, YY, wdata[0, …], wdata[1, …], color=’darkgreen’, zorder=100, inc=5) graph.contour(XX, YY, psi, levels=[-1.5, -1, -0.5, 0], colors=’k’, linewidths=1) graph.color_plot(XX, YY, omega, ax=ax, cmap=’bwr’) # graph.color_plot(XX, YY, psi, ax=ax, cmap=’bwr’) graph.scatter([0], [a/np.sqrt(2)], ax=ax) # psi has an extremum at a/sqrt(2)
- tflow.velocity.get_streamfunction_poisson_solver(udata, omega=None, dx=1.0, dy=1.0, xx=None, yy=None, verbose=True)
Computes the streamfunction by solving a poisson equation
- Parameters
udata (ndarray, velocity field) –
omega (ndarray, vorticity field) –
dx (float, grid spacing in x) –
dy (float, grid spacing in y) –
xx (ndarray, x grid) –
yy (ndarray, y grid) –
verbose (bool, print progress) –
- Returns
- Return type
psi
- tflow.velocity.get_streamfunction_thin_cored_vring(xx, yy, x0=0, y0=0, gamma=1.0, R=1.0, a=0.01, reference_frame='lab', uc=None, return_cylindrical_coords=True, verbose=True, notebook=True)
Returns a streamfunction of a thin-cored vortex ring in cylindrical coordinates
- Parameters
xx (2d array, positional grid) –
yy (2d array, positional grid) –
x0 (float, x-coordinate of the origin of the cylindrical coordinate) –
y0 (float, x-coordinate of the origin of the cylindrical coordinate) –
gamma (float, circulation of a vortex ring) –
R (float, radius of a vortex ring) –
a (float, cora radius of a vortex ring) –
reference_frame (str, default- 'lab') – … Choose reference_frame from [lab, wind, vortex] … “lab” refers to the rest frame … “vortex” refers to the frame of reference of the vortex
uc (float, self-induced velocity of a vortex ring, default: None) – … If a<<r, uc = -gamma / (4 * np.pi * R) * (np.log(8 * R / a) - 0.25) … For reference_frame==’vortex’, it assumes that the induced velocity is
return_cylindrical_coords (bool, default- False) –
verbose (bool, default- True) –
notebook (bool, default- True, whether to use tqdm_notebook instead of tqdm) –
- Returns
psi (2d array, streamfunction(zz, rrho))
zz, rrho (2d arrays, cylindrical coordinates, optional)
- tflow.velocity.get_streamfunction_vloop(xx, yy, x0=0, y0=0, gamma=1, R=1, reference_frame='lab', return_cylindrical_coords=False, verbose=True)
Returns a streamfunction of a vortex loop in cylindrical coordinates … A loop consists of a vortex filament. i.e. the vorticity is concentrated on a point (zero cross-section) … This makes the streamfunction on the filament to diverge. … Similarly, the energy density diverges like rho*gamma^2*R*log(R/epsilon) as it approaches to the filament by epsilon.
y(input) => rho in the cylindrical axis (distance from the symmetry axis) ^ | | ————————–> x(input) = z-axis in the cylindrical coordinates
- Parameters
xx (2d array, positional grid) –
yy (2d array, positional grid) –
x0 (float, x-coordinate of the origin of the cylindrical coordinate) –
y0 (float, x-coordinate of the origin of the cylindrical coordinate) –
gamma (float, circulation of a vortex loop) –
R (float, radius of a vortex loop) –
reference_frame (str, default- 'lab') – … Choose reference_frame from [lab, wind, vortex] … “lab” refers to the rest frame … “vortex” refers to the frame of reference of the vortex
return_cylindrical_coords (bool, default- False) –
- Returns
psi (2d array, streamfunction(rrho, zz))
rrho (2d array)
zz (2d array)
- tflow.velocity.get_structure_function(udata, x, y, z=None, nu=1.004, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, p=2, nr=None, nd=1000, mode='long', time_thd=10.0, spacing='log', notebook=True)
Compute the structure function of the velocity field.
- Parameters
udata (ndarray, 2/3D velocity field) –
x (ndarray, x-coordinates of the velocity field) –
y (ndarray, y-coordinates of the velocity field) –
z (ndarray, z-coordinates of the velocity field) –
nu (float, kinematic viscosity) –
x0 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
x1 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
y0 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
y1 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
z0 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
z1 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
t0 (int, index used to specify a temporal region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
t1 (int, index used to specify a temporal region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
p (int, order of the structure function) –
nr (int, number of points (distances) at which the structure function is evaluated) –
nd (int, number of pairs considered to compute the structure function value at a given distance) –
mode (str, 'long' or 'trans') – … Specify whether longitudinal or transverse correlations is evaluated
time_thd (float, threshold for the computation time (in sec) to determine a correlation value at a given distance r) – … default: 10. sec
spacing (str, 'log' or 'linear') – … Specify whether the considered distance r is evenly spaced logarithmically or linearly
notebook (bool, if True, it will use tqdm_notebook instead of tqdm to display a progress bar) –
- Returns
rrs (2d array, distances at which the structure function is evaluated, shape: (nr, duration))
Dijks (2d array, structure function values at the distances rrs, shape: (nr, duration))
Dijk_errs (2d array, standard errors of the structure function values at the distances rrs, shape: (nr, duration))
rrs_scaled (2d array, rrs / eta, eta: Kolmogorov length scale estimated from the rate-of-strain tensor)
Dijks_scaled (2d array, Dijks / (epsilon * rrs * (p/3)), epsilon: Kolmogorov length scale estimated from the rate-of-strain tensor*)
Dijk_errs_scaled (2d array, Dijk_errs / (epsilon * rrs * (p/3)), epsilon: Kolmogorov length scale estimated from the rate-of-strain tensor*)
- tflow.velocity.get_structure_function_long(udata, x, y, z=None, p=2, roll_axis=1, n_bins=None, nu=1.004, u='ux', x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, coarse=1.0, coarse2=0.2, notebook=True)
DEPRECATED! Use get_structure_function()
Structure tensor Dij is essentially the covariance of the two-point velocity difference There is one-to-one correspondence between Dij and Rij. (Pope 6.36) This method returns the LONGITUDINAL STRUCTURE FUNCTION. If p=2, this returns D_LL. … Returns rrs, Dxxs, Dxx_errs, rrs_scaled, Dxxs_scaled, Dxx_errs_scaled :param udata: :param x: x-coordinate of the spatial grid corresponding to the given udata
… it does not have to ve equally spaced
- Parameters
y (numpy array) – y-coordinate of the spatial grid corresponding to the given udata … it does not have to ve equally spaced
z (numpy array) – z-coordinate of the spatial grid corresponding to the given udata … it does not have to ve equally spaced
p (float or int) – order of structure function
roll_axis (int) – “u” and “roll_axis” determines whether this method returns the longitudinal or transverse structure function If you want longitudinal, match “u” and “roll_axis”. e.g.- u=’ux’ and roll_axis=1, u=’uy’ and roll_axis=0 If you want transverse, do not match “u” and “roll_axis”. e.g.- u=’ux’ and roll_axis=0, u=’uy’ and roll_axis=1
n_bins (int, default=None) – number of bins used to take a histogram of velocity difference
nu (float) – viscosity
u (str, default='ux') – velocity component used to compute the structure functions. Choices are ‘ux’, ‘uy’, ‘uz’
x0 (int, default: 0) – Specified the region of udata to compute the structure function. This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
x1 (int, default: None) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
y0 (int, default: 0) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
int (t1) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
default (None) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
z0 (int, default: 0) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
int – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
default – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
t0 (int, default: 0) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
int – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
default – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
coarse (float, (0, 1], default: 1) – the first parameter to save computation time related sampling frequency … The higher “coarse” is, it samples more possible data points. … If “coarse” == 1, it samples all possible data points. … If “coarse” == 0.5, it samples only a half of possible data points. Could overestimate Taylor microscale.
coarse2 (float, (0, 1], default: 0.2) – the second parameter to save computation time related to making a histogram … Determines how many sampled data points to be used to make a histogram … If “coarse” == 1, it uses all data points to make a histogram. … If “coarse” == 0.5, it uses only a half of data points to make a histogram
notebook (bool) – … if True, it uses tqdm.tqdm_notebook instead of tqdm.tqdm
- Returns
rrs (numpy array) – two-point separation distance for the structure function
Dxxs (numpy array) – values of the structure function
Dxx_errs (numpy array) – error of the structure function
rrs_scaled (numpy array) – two-point separation distance for the SCALED structure function
Dxxs_scaled (numpy array) – values of the SCALED structure function
Dxx_errs_scaled (numpy array) – error of the SCALED structure function
- tflow.velocity.get_structure_function_roll(udata, x, y, z=None, indices=('x', 'x'), roll_axis=1, n_bins=None, nu=1.004, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, coarse=1.0, coarse2=0.2, notebook=True)
DEPRECATED! Use get_structure_function() A method to compute a generalized structure function
Structure tensor Dij…k is essentially the generalized variance of the two-point velocity difference This method returns the STRUCTURE FUNCTION D_{ij…k}(r x_m) where the tensor indices are “indices” and the subscript of x_m, m, is expressed as roll_axis.
If indices=(0, 0) & roll_axis=1, this returns D_{xx}(r hat{x}). # longitudinal, 2nd order If indices=(1, 1) & roll_axis=0, this returns D_{yy}(r hat{y}). # longitudinal, 2nd order If indices=(1, 1) & roll_axis=0, this returns D_{yy}(r hat{x}). # transverse, 2nd order If indices=(0, 0, 0) & roll_axis=1, this returns D_{xxx}(r hat{x}). # longitudinal, 3nd order If indices=(0, 1, 0) & roll_axis=1, this returns D_{xyx}(r hat{x}). # (1, 2, 1)-component of the 3rd order structure function tensor
… Returns rrs, Dijks, Dijk_errs, rrs_scaled, Dijks_scaled, Dijk_errs_scaled
- Parameters
udata –
x (numpy array) – x-coordinate of the spatial grid corresponding to the given udata … it does not have to ve equally spaced
y (numpy array) – y-coordinate of the spatial grid corresponding to the given udata … it does not have to ve equally spaced
z (numpy array) – z-coordinate of the spatial grid corresponding to the given udata … it does not have to ve equally spaced
indices (array-like, default: (1, 1)) – … tensor indices of the structure function tensor: D_{i,j,…, k} … indices=(1,1) corresponds to D_{xx}. … For a 3D spatial field, x, y, z corresponds to 1, 0, 2 respectively. Recall udata.shape = (height, width, depth, duration) … For a 2D spatial field, x, y corresponds to 1, 0 respectively. Recall udata.shape = (height, width, duration)
roll_axis (int) – “u” and “roll_axis” determines whether this method returns the longitudinal or transverse structure function If you want longitudinal, match “u” and “roll_axis”. e.g.- u=’ux’ and roll_axis=1, u=’uy’ and roll_axis=0 If you want transverse, do not match “u” and “roll_axis”. e.g.- u=’ux’ and roll_axis=0, u=’uy’ and roll_axis=1
n_bins (int, default=None) – number of bins used to take a histogram of velocity difference
nu (float) – viscosity
u (str, default='ux') – velocity component used to compute the structure functions. Choices are ‘ux’, ‘uy’, ‘uz’
x0 (int, default: 0) – Specified the region of udata to compute the structure function. This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
x1 (int, default: None) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
y0 (int, default: 0) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
int (t1) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
default (None) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
z0 (int, default: 0) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
int – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
default – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
t0 (int, default: 0) – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
int – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
default – This method uses only udata[y0:y1, x0:x1, z0:z1, t0:t1].
coarse (float, (0, 1], default: 1) – the first parameter to save computation time related to sampling frequency … The higher “coarse” is, it samples more possible data points. … If “coarse” == 1, it samples all possible data points. … If “coarse” == 0.5, it samples only a half of possible data points.
coarse2 (float, (0, 1], default: 0.2) – the second parameter to save computation time related to making a histogram … Determines how many sampled data points to be used to make a histogram … If “coarse” == 1, it uses all data points to make a histogram. … If “coarse” == 0.5, it uses only a half of data points to make a histogram
notebook (bool) – … if True, it uses tqdm.tqdm_notebook instead of tqdm.tqdm
- Returns
rrs (numpy array) – two-point separation distance for the structure function
Dxxs (numpy array) – values of the structure function
Dxx_errs (numpy array) – error of the structure function
rrs_scaled (numpy array) – two-point separation distance for the SCALED structure function
Dxxs_scaled (numpy array) – values of the SCALED structure function
Dxx_errs_scaled (numpy array) – error of the SCALED structure function
- tflow.velocity.get_suggested_inds(udatapath)
Returns a dictionary of the recommended indices of the udata stored in udatapath … e.g.
inds = read_suggested_inds(udatapath) udata = read_udata_from_path(udatapath, **inds) … This will load udata[y0:y1, x0:x1, z0:z1, :] onto the memory … The motivation behind this is that STB sometimes results a lot of empty data especially when no particles can be tracked in the region.
… This is often the case due to the limited depth of the field that the STB may resolve. … suggest_udata_dim2load(udatapath) computes the statistics, and suggests the indices one should use so that one avoids loading the empty data which could bias the data and cause problems for many analyses such as a Fourier analysis.
- Parameters
udatapath (str, a path to the h5 file where udata is stored) –
- Returns
inds – … inds = {“x0”: x0, “x1”: x1, “y0”: y0, “y1”: y1, “z0”: z0, “z1”: z1} … udata[y0:y1, x0:x1, z0:z1, :]
- Return type
dict, the suggested indices of the udata
- tflow.velocity.get_taylor_microscales(r_long, f_long, r_tran, g_tran, residual_thd=0.015, deg=2, return_err=False, npt_min=4)
Returns Taylor microscales as the curvature of the autocorrelation functions at r=0 … Algorithm: … (1) Polynomial fit (cubic) the long./trans. autocorr functions … (2) Evaluate its second derivate at r=0. … (3) Relate that value to the taylor microscale … Feed the results from get_two_point_vel_corr_iso().
- Parameters
r_long (numpy 2d array with shape (no. of elements, duration)) – … r for longitudinal autoorrelation values
f_long (numpy 2d array with shape (no. of elements, duration)) – … longitudinal autoorrelation values
r_tran (numpy 2d array with shape (no. of elements, duration)) – … r for longitudinal autoorrelation values
g_tran (numpy 2d array with shape (no. of elements, duration)) – … longitudinal autoorrelation values
residual_thd (float) – … threshold for the residuals of the polynomial fit
deg (int, default 2, degree of the polynomial fit) –
return_err –
bool –
False (default) –
fit (whether to return the error of the polynomial) –
npt_min (int, default 4, minimum number of points for the polynomial fit to compute Taylor's microscale) –
- Returns
lambda_f (numpy 2d array with shape (duration, )) – … Longitudinal Taylor microscale
lambda_g (numpy 2d array with shape (duration, )) – … Transverse Taylor microscale
lambda_err_f (numpy 2d array with shape (duration, ), optional)
lambda_err_g (numpy 2d array with shape (duration, ), optional)
- tflow.velocity.get_taylor_microscales_all(udata, r_long, f_long, r_tran, g_tran)
Returns Taylor microscales (Length, Velocity, Time) based on autocorrelation functions … More time-consuming than get_taylor_microscales_all_iso() but more basic …… the time-consuming part is the estimation of the autocorrelation functions: r_long, f_long, r_tran, g_tran
- Parameters
udata (numpy array) – velocity field array
r_long (numpy array) – … output of get_two_point_vel_corr_iso(…)
f_long (numpy array) – … output of get_two_point_vel_corr_iso(…)
r_tran (numpy array) – … output of get_two_point_vel_corr_iso(…)
g_tran (numpy array) – … output of get_two_point_vel_corr_iso(…)
- Returns
lambda_f (1d array) – Taylor microscale (length)
u_lambda (1d array) – Taylor microscale (velocity)
tau_lambda (1d array) – Taylor microscale (time)
- tflow.velocity.get_taylor_microscales_all_iso(udata, epsilon, nu=1.004)
Returns Taylor microscales using isotropic formula based on udata and dissipation rate … Quick but only applicable to isotropic turbulence … a dissipation rate must be accurately estimated to have a meaningful result
- Parameters
udata (numpy array) – velocity field array
epsilon (numpy array) – disspation rate
nu (numpy array) – viscosity
- Returns
lambda_f_iso (1d array) – Taylor microscale (length)
u_lambda_iso (1d array) – Taylor microscale (velocity)
tau_lambda_iso (1d array) – Taylor microscale (time)
- tflow.velocity.get_taylor_microscales_iso(udata, epsilon, nu=1.004)
Return Taylor microscales computed by isotropic formulae: lambda_g_iso = (15 nu * u_irms^2 / epsilon) ^ 0.5
- Parameters
udata (nd array) –
epsilon (float or array with the same length as udata) –
nu (float) – viscoty
- Returns
lambda_f_iso (numpy array) – longitudinal Taylor microscale
lambda_g_iso (numpy array) – transverse Taylor microscale
- tflow.velocity.get_taylor_re(udata, r_long, f_long, r_tran, g_tran, nu=1.004)
Returns Taylor reynolds number (Pope 6.63) from autocorrelation functions
- Parameters
udata (numpy array) – velocity field array
r_long (numpy array) – … output of get_two_point_vel_corr_iso(…)
f_long (numpy array) – … output of get_two_point_vel_corr_iso(…)
r_tran (numpy array) – … output of get_two_point_vel_corr_iso(…)
g_tran (numpy array) – … output of get_two_point_vel_corr_iso(…)
nu (float, default: 1.004 (water, in mm^2/s)) – viscosity
- Returns
Re_lambda – Taylor Reynolds number
- Return type
array
- tflow.velocity.get_taylor_re_iso(udata, epsilon, nu=1.004)
Returns Taylor reynolds number (Pope 6.63) using isotropic formula
- Parameters
udata (numpy array) – velocity field array
epsilon (numpy array) – disspation rate
nu (numpy array) – viscosity
- Returns
Re_lambda_iso – Taylor Reynolds number
- Return type
array
- tflow.velocity.get_time_avg_energy(udata)
Returns a time-averaged energy field
- Parameters
udata (nd array) –
- Returns
time-averaged energy field
- Return type
energy_avg
- tflow.velocity.get_time_avg_energy_from_udatapath(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, slicez=None, inc=1, clean=False, median_filter=False, thd=inf, fill_value=nan, udata_mean=None, notebook=True, **kwargs)
Returns time-averaged energy when a path to udata is provided … recommended to use if udata is large (> half of your memory size) … only a snapshot of data exists on memory while time-averaging is performed
- Parameters
udatapath (str) – … path to udata
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
slicez (int, default: None) – … Option to return a 2D time-averaged field at z=slicez from 4D udata … This is mostly for the sake of fast turnout of analysis
inc (int, default: 1) – … time increment to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
thd (float, default: np.inf) – … energy > thd will be replaced by fill_value. (Manual screening of data)
fill_value (float, default: np.nan) – … value used to fill the data when data value is greater than a threshold
udata_mean (array, default: None) – … It subtracts the given array from the udata. This feature can be used to compute the mean fluctuating energy.
clean (bool, if True, it runs clean_udata() before computing energy) – … it is often recommmended to pass an additional kwarg ‘showtqdm=False’ for concise output. … if method=’idw’, this process could take time so ‘showtqdm=True’ makes sense to monitor this cleaning process.
- Returns
eavg
- Return type
nd array, time-averaged energy
- tflow.velocity.get_time_avg_enstrophy(udata, dx=1.0, dy=1.0, dz=1.0, xx=None, yy=None, zz=None)
Returns a time-averaged enstrophy field
- Parameters
udata (nd array, velocity field) –
dx (float, spacing along x) –
dy (float, spacing along y) –
dz (float, spacing along z (optional, applicable to 3D data)) –
xx (nd array, x coordinates) –
yy (nd array, y coordinates) –
zz (nd array, z coordinates (optional, applicable to 3D data)) –
- Returns
enstrophy_avg
- Return type
nd array, time-averaged enstrophy field
- tflow.velocity.get_time_avg_enstrophy_from_udatapath(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, slicez=None, inc=1, thd=inf, fill_value=nan, udata_mean=None, notebook=True)
Returns time-averaged energy from a path to udata … recommended to use if udata is large (> half of your memory size) … only a snapshot of data exists on memory while time-averaging is performed
- Parameters
udatapath (str) – … path to udata
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
slicez (int, default: None) – … Option to return a 2D time-averaged field at z=slicez from 4D udata … This is mostly for the sake of fast turnout of analysis
inc (int, default: 1) – … time increment to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
thd (float, default: np.inf) – … energy > thd will be replaced by fill_value. (Manual screening of data)
fill_value (float, default: np.nan) – … value used to fill the data when data value is greater than a threshold
- Returns
enstavg
- Return type
ndarray, time-averaged enstrophy
- tflow.velocity.get_time_avg_field_from_udatapath(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, slicez=None, inc=1, thd=inf, fill_value=nan, notebook=True)
Returns time-averaged velocity field when a path to udata is provided … recommended to use if udata is large (> half of your memory size) … only a snapshot of data exists on memory while time-averaging is performed
- Parameters
udatapath (str) – … path to udata
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
slicez (int, default: None) – … Option to return a 2D time-averaged field at z=slicez from 4D udata … This is mostly for the sake of fast turnout of analysis
inc (int, default: 1) – … time increment to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
thd (float, default: np.inf) – … energy > thd will be replaced by fill_value. (Manual screening of data)
fill_value (float, default: np.nan) – … value used to fill the data when data value is greater than a threshold
- Returns
u_m
- Return type
ndarray, mean velocity field with shape (dim, height, width, (depth))
- tflow.velocity.get_time_from_path(dpath, fps, inc=1, t0=0, t1=None, save=False, overwrite=False)
Returns real time that corresponds to udata … time = np.arange(t0, t1, inc) / fps
- Parameters
dpath (str, a path where a velocity field is stored) –
fps (float, frame rate in FPS) –
inc (int, increment) –
t0 (int, starting frame number) –
t1 (int, ending frame number) –
save (bool, if True, it adds the created 1d array at /t) –
overwrite (bool, if True AND save is True, it saves the created 1d array at /t even if the data already exists there.) –
- Returns
realtimes
- Return type
1d array, time (in sec)
- tflow.velocity.get_time_indices_for_selfsimilar_movie(time, t0, dt, exponent=- 1, nmax=None)
Returns indices of a time array required to make a self-similar movie
… Let t_i be the time at frame i. To preserve the displacement between two frames when energy decays in a power law (E ~ (t-t0)^n), t_i must satisfy the following recurrence relation.
t_{i+2} = {2t_{i+1}^m - 2t_{i}^m }^{1/m}
where m = n/2 + 1.
… This function returns indices for the given array “time”. To do so, one needs t0, t1, and n. … t1 = t0 + dt … exponent is “n”.
- Parameters
time (1d array) – … time. this does not have to be evenly spaced. … e.g. [0.0, 0.005, 0.010, 0.020, …]
t0 (float/int) – … the first
dt (float/int) – … t1 = t0 + dt. If not clear, read about the recurrence relation above
exponent (exponent of energy decay, default=-1) – … Some best estimate on this is around -1.2 for the initial period of decay.
nmax (int, default=None) – … number of elements of the output array
- Returns
t_indices
- Return type
1d array, indices of a time array required to make a self-similar movie
- tflow.velocity.get_turbulence_intensity_from_path(dpath, writeData=False, overwrite=False, notebook=True)
Computes the turbulence intensity of udata in a given path
- Parameters
dpath (str, a path (h5) to the udata) –
writeData (bool, if True, it writes the turbulence intensity to the h5 file) –
overwrite (bool, if True, it overwrites the turbulence intensity if it already exists) –
notebook (bool, if True, it uses tqdm_notebook instead of tadm to display the progress) –
- Returns
ti
- Return type
nd array, turbulence intensity with shape (height, width, (optional: depth))
- tflow.velocity.get_turbulence_intensity_local(udata)
Turbulence intensity is defined as u/U where u = sqrt((ux**2 + uy**2 + uz**2)/3) # characteristic turbulent velocity U = sqrt((Ux**2 + Uy**2 + Uz**2)) # norm of the rms velocity
Note that this is ill-defined for turbulence with zero-mean flow !
- Parameters
udata (nd array, a velocity field) –
- Returns
ti_local – … a field of a turbulent intensity (a scaler field)
- Return type
nd array
- tflow.velocity.get_turbulence_re(udata, dx, dy, dz=None, nu=1.004)
Returns turbulence reynolds number (Pope 6.59) … Integral Reynolds number
- Parameters
udata (numpy array) –
dx (float) – data spacing in x
dy (float) – data spacing in y
dz (float) – data spacing in z
nu (float) – viscosity
- Returns
Re_L – Turbulence Reynolds number
- Return type
numpy array
- tflow.velocity.get_two_point_vel_corr(udata, x, y, z=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, nd=1000, nr=70, rmax=None, notebook=True, periodic=False)
Returns the normalized two-point velocity tatistics (rrs, fs, f_errs, rrs, gs, g_errs)
… f(r): longitudinal two-pt stat … g(r): transverse two-pt stat … In order for f(r) and g(r) to have a meaning, the flow MUST be isotropic … Algorithm:
… The v-field must be isotropic for this result to make sense.
- Parameters
udata (nd array, a velocity field) –
x (2/3d array, x-coordinates of the velocity field) –
y (2/3d array, y-coordinates of the velocity field) –
z (2/3d array, z-coordinates of the velocity field) –
x0 (int, index used to specify a spatial region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
x1 (int, index used to specify a spatial region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
y0 (int, index used to specify a spatial region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
y1 (int, index used to specify a spatial region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
z0 (int, index used to specify a spatial region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
z1 (int, index used to specify a spatial region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
t0 (int, index used to specify a temporal region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
t1 (int, index used to specify a temporal region in which the statistics is computed udata[:, x0:x1, y0:y1, z0:z1, t0:t1]) –
nd (int, number of bins in the histogram- the bin width is roughly rmax/nd) –
nr (int, number of pairs of points used to compute the two-point correlation function at a particular distance r) –
rmax (float, maximum distance to compute the two-point correlation function) –
notebook (bool, if True, tqdm_notebook is used instead of tqdm) –
periodic (bool, if True, the velocity field is assumed to be periodic) –
- Returns
autocorrs (tuple)
… autocorrs = (rrs, fs, f_errs, rrs, gs, g_errs)
… rrs (2d array, radial distances with shape (nd, duration))
… fs (2d array, longitudinal velocity correlation funciton (nd, duration))
… f_errs (2d array, longitudinal velocity correlation funciton error (nd, duration))
… rrs (2d array, radial distances with shape (nd, duration))
…… same as the first return value (this is returned for consistency)
… gs (2d array, transverse velocity correlation funcitonwith shape (nd, duration))
… g_errs (2d array, transverse velocity correlation funciton error with shape (nd, duration))
- tflow.velocity.get_two_point_vel_corr_iso(udata, x, y, z=None, time=None, n_bins=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=None, t1=None, coarse=1.0, coarse2=0.2, notebook=True, return_rij=False)
Returns two-point velocity autocorrelation tensor, and autocorrelation functions. Uses the x-component of velocity. (CAUTION required for unisotropic flows) … Pope Eq. 6.44
- udata: 5D or 4D numpy array, 5D if the no. of spatial dimensions is 3. 4D if the no. of spatial dimensions is 2.
… (ux, uy, uz) or (ux, uy) … ui has a shape (height, width, depth, duration) or (height, width, depth) (3D) … ui may have a shape (height, width, duration) or (height, width) (2D)
x: 2d/3d grid, x coordinate of a field y: 2d/3d grid, y coordinate of a field z: 2d/3d grid, y coordinate of a field roll_axis: int, direction of a displacement vector between two points
… 0: y, 1: x, 2:z
n_bins: int, nuber of bins used to compute the two-point statistics x0: int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] x1: int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] y0: int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] y1: int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] z0: int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] z1: int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] t0: int, index used to specify a temporal region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] t1: int, index used to specify a temporal region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1] coarse: float, (0, 1], default: 1
the first parameter to save computation time related sampling frequency … The higher “coarse” is, it samples more possible data points. … If “coarse” == 1, it samples all possible data points. … If “coarse” == 0.5, it samples only a half of possible data points. Could overestimate Taylor microscale.
- coarse2: float, (0, 1], default: 0.2
the second parameter to save computation time related to making a histogram … Determines how many sampled data points to be used to make a histogram … If “coarse” == 1, it uses all data points to make a histogram. … If “coarse” == 0.5, it uses only a half of data points to make a histogram
notebook: bool, if True, it uses tqdm_notebook instead of tqdm to display a progress bar return_rij: bool,
- … If True, it returns a funciton (the autocorrealtion tensor Rij with aarguments (i, j, r, t, udata))
AND autocorrs = (r_long, f_long, f_err_long, r_tran, g_tran, g_err_tran)
- autocorrs: tuple, (r_long, f_long, f_err_long, r_tran, g_tran, g_err_tran)
… r_long: 2D numpy array, distance for f_long, shape: (nbins, duration) … f_long: longitudinal autocorrelation values, shape: (nbins, duration) … f_err_long: longitudinal autocorrelation errors, shape: (nbins, duration) … r_tran: 2D numpy array, distance for g_tran, shape: (nbins, duration) … g_tran: transverse autocorrelation values, shape: (nbins, duration) … g_err_tran: transverse autocorrelation errors, shape: (nbins, duration)
- rij: funciton with arguments (r, t, i, j), autocorrelation tensor ,optional
… Rij (
ec{r} , t) = <u_j( ec{x}) u_j( ec{x}+ ec{r})> / <u_j( ec{x})^2>
- … If system is homogeneous and isotropic,
Rij (
- ec{r} , t) = u_rms^2 [g(r,t) delta_ij + {f(r,t) - g(r,t)} r_i * r_j / r^2]
where f, and g are long. and transverse autocorrelation functions.
- tflow.velocity.get_two_point_vel_corr_roll(ui, x, y, z=None, roll_axis=1, n_bins=None, x0=None, x1=None, y0=None, y1=None, z0=None, z1=None, t0=None, t1=None, coarse=1.0, coarse2=0.2, periodic=False, Lx=None, Ly=None, Lz=None, notebook=True)
- Returns a two-point velocity correlation function <ui(x) ui(x+r)> / < |ui(x)|^2 > … Redirects to compute_spatial_autocorr2d OR compute_spatial_autocorr3d!
… Spatial autocorrelation function and two-pt vel corr function are the same things.
- … This function is primarily used to compute the longitudnal/transverse two-pt vel correlation functions
… f(r) = <u1(x) u1(x+r hat{x_1})> / < |u1(x)|^2 > … ui = udata[0, …], roll_axis=1 … g(r) = <u1(x) u1(x+r hat{x_2})> / < |u1(x)|^2 > … ui = udata[1, …], roll_axis=1
… One can deduce Taylor microscale, energy spectrum from f(r) and g(r) … One can compute Rii with the outputs of this function.
R11 = f(r) * < ux^2 >
R22 = g(r) * < uy^2 > … This g(r) can be obtained by (ui = udata[1, …], roll_axis=1)
R33 = g(r) * < uy^2 > … This g(r) can be obtained by (ui = udata[2, …], roll_axis=1)
- … Important quantities to check are one-dimensional spectra Eii.
… Eii = 2 x Fourier Transform of(Rii) … This may not yield the cleanest spectra; however, one should always check
the following equality … < ux^2 > = int_0^infty E11(kappa1) dkappa1 … < uy^2 > = int_0^infty E22(kappa1) dkappa1 … < uz^2 > = int_0^infty E33(kappa1) dkappa1 i.e. (Turbulent) Energy = 0.5 int_0^infty Eii(kappa1) dkappa1
- Parameters
ui (nd array, ux, uy or uz) –
udata[0 (... e.g.) –
ux (...] for) –
x (2d/3d grid, x coordinate of a field) –
y (2d/3d grid, y coordinate of a field) –
z (2d/3d grid, y coordinate of a field) –
roll_axis (int, direction of a displacement vector between two points) – … 0: y, 1: x, 2:z
n_bins (int, nuber of bins used to compute the two-point statistics) –
x0 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
x1 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
y0 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
y1 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
z0 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
z1 (int, index used to specify a spatial region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
t0 (int, index used to specify a temporal region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
t1 (int, index used to specify a temporal region in which the statistics is computed [y0:y1, x0:x1, z0:z1, t0:t1]) –
coarse (float, (0, 1], default: 1) – the first parameter to save computation time related sampling frequency … The higher “coarse” is, it samples more possible data points. … If “coarse” == 1, it samples all possible data points. … If “coarse” == 0.5, it samples only a half of possible data points. Could overestimate Taylor microscale.
coarse2 (float, (0, 1], default: 0.2) – the second parameter to save computation time related to making a histogram … Determines how many sampled data points to be used to make a histogram … If “coarse” == 1, it uses all data points to make a histogram. … If “coarse” == 0.5, it uses only a half of data points to make a histogram
periodic (bool, default False) – … turn this on to correctly account for the periodicty of the field
Lx (float, size of the periodic box in the x-direction (not index)) –
Ly (float, size of the periodic box in the y-direction (not index)) –
Lz (float, size of the periodic box in the z-direction (not index)) –
notebook (bool, if True, it uses tqdm_notebook instead of tqdm) –
- Returns
rr (2d numpy array, distance (distance, time))
corr (2d numpy array, (two-point correlation values, time))
corr_err (2d numpy array, (std of two-point correlation, time))
- tflow.velocity.get_udata(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, frame=None, return_xy=False, verbose=True, slicez=None, crop=None, mode='r', reverse_x=False, reverse_y=False, reverse_z=False, ind=0)
Returns udata from a path to udata If return_xy is True, it returns udata, xx(2d grid), yy(2d grid)
- Parameters
udatapath –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
inc (int) – time increment of data to load from udatapath, default: 1
frame (array-like or int, default: None) –
If an integer is given, it returns a velocity field at that instant of time If an array or a list is given, it returns a velocity field at the given time specified by the array/list.
By default, it loads data by a specified increment “inc”. If “frame” is given, it is prioritized over the incremental loading.
return_xy (bool, defualt: False) –
verbose (bool) – If True, return the time it took to load udata to memory
ind (int, id for a file with multiple piv data (udata)) – … A file may include ux, uy, x, y under /piv/piv000/, /piv/piv001, /piv/piv001, … when piv is conducted on the same footage.
- Returns
udata (nd array with shape (dim, height, width, (depth), duration)) – … udata[0, …]: ux, udata[1, …]: uy, udata[2, …]: uz … udata[0, …, t] is a 2D/3D array which stores the x-component of the velocity field. … Intuitively speaking, udata is organized like udata[dim, y, x, (z), time]
(optional)
xx (2d/3d array of a positional grid (x) stored in the given file)
yy (2d/3d array of a positional grid (y) stored in the given file)
zz (2d/3d array of a positional grid (z) stored in the given file)
- tflow.velocity.get_udata_dim(udatapath)
Returns the array size of ux stored in the given path
- tflow.velocity.get_udata_from_path(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, frame=None, return_xy=False, verbose=True, slicez=None, crop=None, mode='r', reverse_x=False, reverse_y=False, reverse_z=False, ind=0)
Returns udata from a path to udata If return_xy is True, it returns udata, xx(2d grid), yy(2d grid)
- Parameters
udatapath –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
inc (int) – time increment of data to load from udatapath, default: 1
frame (array-like or int, default: None) –
If an integer is given, it returns a velocity field at that instant of time If an array or a list is given, it returns a velocity field at the given time specified by the array/list.
By default, it loads data by a specified increment “inc”. If “frame” is given, it is prioritized over the incremental loading.
return_xy (bool, defualt: False) –
verbose (bool) – If True, return the time it took to load udata to memory
ind (int, id for a file with multiple piv data (udata)) – … A file may include ux, uy, x, y under /piv/piv000/, /piv/piv001, /piv/piv001, … when piv is conducted on the same footage.
- Returns
udata (nd array with shape (dim, height, width, (depth), duration)) – … udata[0, …]: ux, udata[1, …]: uy, udata[2, …]: uz … udata[0, …, t] is a 2D/3D array which stores the x-component of the velocity field. … Intuitively speaking, udata is organized like udata[dim, y, x, (z), time]
(optional)
xx (2d/3d array of a positional grid (x) stored in the given file)
yy (2d/3d array of a positional grid (y) stored in the given file)
zz (2d/3d array of a positional grid (z) stored in the given file)
- tflow.velocity.get_udata_from_path_nested(udatapath, ind=0, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, t0=0, t1=None, inc=1, frame=None, return_xy=False, verbose=True, slicez=None, crop=None, mode='r', reverse_x=False, reverse_y=False, reverse_z=False)
A function to read udata from a hdf5 file … This function is suited for a nested structure Takumi used temporarily between 2017-18.
This format stores udata generated by multiple PIV settings (different Dt, interrogation window size, etc) on the same movie
- … The hdf5 should have a following structure
/piv/exp/__quantity_like_piston_velocity_piston_position_etc /piv/piv000/__quantity_like_ux_uy_x_y_lambda_etc /piv/piv001/__quantity_like_ux_uy_x_y_lambda_etc … /piv/piv010/__quantity_like_ux_uy_x_y_lambda_etc
… Specify which udata to load via “ind”
- Parameters
udatapath –
str –
ind (int, index to specify which piv data to load in a nested h5) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
inc (int) –
frame (int) –
return_xy (bool, If True, it retursn a 2D/3D grid which can be used for pcolormesh etc.) –
verbose (bool, If True, it reports progress) –
slicez (int, default: None) –
- … Feature for loading a planar udata from a volumetric udata
If given, it returns a (ux, uy, uz) on a plane z=slizez (in index space)
crop (int, default: None) – If given, it will make x0=y0=z0=crop, x1=y1=z1=-crop … This literally “crops” a velocity field in a square/cubic mannar
reverse_x (bool, If True, it reverses the order of x) –
- … This is sometimes useful if external function requires a monotonically increasing array.
e.g. interpolation in scipy/numpy
reverse_y (bool, If True, it reverses the order of y) –
reverse_z (bool, If True, it reverses the order of z) –
- Returns
udata (nd array, velocity field)
xx, yy, zz (2D/3D array, position grid, (if return_xy is True))
- tflow.velocity.get_udata_phys_dim(udatapath, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None)
Returns the physical dimensions of the velocity field stored in the standard format in the given path … the h5 file must contain the following datasets:
ux at /ux
uy at /uz
uz at /uy
x at /x
y at /y
z at /z
width, height, and the depth of the udata in physical dimensions (probably in mm)
- Parameters
udatapath (str, path to the h5 file containing the velocity field) –
x0 (int, default: 0) – … index to specify volume of data (xx[y0:y1, x0:x1, z0:z1])
x1 (int, default: 0) – … index to specify volume of data (xx[y0:y1, x0:x1, z0:z1])
y0 (int, default: 0) – … index to specify volume of data (xx[y0:y1, x0:x1, z0:z1])
y1 (int, default: 0) – … index to specify volume of data (xx[y0:y1, x0:x1, z0:z1])
z0 (int, default: 0) – … index to specify volume of data (xx[y0:y1, x0:x1, z0:z1])
z1 (int, default: 0) – … index to specify volume of data (xx[y0:y1, x0:x1, z0:z1])
- Returns
w, h, (d- if applicable)
- Return type
float, physical dimensions of the velocity field (width, height, depth)
- tflow.velocity.get_unidirectional_flow(xx, yy, t=array([0, 1]), U=10, c=0, decay=None, decay_scale=1.0)
Returns udata of a unidirectional flow. The forwarding direciton is described by a tangent vector t.
- Parameters
xx (2d array, x coordinates) –
yy (2d array, y coordinates) –
t (1d array with two elements specifying a direction of the flow (y, x)) –
U (float, velocity magnitude) –
c (float, a parameter relevant for decay=='linear' or 'exponential) – … This parameter determines where the field starts to decrease either linearly or exponentially … e.g. c = 100, decay==’linear’, t=(0, 1) …… This makes a field with a constant flow up to xx<c (c and xx must share the units) …… Then, the field linearly decays to zero at max(xx)
decay (str, options: ["linear", "exponential"] default: None) – … If given, the field decays to zero at the edge of the field
decay_scale (float, a relevant parameter for an exponentially decaying field, default: 1.) – … The higher, decay_scale is, the flow decays faster to zero. … udata = U * np.exp(- decay_scale * dd / np.max(dd)) … If given, the field decays to zero
- Returns
udata
- Return type
3d numpy array of a unidirectional field
- tflow.velocity.get_window_radial(xx, yy, zz=None, wtype='hamming', rmax=None, duration=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, n=500)
General method to get a window with shape (xx.shape[:], duration) or (xx.shape[:]) if duration is None … Window types:
boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs a decay scale), tukey (needs taper fraction)
- Parameters
xx (nd array) – x-coordinate of the spatial grid of udata
yy (nd array) – y-coordinate of the spatial grid of udata
zz (nd array) – y-coordinate of the spatial grid of udata
wtype (str) – name of window function such as ‘hamming’, ‘flattop’
rmax (float) – window function returns zero for r > rmax
duration (int, default: None) – specifies the temporal dimension of the returning window function.
x0 (int, default: 0) – used to specify the region of the returning window function. When coordinates outside the specified region is given to the window function, it returns 0.
x1 (int, default: None) – used to specify the region of the returning window function. When coordinates outside the specified region is given to the window function, it returns 0.
y0 (int, default: 0) –
y1 (int, default: None) – used to specify the region of the returning window function. When coordinates outside the specified region is given to the window function, it returns 0.
z0 (int, default: 0) –
z1 (int, default: None) – used to specify the region of the returning window function. When coordinates outside the specified region is given to the window function, it returns 0.
n (int, default: 500) – number of data points when 1D window function is called for the first time. The higher n is, the returning windowing function is more accurate.
- Returns
window/windows (nd array)
… window (hamming window with the shape as xx)
… window (hamming window with the shape (xx.shape[:], duration))
- tflow.velocity.grad(U, dx=1.0, dy=1.0, dz=1.0, xyz_orientations=array([1, - 1, 1]), xx=None, yy=None, zz=None)
Computes divergence of a velocity field
- Parameters
U (numpy array) – … U has a shape (height, width, depth, duration) or (height, width, depth) (3D) … U may have a shape (height, width, duration) or (height, width) (2D)
- Returns
grad_U – … grad_U has a shape (3, height, width, depth, duration) (3D) or (2, height, width, duration) (2D)
- Return type
numpy array
- tflow.velocity.griddata_easy(x, y, data, xi=None, yi=None, dx=None, dy=None, nx=10, ny=10, method='nearest', xmin=None, xmax=None, ymin=None, ymax=None, fill_value=None)
Conduct 2D interpolation of data from a nonuniformly spaced rectangular grid … A wrapper of scipy.interplate.griddata
- Parameters
xx (nd array-like) – x-coordinate of scattered data this will be flattened when passed to griddata
yy (nd array-like) – y-coordinate of scattered data this will be flattened when passed to griddata
data (nd array-like) – values of scattered data this will be flattened when passed to griddata
xi (1d array) – x-coordinate of the interpolated grid … The array must be monotonically increasing. … If None, xi = np.arange(xmin, xmax, dx)
yi (1d array) – y-coordinate of the interpolated grid … The array must be monotonically increasing. … If None, yi = np.arange(ymin, ymax, dy)
dx (float) – spacing of ‘xi’ if ‘xi’ is not given
dy (float) – spacing of ‘xi’ if ‘xi’ is not given
nx (int) – if ‘dx’ were not given, dx is set as (xmax-xmin)/nx
ny (int) – if ‘dy’ were not given, dx is set as (ymax-ymin)/ny
method (method of 2D interpolation) – … Options: ‘nearest’, ‘linear’, ‘cubic’
xmin (float, minimum x value of the interpolated grid) –
xmax (float, maximum x value of the interpolated grid) –
ymin (float, minimum y value of the interpolated grid) –
ymax (float, maximum y value of the interpolated grid) –
fill_value (float, value to fill in the interpolated grid, default is None) –
- Returns
xxi (2d array) – x-coordinate of the grid
yyi (2d array) – y-coordinate of the grid
data_i (2d array) – values on the grid
- tflow.velocity.interpolate_scalar_field_at_instant_of_time(field, xx, yy, zz=None, t=0, bounds_error=False, **kwargs)
Returns an interpolating function a scalar field (energy, enstrophy etc.) at instant of time using scipy.interpolate.RegularGridInterpolator … field_i( (y, x, z) ): the field at (x, y, z)
- Parameters
field (ndarray, scalar field, shape (height, width, (depth), duration)) – … The most right index of “field” is the time index.
xx (2d/3d array, x-grid) –
yy (2d/3d array, y-grid) –
zz (2d/3d array, z-grid, optional) –
t (int, time index, default: 0) –
bounds_error (bool, default: False) – … If True, when interpolating outside of the input data, raise a ValueError.
kwargs (kwargs will be passed to scipy.interpolate.RegularGridInterpolator()) –
- Returns
field_i
- Return type
interpolating function of the scalar field at time t
- tflow.velocity.interpolate_udata_at_instant_of_time(udata, xx, yy, zz=None, t=0, bounds_error=False, **kwargs)
Returns interpolating functions of each spatial component of a velocity field at instant of time using scipy.interpolate.RegularGridInterpolator … Returns a tuple (f_ux, f_uy, f_uz) … f_ux( (y, x, z) ) gives ux at (x, y, z)
- Parameters
udata (ndarray, shape (dim, height, width, (duration))) –
xx (2d/3d array, x-grid) –
yy (2d/3d array, y-grid) –
zz (2d/3d array, z-grid, optional) –
t (int, default: 0) – This function generates interpolating functions of udata at time index of
bounds_error (bool, default: False) – … If True, when interpolating outside of the input data, raise a ValueError.
kwargs (kwargs will be passed to scipy.interpolate.RegularGridInterpolator()) –
- Returns
f_ux (interpolating function of ux at time t)
f_uy (interpolating function of uy at time t)
f_uz (interpolating function of uz at time t, optional)
- tflow.velocity.interpolate_vector_field_at_instant_of_time(vfield, xx, yy, zz=None, t=0, bounds_error=False, **kwargs)
Returns interpolating functions of a vector field (e.g. vorticity field: omega) using scipy.interpolate.RegularGridInterpolator … e.g.
Input: vorticity field (omega) with shape (3, height, width, depth, duration) Output: a list of interpolating functions for each spatial direction- [omega_x, omega_y, omega_z]
- Parameters
vfield (ndarray, vector field, shape (dim, height, width, (depth), duration)) –
xx (2d/3d array, x-grid) –
yy (2d/3d array, y-grid) –
zz (2d/3d array, z-grid, optional) –
t (int, time index, default: 0) –
bounds_error (bool, default: False) –
True (... If) –
data (when interpolating outside of the input) –
ValueError. (raise a) –
kwargs (kwargs will be passed to scipy.interpolate.RegularGridInterpolator()) –
- Returns
funcs – … funcs[n] is the interpolating function of the vfield[n, …, t]
- Return type
list, interpolating functions
- tflow.velocity.isRingFormed(sl, sv, f, P=1.0, do=25.6, dp=160.0, n=8, ldmax=4.5, amax=18000.0)
Returns if a commanded ring is formed in the turbulent blob experiment … A ring is formed regardless of commanded stroke length and velocity; however, the piston may not move as commanded … This function tells if a ring was formed cleanly … Condition 1: L/D<=4… Ring is accompanied by a jet if L/D>4 … Condition 2: Piston moves with finite acceleration. Effective velocity, veff, is always less than a certain value. … Condition 3: Oscillatory motion sets the minimum velocity of the piston needs to be.
- Parameters
sl (float/1d array, commanded stroke length in mm) –
sv (float/1d array, commanded stroke velocity in mm/s) –
f (float/1d array, driving frequency of the piston) –
P (float, velocity shape factor <v^2>/<v>^2>=1. Experimentally, this is around 1.2.) –
do (float, diameter of the orifice) –
dp (float, diameter of the piston) –
n (int, number of orifices of the chamber) –
amax (float, maximum acceleration of the piston. Experimentally, this is 1.8e4 mm/s2. Relevant to Condition2.) –
- Returns
isRingFormed (bool, True if the ring could be formed at the given driving frequency)
(the formed ring would have the same or similar properties as the rings formed by a corresponding pulse)
False if the formed ring would have different properties from the rings formed by a corresponding pulse.
- tflow.velocity.is_data_derived(savepath, datanames, verbose=False, mode=None)
Check whether quantities of your interest is derived Returns True if the quantities exist in the h5 file, False otherwise
- Parameters
savepath (str, path to the h5 file) –
datanames (list of str, names of the quantities of interest) –
verbose (bool, whether to print out the names of the quantities that are not found) –
mode (str, 'hard' or 'easy') –
- … if mode==’easy’,
it checks whether quantities of derive_easy() are in savepath
- … if mode==’hard’,
it checks whether quantities of derive_hard() are in savepath
- tflow.velocity.kolmogorov_53(k, k0=50)
Customizable Kolmogorov Energy spectrum Returns the value(s) of k0 * k^{-5/3}
- Parameters
k (array-like, wavenumber: convention is k= 1/L NOT 2pi/L) –
k0 (float, coefficient) –
- Returns
e_k
- Return type
power-law spectrum with exponent -5/3 for a given k and k0
- tflow.velocity.kolmogorov_53_uni(k, epsilon, c=1.6)
Universal Kolmogorov Energy spectrum Returns the value(s) of C epsilon^{2/3} k^{-5/3}
- Parameters
k (array-like, wavenumber) –
epsilon (float, dissipation rate) –
c (float, Kolmogorov constant c=1.6 (default)) –
k^(-5/3) (... E22(k) = c2 epsilon^(2/3)) –
k^(-5/3) –
k^(-5/3) –
c1 (...) –
1.6 (... If c =) –
0.491 (c1 =) –
1.125 (c2 =) –
values (... Exp.) –
- Returns
e_k
- Return type
array-like, Kolmogorov energy spectrum for a given range of k
- tflow.velocity.kronecker_delta(i, j)
kronecker_delta Delta function: delta_{i, j}
- Parameters
i (tensor index) –
j (tensor index) –
- Returns
- Return type
1 if i==j, 0 otherwise
- tflow.velocity.lamb_oseen_vortex_2d(xx, yy, x0=0, y0=0, gamma=1.0, a0=1.0, nu=1.0, t=0)
Return a 2D velocity field with a single Rankine vortex at (x0, y0)
- Parameters
xx (numpy array) – x-coordinate, 2d grid
yy (numpy array) – y-coordinate, 2d grid
x0 (float) – x-coordinate of the position of the rankine vortex
y0 (float) – y-coordinate of the position of the rankine vortex
gamma (float) – circulation of the rankine vortex
a (float) – core radius of the rankine vortex
- Returns
udata – … udata[0] = ux … udata[1] = uy
- Return type
nd array, velocity field
- tflow.velocity.lamb_oseen_vortex_line_3d(xx, yy, zz, x0=0, y0=0, z0=0, gamma=1.0, a0=1.0, nu=1.0, t=0, ux0=0, uy0=0, uz0=0, axis=2)
Returns a velocity field (udata with shape (3, nrows, ncols, nstacks) induced by a Lamb-Oseen voretx line of a diameter a0 and circulation gamma … Lambd-Oseen vortex core grows as sqrt{a0**2 + 4
- u t}
… Azimuthal velocity: utheta = gamma / (2 * np.pi * rr) * (1 - np.exp(- rr ** 2 / a ** 2)) … an orientation of a vortex can be specified … a rectilinear stream can be added along the x-/y-/z-direction
xx: 3d array, x-coordinate yy: 3d array, y-coordinate zz: 3d array, y-coordinate x0: float, x-coordinate of the point where the vortex line penetrates y0: float, y-coordinate of the point where the vortex line penetrates z0: float, z-coordinate of the point where the vortex line penetrates gamma: float, circulation a0: float, core radius nu: float, kinematic viscosity t: float, time,
… Lambd-Oseen vortex core grows as sqrt{a0**2 + 4
- u t}
ux0: float, a stream velocity, default = 0 uy0: float, a stream velocity, default = 0 uz0: float, a stream velocity, default = 0 axis: int, axis of the symmetry, default = 2 (z-axis)
… Choose from [0, 1, 2] corresponding to (y, x, z)
udata: 4d array, a velocity field (3, nrows, ncols, nstacks)
- tflow.velocity.laplacian(p, dx, dy, il=None, ir=None, jb=None, jt=None)
Returns Laplacian of p, d^2p/dx^2 + d^2/dy^2. If needed, specify how to grab the image of a point outside the domain. Otherwise, the d^2p/dx^2 or d^2/dy^2 term is not included on the boundary.
Source: https://anaconda.org/bfiedler/n090_streamfunctionvorticity2d/notebook?version=2018.07.28.0933
- e.g. # Compute vorticity from a stream function
laplacian(streamfunction, dx, dy)
- Parameters
p (2d array, a scalar field) –
dx (float, grid spacing in x) –
dy (float, grid spacing in y) –
il –
ir –
jb –
jt –
- Returns
lapl
- Return type
2d array
- tflow.velocity.low_pass_filter(data, fc, fs, order=5)
Apply low-pass filter to a 1D data (signal) … the signal must be sampled evenly
- Parameters
data (1d array-like) –
fc (float, cutoff frequency) –
fs (float, sampling frequency of data) –
- Returns
filtered
- Return type
1d array, low-pass filtered signal
- tflow.velocity.mag(udata)
Returns a norm of of udata
- Parameters
udata (nd array with a shape (dim, height, width, (depth), (duration))) –
- Returns
umag
- Return type
np.array with shape () or (duration, )
- tflow.velocity.make_blocks_from_2d_array(arr, nrows, ncols)
Return an array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array should look like n subblocks with each subblock preserving the “physical” layout of arr.
- Parameters
arr (M x N list or numpy array) –
nrows (int, number of rows in each block) –
ncols (int, number of columns in each block) –
- Returns
blocks
- Return type
numpy array with shape (n, nrows, ncols)
- tflow.velocity.make_movie(imgname=None, imgdir=None, movname=None, indexsz='05', framerate=10, crf=12, bkgColor=None, bkgWidth=800, bkgHeight=800, rm_images=False, save_into_subdir=False, start_number=0, framestep=1, ext='png', option='normal', overwrite=False, invert=False, add_commands=[], ffmpeg_path='/Users/takumi/Documents/git/tflow/tflow/ffmpeg')
Create a movie from a sequence of images using the ffmpeg supplied with ilpm. Options allow for deleting folder automatically after making movie. Will run ‘./ffmpeg’, ‘-framerate’, str(int(framerate)), ‘-i’, imgname + ‘%’ + indexsz + ‘d.png’, movname + ‘.mov’,
‘-vcodec’, ‘libx264’, ‘-profile:v’, ‘main’, ‘-crf’, ‘12’, ‘-threads’, ‘0’, ‘-r’, ‘100’, ‘-pix_fmt’, ‘yuv420p’])
- … ffmpeg is not smart enough to recognize a pattern like 0, 50, 100, 150… etc.
It tries up to an interval of 4. So 0, 3, 6, 9 would work, but this hinders practicality. Use the glob feature in that case. i.e. option=’glob’
- … As for images with transparent background, ffmpeg outputs a bad quality movie.
In that case, provide [bkgColor=’white’, bkgWidth=800, bkgHeight=800] … bkgWidth and bkgHeight must have the same aspect ratio as the images … this uses an option -filter_complex which is not compatible with the other filtering option -vf. … If one would like to use -vf for inverting images for example, one must code it differently
- Parameters
imgname (str) – … path and filename for the images to turn into a movie … could be a name of directory where images are stored if option is ‘glob’
movname (str) – path and filename for output movie (movie name)
indexsz (str) – string specifier for the number of indices at the end of each image (ie ‘file_000.png’ would merit ‘03’)
framerate (int (float may be allowed)) – The frame rate at which to write the movie
crf (int, 0-51) – … constant rate factor- the lower the value is, the better the quality becomes
rm_images (bool) – Remove the images from disk after writing to movie
save_into_subdir (bool) – The images are saved into a folder which can be deleted after writing to a movie, if rm_images is True and imgdir is not None
option (str) – If “glob”, it globs all images with the extention in the directory. Therefore, the images does not have to be numbered.
add_commands (list) – A list to add extra commands for ffmpeg. The list will be added before output name i.e. ffmpeg -i images command add_commands movie_name exmaple: add_commands=[‘-vf’, ‘ pad=ceil(iw/2)*2:ceil(ih/2)*2’]
- tflow.velocity.make_time_evo_movie_from_udata(qty, xx, yy, time, t=1, inc=100, label='$\\frac{1}{2} U_i U_i$ ($mm^2/s^2$)', x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, vmin=0, vmax=None, cmap='magma', option='scientific', draw_box=True, xlabel='$x$ ($mm$)', ylabel='$y$ ($mm$)', invert_y=False, savedir='./', qtyname='qty', framerate=10, ffmpeg_path='/Users/takumi/Documents/git/tflow/tflow/ffmpeg', overwrite=True, redo=False, notebook=True, verbose=False, box_kwargs={})
Make a movie about the running average (number of frames to average is specified by “t”)
- Parameters
qty (3D array (height, width, duration)) – … quantity to show as a movie (energy, enstrophy, vorticity, etc)
xx (2D array, x-coordinates (height, width)) –
yy (2D array, y-coordinates (height, width)) –
time (1D array, time) –
t (int, number of frames to average) –
inc (int, number of frames to skip between two frames) –
label (str, label of the quantity, default is '$frac{1}{2} U_i U_i$ ($mm^2/s^2$)') –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (z1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
vmin (float, default: 0, color range minimum) –
vmax (float, default: None, color range minimum) –
draw_box (bool, default: True, draw a box around the heatmap) –
xlabel (str, default: '$x$ ($mm$)') –
ylabel (str, default: '$y$ ($mm$)') –
savedir (str, default: './', directory where the movie is saved) –
qtyname (str, default: 'qty', name of the quantity) –
framerate (int, default: 10, framerate of the movie) –
ffmpeg_path (str, path to ffmpeg) –
overwrite (bool, default: True, if True, it overwrites the existing movie) –
redo (bool, default: False, if True, it generates the images again even if the movie exists) –
notebook (bool, default: True, if True, use the notebook to make the movie) –
- tflow.velocity.mask_udata(udata, mask)
Returns a numpy.masked array of udata … The shape of the mask must be one of ushape, ushape[1:], ushape[1:-1] where ushape=udata.shape
- Parameters
udata (nd array, v-field data) –
mask (md boolean array) –
ushape=udata.shape (... The shape of the mask must be one of) –
ushape[1 (], ushape[1:-1] where ushape=udata.shape) –
array (... The mask must be a boolean) –
hide (where True indicates values to) –
- Returns
udata
- Return type
numpy masked nd array
- tflow.velocity.median_filter_scaar_field(data, kernel_radius=1)
Filter input with a median filter using scipy.signal.medfilt() … data must have a shape of (…, duration)
A median filter will be applied on the stacks (span by axis=0, 1, …, -2) … The last axis is interpreted as a temporal axis of data
- Parameters
data (nd array) –
kernel_radius (int, default: 1) – … radius of the kernel of the median filter
- Returns
filtered – … Filtered data
- Return type
nd array
- tflow.velocity.median_filter_vector_field(vdata, kernel_radius=1)
Filter a vector field with a median filter using scipy.signal.medfilt() … data must have a shape of (dim, …, duration)
A median filter will be applied on the stacks (span by axis= 1, …, -2) … The last axis is interpreted as a temporal axis of data
- Parameters
data (nd array) –
kernel_radius (int, default: 1) – … radius of the kernel of the median filter
- Returns
filtered – … Filtered data
- Return type
nd array
- tflow.velocity.merge_simple_hdf5s(path2masterh5, paths2h5s2add, overwrite=False)
This function merges the datasets in H5FILES to H5MASTER … datasets in H5FILES must be located under the top directory (/DATASET1, /DATASET2, …) … If H5MASTER already contains the dataset(s), this function does not overwrite the existing data unless specified.
- Parameters
path2masterh5 (str, a path to the master h5 file (where the data in paths2h5s2add will be added)) –
paths2h5s2add (list of str, paths where the data to be added to the master h5 are stored.) –
overwrite (bool, default: False. If True, the data in path2masterh5 will be overwritten by the data in paths2h5s2add if it exists.) –
- Returns
- Return type
None
- tflow.velocity.moddirpath = '/Users/takumi/Documents/git/tflow/tflow'
Module designed to process a planar/volumetric velocity field - energy, enstrophy, vorticity fields - energy spectra - n-th order structure functions - dissipation rate - turbulent length scales
Philosophy: Prepare a velocity field array “udata”. Pass it to functions in this module to obtain any quantities related to turbulence. It should require a single line to obtain the desired quantity from a velocity field unless an intermediate step is computationally expensive. The primary example for this is an autocorrelation function which is used for various quantities like Taylor microscale.
udata = (ux, uy, uz) or (ux, uy) each ui has a shape (height, width, (depth), duration)
If ui-s are individually given, make udata like udata = np.stack((ux, uy))
Dependencies: h5py, tqdm, numpy, scipy, matplotlib
author: takumi matsuzawa
- tflow.velocity.model_energy_spectrum(k, epsilon, nu, L, c=1.6, p0=2, cL=6.78, ceta=0.4, beta=5.2)
Returns a model energy spectrum E(k)=c epsilon^(2/3) * k**(-5/3) f(kL) g(kEta)
- Parameters
k (1d array, wavenumbers) –
epsilon (float/1d array, dissipation rate) –
nu (float, viscosity) –
L (float, integral length scale) –
c (float, kolmogorov constant (default: 1.6)) –
p0 (float, power in the energy containing regime (default: 2, p0=4: Karman spectrum)) –
cL (float, a parameter related to the onset of the inertial range (cL=6.78, Pope p233)) –
ceta (float, a parameter related to the onset of the inertial range (ceta=0.4, Pope p233)) –
beta (float: strength of the exponential in the dissipation range) –
- Returns
ek
- Return type
1d array, energy spectrum
- tflow.velocity.natural_sort(arr)
natural-sorts elements in a given array alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy’s implementation in the comments)
e.g.- arr = [‘a28’, ‘a01’, ‘a100’, ‘a5’] … WITHOUT natural sorting,
-> [‘a01’, ‘a100’, ‘a28’, ‘a5’]
- … WITH natural sorting,
-> [‘a01’, ‘a5’, ‘a28’, ‘a100’]
- Parameters
arr (list or numpy array of strings) –
- Returns
sorted_array
- Return type
natural-sorted
- tflow.velocity.norm(udata)
Returns a normalized udata (a vector stored at every location is normalized)
- Parameters
udata (nd array with a shape (dim, height, width, (depth), (duration))) –
- Returns
normalized udata
- Return type
: nd array with the same shape as udata
- tflow.velocity.normalize_udata(udata)
Returns the normalized v-field
- Parameters
udata (nd array, v-field data) –
- Returns
norm_udata
- Return type
nd array, normalized v-field
- tflow.velocity.plot_energy_spectra(udata, dx, dy, dz=None, x0=0, x1=None, y0=0, y1=None, window='flattop', epsilon_guess=100000, nu=1.004, label='', plot_e22=False, plot_ek=False, fignum=1, t0=0, legend=True, loc=3)
A method to quickly plot the 1D energy spectra
- Parameters
udata (nd array, velocity field,) –
dx (float, grid spacing in x-direction) –
dy (float, grid spacing in y-direction) –
dz (float, grid spacing in z-direction) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (y1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
window (str, default: 'flattop', window function to be used in the FFT, see scipy.signal.get_window() for more options) –
epsilon_guess (float, default: 10 ** 5, estimate of the dissipation rate of the flow) –
nu (float, default: 1.004, kinematic viscosity of the fluid) –
label (str, default: '', label of the plot (e.g. 'Data on MM/DD/YY')) –
plot_e22 (bool, default: False, if True, plot the E22 energy spectrum) –
plot_ek (bool, default: False, if True, plot the 3D energy spectrum) –
fignum (int, default: 1, figure number) –
t0 (int, default: 0, index of the time to specify the instantaneous v-field) –
legend (bool, default: True, if True, plot legend) –
loc (int, default: 3, location of the legend) –
- Returns
fig (matplotlib.figure.Figure, figure object)
axes (tuple of two matplotlib.axes._subplots.AxesSubplot objects)
- tflow.velocity.plot_energy_spectra_avg_w_energy_heatmap(udata, dx, dy, dz=None, x0=0, x1=None, y0=0, y1=None, window='flattop', epsilon_guess=100000, nu=1.004, label='', plot_e11=True, plot_e22=False, plot_ek=False, plot_kol=False, plot_sv=True, color_ref='k', alpha_ref=0.6, fignum=1, legend=True, loc=3, crop_edges=5, yoffset_box=20, sb_txtloc=(- 0.1, 0.4), errorfill=True, vmin=0, vmax=100000, return_spectra=False, figparams=None)
A method to quickly plot the energy spectra (Time-averaged) and time-averaged energy
- Parameters
udata (nd array, velocity field,) –
dx (float, grid spacing in x-direction) –
dy (float, grid spacing in y-direction) –
dz (float, grid spacing in z-direction) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (y1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
window (str, default: 'flattop', window function to be used in the FFT, see scipy.signal.get_window() for more options) –
epsilon_guess (float, default: 10 ** 5, estimate of the dissipation rate of the flow) –
nu (float, default: 1.004, kinematic viscosity of the fluid) –
label (str, default: '', label of the plot (e.g. 'Data on MM/DD/YY')) –
plot_e22 (bool, default: False, if True, plot the E22 energy spectrum) –
plot_ek (bool, default: False, if True, plot the 3D energy spectrum) –
fignum (int, default: 1, figure number) –
t0 (int, default: 0, index of the time to specify the instantaneous v-field) –
legend (bool, default: True, if True, plot legend) –
loc (int, default: 3, location of the legend) –
crop_edges (int, default: 5, crop the edges of the energy spectra to remove the high frequency noise) –
yoffset_box (int, default: 20, y-offset of the energy heatmap with respect to the center of the box) –
sb_txtloc (tuple, default: (-0.1, 0.4), location of the scale bar text) –
return_spectra (bool, default: False, if True, return the values of energy spectra) –
- Returns
fig (matplotlib.figure.Figure, figure object)
axes (tuple of three matplotlib.axes._subplots.AxesSubplot objects)
spectra_dict (dict, optional. Returned if return_spectra is True)
- tflow.velocity.plot_energy_spectra_w_energy_heatmap(udata, dx, dy, dz=None, x0=0, x1=None, y0=0, y1=None, window='flattop', epsilon_guess=100000, nu=1.004, label='', plot_e22=False, plot_ek=False, fignum=1, t0=0, legend=True, loc=3, crop_edges=5, yoffset_box=20, sb_txtloc=(- 0.1, 0.4), vmax=63095.7344480193)
A method to quickly plot the energy spectra (snapshot) and time-averaged energy
- Parameters
udata (nd array, velocity field,) –
dx (float, grid spacing in x-direction) –
dy (float, grid spacing in y-direction) –
dz (float, grid spacing in z-direction) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (y1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
window (str, default: 'flattop', window function to be used in the FFT, see scipy.signal.get_window() for more options) –
epsilon_guess (float, default: 10 ** 5, estimate of the dissipation rate of the flow) –
nu (float, default: 1.004, kinematic viscosity of the fluid) –
label (str, default: '', label of the plot (e.g. 'Data on MM/DD/YY')) –
plot_e22 (bool, default: False, if True, plot the E22 energy spectrum) –
plot_ek (bool, default: False, if True, plot the 3D energy spectrum) –
fignum (int, default: 1, figure number) –
t0 (int, default: 0, index of the time to specify the instantaneous v-field) –
legend (bool, default: True, if True, plot legend) –
loc (int, default: 3, location of the legend) –
crop_edges (int, default: 5, crop the edges of the energy spectra to remove the high frequency noise) –
yoffset_box (int, default: 20, y-offset of the energy heatmap with respect to the center of the box) –
sb_txtloc (tuple, default: (-0.1, 0.4), location of the scale bar text) –
- Returns
fig (matplotlib.figure.Figure, figure object)
axes (tuple of three matplotlib.axes._subplots.AxesSubplot objects)
- tflow.velocity.plot_mean_flow(udata, xx, yy, f_p=5.0, crop_edges=4, fps=1000.0, data_spacing=1, umin=- 200, umax=200, tau0=0, tau1=10, yoffset_box=20.0)
A method to quickly plot the mean flow (Only applicable to 2D v-field), time-averaged energy and time-averaged enstrophy … dependencies: tflow.graph
- Parameters
udata (nd array, velcity field) –
xx (2d array, x-coordinates) –
yy (2d array, y-coordinates) –
f_p (float, forcing frequency) –
crop_edges (int, default: 5, crop the edges of the energy spectra to remove the high frequency noise) –
fps (int, frame rate of the udata) –
data_spacing (int, default=1, Forcing period = tau_p = int(1. / f_p * fps / data_spacing)) –
umin (float, ignore velocity values below this value) –
umax (float, ignore velocity values above this value) –
tau0 (float, used to plot vertical bands) –
tau1 (float, used to plot vertical bands) –
yoffset_box (int, default: 20, y-offset of the energy heatmap with respect to the center of the box) –
- Returns
fig (matplotlib.figure.Figure, figure object)
axes (tuple of three matplotlib.axes._subplots.AxesSubplot objects)
- tflow.velocity.plot_spatial_avg_energy(udata, time, x0=0, x1=None, y0=0, y1=None, t0=0, t1=None, ylabel='$\\frac{1}{2} \\langle U_i U_i\\rangle~(mm^2/s^2)$', xlabel='$t~(s)$', xmin=None, xmax=None, ymin=None, ymax=None, **kwargs)
Plots spatially averaged energy vs time … <0.5 ux^2 + uy^2 + uz^2>_space
- Parameters
udata (nd array- velocity field data) –
xx (2d array- positional grids (x-coordinate)) –
yy (2d array- positional grids (y-coordinate)) –
x0 (int, xx[y0:y1, x0:x1] will be plotted) –
x1 (int, xx[y0:y1, x0:x1] will be plotted) –
y0 (int, xx[y0:y1, x0:x1] will be plotted) –
y1 (int, xx[y0:y1, x0:x1] will be plotted) –
t0 (int, This function considers udata[..., t0:t1]) –
t1 (int, This function considers udata[..., t0:t1]) –
xlabel (str, xlabel) –
ylabel (str, ylabel) –
vmin (float, default: None, color range) –
vmax (float, default: None, color range) –
kwargs (passed to pcolormesh()) –
- Returns
fig (figure)
ax (axes)
- tflow.velocity.plot_time_avg_energy(udata, xx, yy, x0=0, x1=None, y0=0, y1=None, t0=0, t1=None, label='$\\frac{1}{2} \\langle U_i U_i\\rangle~(mm^2/s^2)$', xlabel='$x~(mm)$', ylabel='$y~(mm)$', vmin=None, vmax=None, **kwargs)
- Parameters
udata –
xx –
yy –
x0 (int, default: 0) –
x0 – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (t1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
int – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
default – … index to specify temporal range of data used to compute time average (udata[…, t0:t1:inc])
- tflow.velocity.plot_time_avg_enstrophy(udata, xx, yy, x0=0, x1=None, y0=0, y1=None, t0=0, t1=None, label='$\\frac{1}{2} \\langle \\omega_z ^2\\rangle~(1/s^2)$', xlabel='$x~(mm)$', ylabel='$y~(mm)$', vmin=None, vmax=None, **kwargs)
Plots time-averaged enstrophy
- Parameters
udata (nd array, velocity field,) –
dx (float, grid spacing in x-direction) –
dy (float, grid spacing in y-direction) –
dz (float, grid spacing in z-direction) –
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1, t0:t1])
x1 (int, default: None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1, t0:t1])
y0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1, t0:t1])
y1 (int, default: None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1, t0:t1])
t0 (int, default: None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1, t0:t1])
t1 (int, default: None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1, t0:t1])
label (str, default: '$frac{1}{2} langle omega_z ^2rangle~(1/s^2)$') –
xlabel (str, xlabel) –
ylabel (str, ylabel) –
vmin (float, default: None, color range) –
vmax (float, default: None, color range) –
kwargs (passed to pcolormesh()) –
- Returns
fig (figure)
ax (axes)
cc (mappable)
- tflow.velocity.poisson_fft(vort, invlapl)
Solves for psi in del^2 psi = vort
Source: https://anaconda.org/bfiedler/n090_streamfunctionvorticity2d/notebook?version=2018.07.28.0933
- Parameters
vort (2d array) –
invlapl (2d array) – … inverse laplacian operator … can be obtained from poisson_fft_prep()
- Returns
psi
- Return type
2d array
- tflow.velocity.poisson_fft_prep(Nx, Ny, dx, dy, lapl='discrete')
Returns the coefficients to multiply the vorticity Fourier amplitudes
Source: https://anaconda.org/bfiedler/n090_streamfunctionvorticity2d/notebook?version=2018.07.28.0933
- Parameters
Nx (int, number of grid points in x) –
Ny (int, number of grid points in x) –
dx (float, grid spacing in x) –
dy (float, grid spacing in y) –
lapl (str, 'discrete') –
- Returns
invlapl – … the coefficents for multiplying the vorticity Fourier amplitudes
- Return type
2d array
- tflow.velocity.pol2cart_udata(r, theta, udata_pol, x0=0, y0=0)
Transformation: Polar coord to Cartesian coord (r, phi, (ur, uphi)) -> (x, y, (ux, uy)) … Returns polar coordiantes AND velocity field in the standard basis
- Parameters
r (numpy array, radial distance) –
theta (numpy array, polar angle [-pi/2, pi/2] (angle from the z-axis)) –
udata_pol (numpy array, velocity field in the polar basis) –
- Returns
x, y, udata
- Return type
cartesian coordinates and velocity field in the standard basis
- tflow.velocity.process_large_udata(udatapath, func=<function get_spatial_avg_energy>, t0=0, t1=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, inc=10, notebook=True, reynolds_decomposition=False, clean=False, cutoff=inf, method='nn', median_filter=False, replace_zeros=True, overwrite_udatam=False, **kwargs)
(Intended for 3D velocity field data) Given a path to a hdf5 file which stores udata, it returns the result of functions without loading an entire udata onto RAM … example:
- results = process_large_udata(udatapath, func=get_spatial_avg_enstrophy,
inc=inc, dx=dx, dy=dy, dz=dz)
enst, enst_err = result
- Parameters
udatapath (str, path to a h5 file which stores udata) –
func (function) – … a function to compute a quantity you desire from udata
t0 (int, index of the first frame to be processed) –
t1 (int, default: None) – … If t1 were not given, it processes from the beginning to the end.
inc (int, use every "inc" frames, default: 10) – … temporal increment at which the function is called
x0 (int, default: 0) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int (z1) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default (None) – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
int – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
default – … index to specify volume of data to load (udata[:, y0:y1, x0:x1, z0:z1])
inc – … inc = 1 means a velocity field at every frame is used for processing.
notebook (bool, default: True) – … if True, it will use tqdm_notebook instead of tqdm to show progress
clean (bool, default: False) – … if True, it will clean the v-field data (udata) before processing … Cleaning involves removing spurious vectors by thresholding and median-filtering.
cutoff (float, default: np.inf) – … if clean=True, it will remove vectors with magnitude smaller than cutoff
median_filter (bool, default: False) – … if True and clean=True, it will apply a median filter to the v-field data.
replace_zeros (bool, default: True) –
… if True and clean=True, it will replace zeros with the nearest non-zero value. … This is sometimes necessary as zero values are default values instead of nan values for some softwares
(DaVis- STB).
kwargs (dict, default: {}, additional keyword arguments to be passed to func()) –
- Returns
datalist – … outputs of the function
- Return type
list
- tflow.velocity.psi2udata(psi, dx=1, dy=1, xy_orientations=array([1, 1]), xx=None, yy=None, coordinate_system='cartesian')
Derives udata from streamfunction psi. returns v = dq/dx and u= -dq/dy, on U-grid
Source: https://anaconda.org/bfiedler/n090_streamfunctionvorticity2d/notebook?version=2018.07.28.0933
- Parameters
psi (2d array, streamfunction values) –
dx (spacing in x-direction) –
dy (spacing in y-direction) –
xy_orientations (2d array, (x-orientation, y-orientation)) – … x-orientation: 1 if x increases from left to right, -1 if x decreases from left to right … y-orientation: 1 if y increases from bottom to top, -1 if y decreases from bottom to top
xx (2d array, x-coordinates of psi) –
yy (2d array, y-coordinates of psi) –
coordinate_system (string, default: 'cartesian', must be 'cartesian' or 'cylindrical') –
- Returns
udata
- Return type
2d array, velocity field (Cartesian)
- tflow.velocity.psi2udata_cylindrical(psi, rrho=None, zz=None, return_cartesian=False)
Derives udata from streamfunction psi in cylindrical basis.
Source: https://anaconda.org/bfiedler/n090_streamfunctionvorticity2d/notebook?version=2018.07.28.0933
- Parameters
psi (2d array, streamfunction values) –
rrho (2d array, rho-coordinates of psi) –
zz (2d array, z-coordinates of psi) –
return_cartesian (bool, default: False, if True, returns udata in cartesian coordinates) –
- Returns
udata – … if return_cartesian=True: udata = (ux, uy) … if return_cartesian=False: udata = (uz, urho)
- Return type
2d array, velocity field (cylindrical)
- tflow.velocity.rankine_vortex_2d(xx, yy, x0=0, y0=0, gamma=1.0, a=1.0)
Reutrns a 2D velocity field with a single Rankine vortex at (x0, y0)
- Parameters
xx (numpy array) – x-coordinate, 2d grid
yy (numpy array) – y-coordinate, 2d grid
x0 (float) – x-coordinate of the position of the rankine vortex
y0 (float) – y-coordinate of the position of the rankine vortex
gamma (float) – circulation of the rankine vortex
a (float) – core radius of the rankine vortex
- Returns
udata – … udata[0] = ux … udata[1] = uy
- Return type
nd array, velocity field
- tflow.velocity.rankine_vortex_line_3d(xx, yy, zz, x0=0, y0=0, z0=0, gamma=1.0, a=1.0, ux0=0, uy0=0, uz0=0, axis=2)
Reutrns a 3D velocity field with a Rankine vortex filament at (x0, y0, z)
- Parameters
xx (3d numpy grid) –
yy (3d numpy grid) –
zz (3d numpy grid) –
x0 (float, location of Rankine vortex filament) –
y0 (float, location of Rankine vortex filament) –
gamma (float, circulation) –
a (float, core radius) –
uz0 (float, constant velocity component in the z-direction) –
- Returns
udata – … udata[0] = ux … udata[1] = uy … udata[2] = uz
- Return type
nd array, velocity field
- tflow.velocity.read_data_from_h5(h5path, keys, return_dict=False, grpname=None, verbose=True)
Grabs data in a simply organized h5 file … Return the data stored at /keys[0], /keys[1], …
- Parameters
h5path (str, a path to a h5 file) –
keys (list, a list of keys) – if
- Returns
data_read (list of data stroed in a h5 file- [data0, data1, data2, …])
or
datadict (dictionary of data- {name0: data0, name1: data1, name2: data2, …})
- tflow.velocity.read_pickle(filename)
A wrapper to read a pickle file … There was a change in the default encoding type during some version update of the pickle package … This wrapper attempts to read a pickle file with different approaches.
- Parameters
filename (str, path to the pickle) –
- Returns
obj
- Return type
object stored in the given path
- tflow.velocity.read_simple_hdf5(datapath, grpname=None)
Returns a dictionary of data in a hdf5 1. ASSUMED DATA ARCHITECTURE (DEFAULT) … The hdf5 file must have a simple structure.
… /DataA … /DataB … /DataC
- … The returned dictionary has a structure like following.
datadit[‘DataA’] = values of DataA datadit[‘DataB’] = values of DataB …
2. OPTIONAL ARCHITECTURE … It is possible to read a COLLECTION of simple data
… /grp0/DataA … /grp0//DataB … /grp0//DataC … /grp1/DataA … /grp1//DataB … /grp1//DataC
- Parameters
datapath (str, path to the hdf5 file) –
grpname (str, default: None) – … ‘grpname’ is the name of the group in the h5 nameto be read.
- Returns
datadict – … datadict[‘DataA’] = values of /DataA
- Return type
dict
- tflow.velocity.remove_data_from_h5(h5path, keys)
Removes datasets from a h5 file
- tflow.velocity.remove_nans_for_array_pair(arr1, arr2)
remove nans or infs for a pair of 1D arrays, and returns the compressed arrays with the same length e.g.: arr1 = [0, 0.1, 0.2, np.nan, 0.4, 0.5], arr2 = [-1.2, 19.2. 155., np.inf, 0.1]
-> compressed_arr1 = [0, 0.1, 0.2, 0.5], compressed_arr2 = [-1.2, 19.2., 0.1]
- Parameters
arr1 (numpy array) – … may include np.nan and np.inf
arr2 (numpy array) – … may include np.nan and np.inf
- Returns
compressed_arr1 (numpy array) – … without any np
compressed_arr2 (numpy array)
- tflow.velocity.replace_nan_w_nn(data, notebook=False)
Nearest neighbor filling for nans in an array … Nearest neighbor filling of ND data … Do not use this function to interpolate udata! Use replace_nan_w_nn_udata(udata) instead. … This is not designed for udata because NN filling for ND data treats all axes equally. Since individual axis of udata means (velocity components, height, width, depth, duration), applying this function to udata requires care. … NN filling occurs from the right to left.
- i.e. array[n-3, n-2, n-1, n, n+1] = 100, np.nan, np.nan, np.nan, 200
-> 100, np.nan, np.nan, 200, 200 # Step1: Fill from the right first -> 100, 100, np.nan, 200, 200 # Step2: Then, fill from the left
-> 100, 100, 200, 200, 200 # Repeat Step1: Fill from the right
- Parameters
data (ND data with missing values (np.nan)) –
notebook (bool, default: False) – … If True, use tqdm_notebook instead of tqdm for a progress bar
- Returns
data
- Return type
ND data, missing values are filled with the nearest neighbor values.
- tflow.velocity.replace_nan_w_nn_udata(udata, notebook=True, showtqdm=True)
Nearest neighbor filling for nans in udata The fastest and most robust function to fill the missing values in udata
- Parameters
udata (ndarray, velocity field, shape (dim, height, width, depth, duration)) –
notebook (bool, default: False) – … If True, use tqdm_notebook instead of tqdm for a progress bar
showtqdm (bool, default: True) – … If True, show tqdm progress bar.
- Returns
udata_filled – … missing values (np.nan) are filled with the nearest neighbors
- Return type
ND array with shape (dim, height, width, depth, duration) or (dim, height, width, duration)
- tflow.velocity.replace_nans(array, max_iter=10, tol=0.05, kernel_radius=2, kernel_sigma=2, method='nn', notebook=True, verbose=False, showtqdm=True)
Replace NaN elements in an array using an iterative inpainting algorithm. The algorithm is the following: 1) For each element in the input array, replace it by a weighted average of the neighbouring elements which are not NaN themselves. The weights depends of the method type. If
method=localmean
weight are equal to 1/( (2*kernel_size+1)**2 -1 ) 2) Several iterations are needed if there are adjacent NaN elements. If this is the case, information is “spread” from the edges of the missing regions iteratively, until the variation is below a certain threshold.Generalized to nD array by Takumi Matsuzawa (UChicago) 2020/02/20
- Parameters
array (nd np.ndarray) –
replaced (an array containing NaN elements that have to be) –
max_iter (int, number of iterations) –
kernel_radius (int, size of the kernel: 2 * kernel_radius + 1) –
kernel_sigma (float, sigma of the gaussian kernel) –
method (str) –
- … the method used to replace invalid values. Valid options are
nearest neighbor filling (method = “nn”)- fast
filling with some constant (method = “fill”)- fast
filling with local mean (method = “localmean”)- slow
filling with an idw kernel (method = “idw”) - slow
- Returns
filled
- Return type
nd np.ndarray, input array with its NaN elements being replaced by some numbers
- tflow.velocity.resample(x, y, n=100, mode='linear')
Resample x, y … this is particularly useful to crete a evenly spaced data in log from a linearly spaced data, and vice versa
- Parameters
x (1d array) –
y (1d array) –
n (int, number of points to resample) –
mode (str, options are "linear" and "log") –
- Returns
x_new, y_rs
- Return type
1d arrays of new x and new y
- tflow.velocity.resample2d(x, ys, n=100, mode='linear', return_x_in_2d=False)
Resample x, y … this is particularly useful to crete a evenly spaced data in log from a linearly spaced data, and vice versa
- Parameters
x (1d array) –
ys (2d array) –
n (int, number of points to resample) –
mode (str, options are "linear" and "log") –
- Returns
x_new, y_rs
- Return type
1d arrays of new x and new y
- tflow.velocity.reynolds_decomposition(udata, t0=0, t1=None)
Apply the Reynolds decomposition to a velocity field Returns a mean field (time-averaged) and a fluctuating field
- Parameters
udata (numpy array) – … (ux, uy, uz) or (ux, uy) … ui has a shape (height, width, depth, duration) or (height, width, depth) (3D) … ui may have a shape (height, width, duration) or (height, width) (2D)
- Returns
u_mean (nd array, mean velocity field)
u_turb (nd array, turbulent velocity field)
- tflow.velocity.run_vel_statistics(dpath, inc=1, overwrite=False, t0=0, t1=None)
Calculate the statistics of the velocity field stored in dpath, and save the results … A helper for derive_easy()
- Parameters
dpath (str, path to the h5 file where velocity field is stored) –
inc (int, increment of the time index to be used to compute the statistics) – … inc==1: use all v-field data … inc==n: use every n-th frame of the v-field data
overwrite (bool, whether to overwrite the existing data in dpath) –
t0 (int, index of the first frame to be used to compute the statistics, [t0, t1)) –
t1 (int, index of the first frame to be used to compute the statistics, [t0, t1)) –
- Returns
- Return type
None
- tflow.velocity.sample_streamlines(udata, xx, yy, zz, npt=1, xmin=0, xmax=None, ymin=0, ymax=None, zmin=0, zmax=None, t0=0, t1=None, dt=0.01)
Returns n streamlines which go through n randomly chosen points inside xx, yy, zz … How this works: Basically, seed particles at the instant of time, and track how they move by the instantaneous vel field. … Streamlines are a family of curves that are instantaneously tangent to the velocity vector of the flow.
- Parameters
udata (nd array, shape (nx, ny, nz, 3)) –
xx (nd array, shape (nx, ny, nz)) –
yy (nd array, shape (nx, ny, nz)) –
zz (nd array, shape (nx, ny, nz)) –
npt (float, number of streamlines) – … to be precise, this is the number of points through which streamlines are drawn.
xmin (int) –
- … The initial points were taken from inside the box whose diagonal vertices are
(xx[ymin, xmin, zmin], yy[ymin, xmin, zmin], zz[ymin, xmin, zmin]) and (xx[ymax, xmax, zmax], yy[ymax, xmax, zmax], zz[ymax, xmax, zmax])
xmax (int, optional) –
ymin (int, optional) –
ymax (int, optional) –
zmin (int, optional) –
zmax (int, optional) –
t0 (int, time index, it gets the streamlines using udata[..., t0:t1]) –
t1 (int, time index, it gets the streamlines using udata[..., t0:t1]) –
dt (float, param to control the accuracy of the 3D streamlines) –
- Returns
strmlines_master – … length of the list is duration (t1-t0) …… strmlines_master[10] are a collection of n streamlines at frame 10 … If t1-t0 == 1 (given udata is a snapshot of the velocity field):
it returns strmlines_master[0]
- Return type
list
- tflow.velocity.scale_energy_spectrum(e_k, kk, epsilon=100000, nu=1.0034, e_k_err=None)
Scales raw energy spectrum by given dissipation rate and viscosity
- Parameters
e_k (numpy array) – spectral energy density
kk (numpy array) – wavenumber
epsilon (numpy array or float) – dissipation rate used for scaling. It could be 1D numpy array or float.
float (nu numpy array or) – viscosity used for scaling. It could be 1D numpy array or float.
e_k_err (numpy array) – error of dissipation rate used for scaling. It could be 1D numpy array or float.
- Returns
e_k_norm, k_norm if e_k_err is not given
e_k_norm, e_k_err_norm, k_norm if e_k_err is given
- tflow.velocity.scale_raw_structure_funciton_long(rrs, Dxxs, epsilon, Dxx_errs=None, nu=1.004, p=2)
Returns the scaled structure functions when raw structure function data are given … This allows users to scale the structure functions with epsilon and nu input by the users.
- Parameters
rrs (numpy array) – separation between two points, output of get_two_point_vel_corr_iso()
Dxxs (numpy array) – longitudinal structure function, output of get_two_point_vel_corr_iso()
Dxx_errs (numpy array) – error of longitudinal structure function, output of get_two_point_vel_corr_iso()
epsilon (numpy array or float) – dissipation rate
nu (float) – viscosity
p (int/float) – order of the structure function
- Returns
rrs_s (numpy array) – Scaled r
Dxxs_s (numpy array) – Scaled structure function
Dxx_errs_s (numpy array (optional)) – Scaled DLL error
- tflow.velocity.scaled_model_energy_spectrum(keta, epsilon, nu, L, c=1.6, p0=2, cL=0.1, ceta=0, beta=5.2)
Returns a model energy spectrum rescaled by eta and epsilon … model spectrum: E(k)=c epsilon^(2/3) * k**(-5/3) f(kL) g(kEta)
- e.g.
keta = np.logspace(-3, 0) plt.plot(keta, vel.scaled_model_energy_spectrum(keta, 1e5, 1.004, 10))
- Parameters
keta (1d array, wavenumbers * kolmogorov length) –
epsilon (float/1d array, dissipation rate) –
nu (float, viscosity) –
L (float, integral length scale) –
c (float, kolmogorov constant (default: 1.6)) –
p0 (float, power in the energy containing regime (default: 2, p0=4: Karman spectrum)) –
cL (float, a parameter related to the onset of the inertial range (cL=6.78, Pope p233)) –
ceta (float, a parameter related to the onset of the inertial range (ceta=0.4, Pope p233)) –
beta (float: strength of the exponential in the dissipation range) –
- Returns
eks
- Return type
1d array, rescaled energy spectrum
- tflow.velocity.show_h5_keys(dpath)
Displays a list of dataset names in h5- only the datasets stored under the top
- tflow.velocity.show_h5_subkeys(dpath, key)
Displays a list of dataset names in h5- only the datasets stored under the top
- tflow.velocity.slice_3d_scalar_field(field, xx, yy, zz, n, pt, spacing=None, basis=None, showtqdm=True, verbose=False, notebook=True, **kwargs)
Returns a spatially 2D udata which is on the cross section of a volumetric data … There are two ways to return the velocity field on the cross section.
In the standard basis (xyz, i.e. ux, uy, uz)
- In the NEW basis (which I call npq basis, i.e. un, up, uq)
the basis vector n is identical to the unit area vector of the cross section
- … By default, this function returns a 2D velocity field in the NEW basis (npq) as well as its coordinates in the same basis.
… This is a natural choice since the cross section is spanned by the new basis vectors p and q. … Any postional vector on the cross section is expresed by its linear combinations.
r = c1 hat{p} + c2 hat{q} (c1, c2) are the coordinates in the pq basis. (Technically, the basis vectors are n, p, q but the coefficient of the n basis vector is always zero on the cross section.) By default, this function returns… 1. velocity field in the NEW basis (npq) on the cross section 2. Coordinates in the pq basis (technically npq basis, but the coordinate in the basis vector n is always zero so I don’t return it)
- … You CAN retrieve the velocity field in the standard basis (xyz, i.e. ux, uy, uz).
Just set “u_basis” equal to “xyz” If you want both (in npq and xyz basses), set “u_basis” equal to “both”
- … If you want a change-of-basis matrix from basis A to basis B, use ilpm.vector.get_change_of_basis_matrix(basisA, basisB)
- e.g.
Mab = vec.get_change_of_basis_matrix(basis_xyz, basis_npq) # transformation matrix from xyz coords to npq coords Mba = np.linalg.inv(Mab) # the change-of-basis matrix is ALWAYS unitary.
Example:
- Parameters
filed (spatially 3d udata (3D or 4D array) with shape (height, width, depth, duration) or (dim, height, width, depth)) –
xx (3d array, grid of x-coordinate) –
yy (3d array, grid of y-coordinate) –
zz (3d array, grid of z-coordinate) –
n (1d array-like, area vector (it does not have to be normalized)) –
pt (1d array-like, xyz coordinates of a point on the plane (Note that n and pt uniquely defines a plane)) –
spacing (float, must be greater than 0. Sampling spatial resolution on the plane) –
show (bool, tflow.graph or takumi.graph is required. If True, it will automatically plot the sampled points on the) – cross section in a 3D view as well as the new basis vectors
method (str, interpolation method of udata, options: 'nn', 'localmean', 'idw') – … volumetric udata may contain lots of np.nan, and cleaning udata often results better results. … ‘nn’: nearest neighbor filling … ‘localmean’: filling using a direct covolution (inpainting with a neighbor averaging kernel) … ‘idw’: filling using a direct covolution (inpainting with a Gaussian kernel)
max_iter (int, parameter for replacng nans in udata clean_udata()) –
tol (float, parameter for replacng nans in udata clean_udata()) –
basis (3x3 matrix, column vectors are the basis vectors.) – … If given, the basis vectors are used to span the crosss section. … The basis vectors may be rotated or converted to right-handed at the end. …
apply_convention (bool, If True, it enforces the new basis to follow the convention (right-handed etc.)) –
u_basis (str, default: "npq", options: "npq", "xyz" / "standard" "std", "both") –
… the basis used to represent a velocity field on the plane … “npq”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (un, up, uq)
- (un, up, uq) = (velocity component parallel to the area vector,
vel comp parallel to the second basis vector p, vel comp parallel to the second basis vector q)
… “xyz”. “standard”, or “std”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (ux, uy, uz)
- Returns
udata_si_npq_basis (udata in the npq basis on the plane spanned by the basis vectors p and q.) – … its shape is (dim, height, width, duration) = (3, height, width, duration) … udata_si_npq_basis[0, …] is velocity u cdot hat{n} … udata_si_npq_basis[1, …] is velocity u cdot hat{p} … udata_si_npq_basis[2, …] is velocity u cdot hat{q}
pp (2d nd array, p-grid)
qq (2d nd array, q-grid)
- tflow.velocity.slice_3d_scalar_field_old(field, xx, yy, zz, n, pt, spacing=None, show=False, basis=None, apply_convention=True, notebook=True)
[DEPRECATED- slice_3d_scalar_field] Returns a spatially 2D udata which is on the cross section of a volumetric data … There are two ways to return the velocity field on the cross section.
In the standard basis (xyz, i.e. ux, uy, uz)
- In the NEW basis (which I call npq basis, i.e. un, up, uq)
the basis vector n is identical to the unit area vector of the cross section
- … By default, this function returns a 2D velocity field in the NEW basis (npq) as well as its coordinates in the same basis.
… This is a natural choice since the cross section is spanned by the new basis vectors p and q. … Any postional vector on the cross section is expresed by its linear combinations.
r = c1 hat{p} + c2 hat{q} (c1, c2) are the coordinates in the pq basis. (Technically, the basis vectors are n, p, q but the coefficient of the n basis vector is always zero on the cross section.) By default, this function returns… 1. velocity field in the NEW basis (npq) on the cross section 2. Coordinates in the pq basis (technically npq basis, but the coordinate in the basis vector n is always zero so I don’t return it)
- … You CAN retrieve the velocity field in the standard basis (xyz, i.e. ux, uy, uz).
Just set “u_basis” equal to “xyz” If you want both (in npq and xyz basses), set “u_basis” equal to “both”
- … If you want a change-of-basis matrix from basis A to basis B, use ilpm.vector.get_change_of_basis_matrix(basisA, basisB)
- e.g.
Mab = vec.get_change_of_basis_matrix(basis_xyz, basis_npq) # transformation matrix from xyz coords to npq coords Mba = np.linalg.inv(Mab) # the change-of-basis matrix is ALWAYS unitary.
Example:
- Parameters
filed (spatially 3d udata (3D or 4D array) with shape (height, width, depth, duration) or (dim, height, width, depth)) –
xx (3d array, grid of x-coordinate) –
yy (3d array, grid of y-coordinate) –
zz (3d array, grid of z-coordinate) –
n (1d array-like, area vector (it does not have to be normalized)) –
pt (1d array-like, xyz coordinates of a point on the plane (Note that n and pt uniquely defines a plane)) –
spacing (float, must be greater than 0. Sampling spatial resolution on the plane) –
show (bool, tflow.graph or takumi.graph is required. If True, it will automatically plot the sampled points on the) – cross section in a 3D view as well as the new basis vectors
method (str, interpolation method of udata, options: 'nn', 'localmean', 'idw') – … volumetric udata may contain lots of np.nan, and cleaning udata often results better results. … ‘nn’: nearest neighbor filling … ‘localmean’: filling using a direct covolution (inpainting with a neighbor averaging kernel) … ‘idw’: filling using a direct covolution (inpainting with a Gaussian kernel)
max_iter (int, parameter for replacng nans in udata clean_udata()) –
tol (float, parameter for replacng nans in udata clean_udata()) –
basis (3x3 matrix, column vectors are the basis vectors.) – … If given, the basis vectors are used to span the crosss section. … The basis vectors may be rotated or converted to right-handed at the end. …
apply_convention (bool, If True, it enforces the new basis to follow the convention (right-handed etc.)) –
u_basis (str, default: "npq", options: "npq", "xyz" / "standard" "std", "both") –
… the basis used to represent a velocity field on the plane … “npq”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (un, up, uq)
- (un, up, uq) = (velocity component parallel to the area vector,
vel comp parallel to the second basis vector p, vel comp parallel to the second basis vector q)
… “xyz”. “standard”, or “std”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (ux, uy, uz)
- Returns
udata_si_npq_basis (udata in the npq basis on the plane spanned by the basis vectors p and q.) – … its shape is (dim, height, width, duration) = (3, height, width, duration) … udata_si_npq_basis[0, …] is velocity u cdot hat{n} … udata_si_npq_basis[1, …] is velocity u cdot hat{p} … udata_si_npq_basis[2, …] is velocity u cdot hat{q}
pp (2d nd array, p-grid)
qq (2d nd array, q-grid)
- tflow.velocity.slice_udata_3d(udata, xx, yy, zz, n, pt, spacing=None, show=False, method='nn', max_iter=10, tol=0.05, median_filter=True, basis=None, u_basis='npq', showtqdm=True, verbose=False, notebook=True, **kwargs)
Returns a spatially 2D udata which is on the cross section of a volumetric data … There are two ways to return the velocity field on the cross section.
In the standard basis (xyz, i.e. ux, uy, uz)
- In the NEW basis (which I call npq basis, i.e. un, up, uq)
the basis vector n is identical to the unit area vector of the cross section
- … By default, this function returns a 2D velocity field in the NEW basis (npq) as well as its coordinates in the same basis.
… This is a natural choice since the cross section is spanned by the new basis vectors p and q. … Any postional vector on the cross section is expresed by its linear combinations.
r = c1 hat{p} + c2 hat{q} (c1, c2) are the coordinates in the pq basis. (Technically, the basis vectors are n, p, q but the coefficient of the n basis vector is always zero on the cross section.) By default, this function returns… 1. velocity field in the NEW basis (npq) on the cross section 2. Coordinates in the pq basis (technically npq basis, but the coordinate in the basis vector n is always zero so I don’t return it)
- … You CAN retrieve the velocity field in the standard basis (xyz, i.e. ux, uy, uz).
Just set “u_basis” equal to “xyz” If you want both (in npq and xyz basses), set “u_basis” as “both”
- … If you want a change-of-basis matrix from basis A to basis B, use ilpm.vector.get_change_of_basis_matrix(basisA, basisB)
- e.g.
Mab = vec.get_change_of_basis_matrix(basis_xyz, basis_npq) # transformation matrix from xyz coords to npq coords Mba = np.linalg.inv(Mab) # the change-of-basis matrix is ALWAYS unitary.
- … e.g. You want a v-field on a slice whose normal vector is obtained by rotating the unit z vector rotated by +45 degrees
theta = np.pi/180.*-45 # Convert degrees to rad n = [np.cos(theta), np.sin(theta), 0] # This is the normal vector of the slice pt = [0, 0, 0] # A point on the slice # Providing the new basis (npq basis) is optional # but this helps to speed up the process to find all available points on the slice basis = np.asarray([n, [0, 0, 1], [np.sin(theta), -np.cos(theta), 0]]).T # The transpose is necessary vdata, pp, qq = vel.slice_udata_3d(udata, xxx, yyy, zzz, n, pt, basis=basis, show=True) enst = vel.get_enstrophy(vdata[1:, …], xx=pp, yy=qq) graph.color_plot(pp, qq, enst[…, 0], fignum=1+i)
- … e.g. get a v-field on the xy plane (z=0)
n = [0, 0, 1] # area vector // unit z vector pt = [0, 0, 0] # the plane contains the origin basis = np.asarray([n, [1, 0, 0], [0, 1, 0]]).T vdata, pp, qq = vel.slice_udata_3d(udata, xxx, yyy, zzz, n, pt, basis=basis, show=True) enst = vel.get_enstrophy(vdata[1:, …], xx=pp, yy=qq) graph.color_plot(pp, qq, enst[…, 0], fignum=1+i)
- … e.g. Get a slice whose normal vector gets rotated about the y-axis gradually
t = 0 # slice the udata in the 1st frame thetas = np.linspace(0, 2*np.pi, 101) for i, theta in enumerate(thetas):
n = [np.sin(theta), 0, np.cos(theta)] vdata, pp, qq = vel.slice_udata_3d(udata[…, t], xxx, yyy, zzz, n, [xc, yc, zc],
basis = np.asarray([n, [np.cos(theta), 0, -np.sin(theta)], [0, 1, 0]]).T, apply_convention=False)
Example:
- Parameters
udata (spatially 3d udata (4D or 5D array) with shape (dim, height, width, depth, duration) or (dim, height, width, depth)) –
xx (3d array, grid of x-coordinate) –
yy (3d array, grid of y-coordinate) –
zz (3d array, grid of z-coordinate) –
n (1d array-like, area vector (it does not have to be normalized)) –
pt (1d array-like, xyz coordinates of a point on the plane (Note that n and pt uniquely defines a plane)) –
spacing (float, must be greater than 0. Sampling spatial resolution on the plane) –
show (bool, tflow.graph or takumi.graph is required. If True, it will automatically plot the sampled points on the) – cross section in a 3D view as well as the new basis vectors
method (str, interpolation method of udata, options: 'nn', 'localmean', 'idw') – … volumetric udata may contain lots of np.nan, and cleaning udata often results better results. … ‘nn’: nearest neighbor filling … ‘localmean’: filling using a direct covolution (inpainting with a neighbor averaging kernel) … ‘idw’: filling using a direct covolution (inpainting with a Gaussian kernel)
max_iter (int, parameter for replacng nans in udata clean_udata()) –
tol (float, parameter for replacng nans in udata clean_udata()) –
basis (3x3 matrix, column vectors are the basis vectors.) – … If given, these basis vectors are used to span the crosss section. … The basis vectors may be rotated or converted to be right-handed at the end. … See the example above for a sample input
apply_convention (bool, If True, it enforces the new basis to follow a convention that is) – … right-handed (n x p // q)
u_basis (str, default: "npq", options: "npq", "xyz" / "standard" "std", "both") –
… the basis used to represent a velocity field on the plane … “npq”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (un, up, uq)
- (un, up, uq) = (velocity component parallel to the area vector,
vel comp parallel to the second basis vector p, vel comp parallel to the second basis vector q)
… “xyz”. “standard”, or “std”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (ux, uy, uz)
- Returns
udata_si_npq_basis (udata in the npq basis on the plane spanned by the basis vectors p and q.) – … its shape is (dim, height, width, duration) = (3, height, width, duration) … udata_si_npq_basis[0, …] is velocity u cdot hat{n} … udata_si_npq_basis[1, …] is velocity u cdot hat{p} … udata_si_npq_basis[2, …] is velocity u cdot hat{q}
pp (2d nd array, p-grid)
qq (2d nd array, q-grid) – … plt.quiver(pp, qq, udata_si_npq_basis[1, …, 0], udata_si_npq_basis[2, …, 0])
- tflow.velocity.slice_udata_3d_old(udata, xx, yy, zz, n, pt, spacing=None, show=False, method='nn', max_iter=10, tol=0.05, median_filter=True, basis=None, apply_convention=True, u_basis='npq', notebook=True)
Returns a spatially 2D udata which is on the cross section of a volumetric data … There are two ways to return the velocity field on the cross section.
In the standard basis (xyz, i.e. ux, uy, uz)
- In the NEW basis (which I call npq basis, i.e. un, up, uq)
the basis vector n is identical to the unit area vector of the cross section
- … By default, this function returns a 2D velocity field in the NEW basis (npq) as well as its coordinates in the same basis.
… This is a natural choice since the cross section is spanned by the new basis vectors p and q. … Any postional vector on the cross section is expresed by its linear combinations.
r = c1 hat{p} + c2 hat{q} (c1, c2) are the coordinates in the pq basis. (Technically, the basis vectors are n, p, q but the coefficient of the n basis vector is always zero on the cross section.) By default, this function returns… 1. velocity field in the NEW basis (npq) on the cross section 2. Coordinates in the pq basis (technically npq basis, but the coordinate in the basis vector n is always zero so I don’t return it)
- … You CAN retrieve the velocity field in the standard basis (xyz, i.e. ux, uy, uz).
Just set “u_basis” equal to “xyz” If you want both (in npq and xyz basses), set “u_basis” as “both”
- … If you want a change-of-basis matrix from basis A to basis B, use ilpm.vector.get_change_of_basis_matrix(basisA, basisB)
- e.g.
Mab = vec.get_change_of_basis_matrix(basis_xyz, basis_npq) # transformation matrix from xyz coords to npq coords Mba = np.linalg.inv(Mab) # the change-of-basis matrix is ALWAYS unitary.
- … e.g. You want a v-field on a slice whose normal vector is obtained by rotating the unit z vector rotated by +45 degrees
theta = np.pi/180.*-45 # Convert degrees to rad n = [np.cos(theta), np.sin(theta), 0] # This is the normal vector of the slice pt = [0, 0, 0] # A point on the slice # Providing the new basis (npq basis) is optional # but this helps to speed up the process to find all available points on the slice basis = np.asarray([n, [0, 0, 1], [np.sin(theta), -np.cos(theta), 0]]).T # The transpose is necessary vdata, pp, qq = vel.slice_udata_3d(udata, xxx, yyy, zzz, n, pt, basis=basis, show=True) enst = vel.get_enstrophy(vdata[1:, …], xx=pp, yy=qq) graph.color_plot(pp, qq, enst[…, 0], fignum=1+i)
- … e.g. get a v-field on the xy plane (z=0)
n = [0, 0, 1] # area vector // unit z vector pt = [0, 0, 0] # the plane contains the origin basis = np.asarray([n, [1, 0, 0], [0, 1, 0]]).T vdata, pp, qq = vel.slice_udata_3d(udata, xxx, yyy, zzz, n, pt, basis=basis, show=True) enst = vel.get_enstrophy(vdata[1:, …], xx=pp, yy=qq) graph.color_plot(pp, qq, enst[…, 0], fignum=1+i)
- … e.g. Get a slice whose normal vector gets rotated about the y-axis gradually
t = 0 # slice the udata in the 1st frame thetas = np.linspace(0, 2*np.pi, 101) for i, theta in enumerate(thetas):
n = [np.sin(theta), 0, np.cos(theta)] vdata, pp, qq = vel.slice_udata_3d(udata[…, t], xxx, yyy, zzz, n, [xc, yc, zc],
basis = np.asarray([n, [np.cos(theta), 0, -np.sin(theta)], [0, 1, 0]]).T, apply_convention=False)
Example:
- Parameters
udata (spatially 3d udata (4D or 5D array) with shape (dim, height, width, depth, duration) or (dim, height, width, depth)) –
xx (3d array, grid of x-coordinate) –
yy (3d array, grid of y-coordinate) –
zz (3d array, grid of z-coordinate) –
n (1d array-like, area vector (it does not have to be normalized)) –
pt (1d array-like, xyz coordinates of a point on the plane (Note that n and pt uniquely defines a plane)) –
spacing (float, must be greater than 0. Sampling spatial resolution on the plane) –
show (bool, tflow.graph or takumi.graph is required. If True, it will automatically plot the sampled points on the) – cross section in a 3D view as well as the new basis vectors
method (str, interpolation method of udata, options: 'nn', 'localmean', 'idw') – … volumetric udata may contain lots of np.nan, and cleaning udata often results better results. … ‘nn’: nearest neighbor filling … ‘localmean’: filling using a direct covolution (inpainting with a neighbor averaging kernel) … ‘idw’: filling using a direct covolution (inpainting with a Gaussian kernel)
max_iter (int, parameter for replacng nans in udata clean_udata()) –
tol (float, parameter for replacng nans in udata clean_udata()) –
basis (3x3 matrix, column vectors are the basis vectors.) – … If given, these basis vectors are used to span the crosss section. … The basis vectors may be rotated or converted to be right-handed at the end. … See the example above for a sample input
apply_convention (bool, If True, it enforces the new basis to follow a convention that is) – … right-handed (n x p // q)
u_basis (str, default: "npq", options: "npq", "xyz" / "standard" "std", "both") –
… the basis used to represent a velocity field on the plane … “npq”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (un, up, uq)
- (un, up, uq) = (velocity component parallel to the area vector,
vel comp parallel to the second basis vector p, vel comp parallel to the second basis vector q)
… “xyz”. “standard”, or “std”: It returns velocity vectors in the npq basis. Returning udata[i, …] = (ux, uy, uz)
- Returns
udata_si_npq_basis (udata in the npq basis on the plane spanned by the basis vectors p and q.) – … its shape is (dim, height, width, duration) = (3, height, width, duration) … udata_si_npq_basis[0, …] is velocity u cdot hat{n} … udata_si_npq_basis[1, …] is velocity u cdot hat{p} … udata_si_npq_basis[2, …] is velocity u cdot hat{q}
pp (2d nd array, p-grid)
qq (2d nd array, q-grid)
- tflow.velocity.slicer(xxx, yyy, zzz, n, pt, basis=None, spacing=None, notebook=True)
Returns coordinates on a slice of a volume at a given point
… basisA: Cartesian basis of the volume … basisB: npq basis
- Parameters
xxx (nd array, shape (Ny, Nx, Nz), x-coordinates of the volume) –
yyy (nd array, shape (Ny, Nx, Nz), y-coordinates of the volume) –
zzz (nd array, shape (Ny, Nx, Nz), z-coordinates of the volume) –
n (tuple/list/1darray, shape (3,), normal vector of the plane (nx, ny, nz)) –
pt (tuple/list/1darray, shape (3,), point on the plane (x, y, z)) –
basis (3x3 array, default None, new basis) – … the new basis vectors are normal vector of the plane (n) and two orthogonal vectors (p, q) on the plane … the column vectors are the new basis vectors: [n, p, q] … If p, and q are specified, theses vectors are used to span the plane.
spacing (float, spacing between points spanned on the plane) –
notebook (bool, default True) – … if True, the tqdm_notebook is used instead of tqdm to show progress
- Returns
xxp (3d array, shape (Ny, Nx, Nz), x-coordinates of the slice)
yyp (3d array, shape (Ny, Nx, Nz), y-coordinates of the slice)
zzp (3d array, shape (Ny, Nx, Nz), z-coordinates of the slice)
pp (2d array, p-coordinates of the slice)
qq (2d array, q-coordinates of the slice)
Mab (3x3 array, change-of-basis matrix from basisA to basisB) – … np.matmul(Mab, vector_in_basiaA) = vector_in_basisB
Mba (3x3 array, change-of-basis matrix from basisB to basisA) – … np.matmul(Mba, vector_in_basisB) = vector_in_basisA
basis_npq (3x3 array, basisB (npq basis)) – … the column vectors are the new basis vectors: [n, p, q] … If p and q were not specified, this code randomly generates orthogonal basis to span the plane.
- tflow.velocity.slicer_old(xx, yy, zz, n, pt, basis=None, spacing=None, apply_convention=True, show=False, notebook=True, debug=False)
DEPRICATED (this slicer function uses a brute-force approach. Use slicer() instead.
Samples points on the cross section of a volume defined by 3D grid (xx, yy, zz) in two different bases and transformation matrices … The area vector (normal to the cross section) and a point on the cross section must be supplied. … It returns xs, ys, zs, ps, qs, ns, Mac, Mca, basisC (xyz coordinates, coordinates in a different basis, transformation matrices, the new basis)
- Details:
Cartesian coordinates use a standard basis (e1, e2, e3). This is not a natural basis for an arbitrary cross section of a cuboid since it is a 2d field embedded in 3d! Hence, a new basis should be created to extract a 2d slice of a volumetric data. We denote the coordinates of the pts in the new basis (n, p, q). The first basis vector is a unit area vector of the cross section. This basis is orthonormal by construction, and the transformation between the bases is unitary (i.e. length conserving) This way, the final outputs are literally the pts on the cross section of a cuboid.
- How it works:
Create an arbitrary orthonormal basis, one of which is a unit area vector given by you
Find points which are intersections of the plane and the cuboid
3. Using the intersecting points and the constructed basis (BasisB), it figures out how much the basis vectors need to span to cover the entire cross section 4. It samples points within the bounds set by Step 3. (This could take seconds) 5. The basis vectors (of basisB) are not usually aligned with the direction along the longest direction of the cross section. Fix the basis vector directions based on the sampled points. The new basis is called basisC. 6. Get a change-of-basis matrix from ilpm.vec or tflow.vec between the standard basis (basisA) and basisC 7. Apply conventions on the basisC.
The diretion with a LONGER side of the cross section is always called p.
The direction of increase in p is the same direction as x. (The same goes for q and y)
Enforce the basisC to be right-handed. n x p = q
Transform the xyz coordinates into npq coordinates using the matrix obtained in Step 6
Return xyz coordinates and npq coordinates and tranformation matrices (Mac: change-of-basis matrix FROM basisA to basisC)
- NEW (Dec 2022):
Efficient algorithm:
e.g. 1.
# xx, yy, zz = get_equally_spaced_grid(udata_stb) # if you have 3D udata x, y, z = np.arange(50), np.arange(30), np.arange(40) xx, yy, zz = np.meshgrid(y, x, z)
n = [0.1, -0.1, 0.4] # Area vector (x, y, z) pt = [0, 0, 10] # Cartesian coordinates of a point which lives on the plane (x, y, z) xs, ys, zs, ps, qs, ns, Mac, Mca, basis = slicer(xx, yy, zz, n, pt, show=False) plt.scatter(ps, qs)
# Get a different point on the cross section in xyz pt_a = np.asarray([0, -10, 20]) # xyz coordinate of a point pt_c = np.matmul(Mac, pt_a) # npq coordinate of the same point new_pt_c = pt_c + basis[:, 1] * 2.5 + basis[:, 2] * -4 # another point on the cross seciton but in basisC new_pt_a = np.matmul(Mca, new_pt_c) # xyz coordinate of the new point
# Get different points on the cross section in xyz pts_a = np.asarray([0, -10, 20], [-2, -11, 26]).T # xyz coordinate of a point- Shape must be (3, m) pts_c = np.matmul(Mac, pts_a) # npq coordinate of the same point new_pts_c = pts_c * 0.5 # points on the cross seciton but in basisC new_pts_a = np.matmul(Mca, new_pts_c) # xyz coordinate of the new points
- Tips:
If you have Takumi’s plotting module (found at takumi.graph or takumi’s github, or ask takumi) one can easily visualize the cross section by uncommenting the sections in the function AND setting “show=True”.
- Parameters
xx (3d numpy array, x coordinates of udata is assumed) –
yy (3d numpy array, y coordinates of udata is assumed) –
zz (3d numpy array, z coordinates of udata is assumed) –
n (1d array-like, area vector in the standard basis (no need to be normalized)) –
pt (1d array-like, a Cartesian coordinate of a point which lives on the cross section (x, y, z)) –
basis (1d array-like, use a user-specified basis instead of a randomly created orthonormal basis for basisB) – … I do not recommend passing a basis unless there is a reason such as repeatability. This might give you unexpected errors.
spacing (float, value must be greater than 0. Spatial resolution of the sampled grid. If None, it uses the spacing of xx) –
show (bool, If True, it plots sampled points on the cross section as well as a cuboid (in a wire frame) both in 3D and 2D.) – … You must have Takumi’s latest plotting module to work. This is not absolute dependencies for public version. Therefore, ask Takumi to how to activate it.
debug (bool, for developers) – … If True, it prints the basisB and basisC at the end of the code.
- Returns
xs, ys, zs, npq_coords[1, (], npq_coords[2, :], npq_coords[0, :], Mac, Mca, basisC)
… Cartesian coordinats of points on the cross section defined by its normal vector and a containing point
… New coordinates (n, p, q)- for usefulness, the function outputs in order of (p, q, n). n should be always zero.
You should print out the values of n whenever you are in doubt.
… Mac (change-of-basis matrix from basis A (standard basis) to basisC)
… Mca (change-of-basis matrix from basis C to basis A (standard basis)- inverse of Mac)
… basisC (new basis for npq coordinates)
- tflow.velocity.smooth(x, window_len=11, window='hanning', log=False)
smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with a given signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal.
- Parameters
x (the input signal) –
window_len (the dimension of the smoothing window; should be an odd integer) –
window (the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman') – flat window will produce a moving average smoothing.
- Returns
- Return type
the smoothed signal
Example
t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.filter
TODO: the window parameter could be the window itself if an array instead of a string NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
- tflow.velocity.smoothAlongAxis(data, n=5, window='hanning')
Takes a 2D array, returns a smooth array along a axis using a specified kernel
- tflow.velocity.sort_n_arrays_using_order_of_first_array(list_of_arrays, element_dtype=<class 'tuple'>)
Sort a list of N arrays by the order of the first array in the list e.g. a=[2,1,3], b=[1,9,8], c=[‘a’, ‘b’, ‘c’]
[a, b, c] -> [(1, 2, 3), (9, 1, 8), (‘b’, ‘a’, ‘c’)]
- Parameters
list_of_arrays (a list of lists/1D-arrays) –
element_dtype (data type, default: tuple) –
… This argument specifies the data type of the elements in the returned list … The default data type of the element is tuple because this functon utilizes sorted(zip(…)) … E.g. element_dtype=np.ndarray
- -> [a, b, c] -> [np.array([1, 2, 3]),
np.array([9, 1, 8], np.array([‘b’, ‘a’, ‘c’], dtype=’<U1’]
- Returns
list_of_sorted_arrays
- Return type
list of sorted lists/1D arrays
- tflow.velocity.sph2cart(r, theta, phi, xc=0, yc=0, zc=0)
Transformation from spherical to cartesian coordinates
- Parameters
r (radial distance) –
theta (polar angle [-pi/2, pi/2] (angle from the z-axis)) –
phi (azimuthal angle [-pi, pi] (angle on the x-y plane)) –
xc (float, origin at (xc, yc, zc)) –
yc (float, origin at (xc, yc, zc)) –
zc (float, origin at (xc, yc, zc)) –
- Returns
x, y, z
- Return type
cartesian coordinates
- tflow.velocity.sph2cart_velocity(ur, utheta, uphi, ttheta, pphi)
Transformation: spherical to cartesian (r, theta, phi, (ur, utheta, uphi)) -> (x, y, (ux, uy, uz))
z = r cos theta y = r sin theta sin phi x = r sin theta cos phi
Spherical coorrdinates: (r, theta, phi) = (radial distance, polar angle, azimuthal angle) r: radius theta: polar angle [-pi/2, pi/2] (angle from the z-axis) phi: azimuthal angle [-pi, pi] (angle on the x-y plane)
http://www.astrosurf.com/jephem/library/li110spherCart_en.htm
- Parameters
ur (numpy array, radial component of velocity field in the spherical basis) –
utheta (numpy array, polar component of velocity field in the spherical basis) –
uphi (numpy array, azimuthal component of velocity field in the spherical basis) –
ttheta (numpy array, polar angle [-pi/2, pi/2] (angle from the z-axis)) –
pphi (numpy array, azimuthal angle [-pi, pi] (angle on the x-y plane)) –
- Returns
ux (numpy array, x-component of velocity field (Cartesian))
uy (numpy array, y-component of velocity field (Cartesian))
uz (numpy array, z-component of velocity field (Cartesian))
- tflow.velocity.square_udata(udata, mode='edge', **kwargs)
Pad zeros to udata to make its spatial dimensions into a square or a cube … Taking a spectrum of a rectangularly shaped array could cause further aliasing. In order to combat this, one may square/cubidize udata before taking the spectrum by padding zeros around the obtained field. :param udata: :param pad_value: :type pad_value: float, value used to pad udata
- Returns
- Return type
squared_udata_padded_with_zero
- tflow.velocity.suggest_name2write(filepath)
Returns a new filepath with a version number if a file with a given path already exists. Otherwise, it returns the given string
- Parameters
filepath (str) –
- Returns
newfilepath
- Return type
new filepath with a version number if the file already exists
- tflow.velocity.suggest_udata_dim2load(dpath, p=1.0, n=5, show=True, return_tuple=False, return_None=True)
Returns a dictionary of inds = {“x0”: x0, “x1”: x1, “y0”: y0, “y1”: y1, “z0”: z0, “z1”: z1} which can be used to load udata via get_udata_from_path(…, **inds) … Estimating a reasonable volume for analysis is crucial to reduce the computation time since inpainting data is the rate-limiting step most of the time. … Estimating the reasonable volume in udata is done by counting the number of nans in the data.
- Parameters
dpath (str, path to a udata (h5)) –
p (... The higher) –
domain (...) –
p – … usually, STB-generated udata contains slices with all nans along z. … You do not want to inpaint this! … So keep p around 1 to be reasonable.
volume. (it returns a bigger) – … usually, STB-generated udata contains slices with all nans along z. … You do not want to inpaint this! … So keep p around 1 to be reasonable.
n (int, number of time slices used for the estimation, default: 5) –
usually (...) –
much (the nan distribution does not vary) –
slices (so use only a couple of) –
show (bool, default:True) –
True (... If) –
axis (show nan distribution along each) –
return_tuple (bool, default: False) –
(x0 (... If one wants) –
x1 –
y0 –
y1 –
z0 –
reason (z1) instead of a dictionary for some) –
True. (set this) –
Typically (...) –
("x0" (one likes to pass this information to a function with the kwargs) –
"x1" –
etc.) –
:param : :param so simply pass the default output (which is a dictionary) like **dictionary to unpack.:
- Returns
ind_dict – … ind_dict = {“x0”: x0, “x1”: x1, “y0”: y0, “y1”: y1, “z0”: z0, “z1”: z1} … e.g.- get_udata_from_path(…, **ind_dict)
- Return type
dict, indices that can be used to load udata
- tflow.velocity.truncateXY(xx, yy, x0=0, x1=None, y0=0, y1=None)
Returns a truncated grid
- Parameters
xxx (2d array, x-coordinate) –
yyy (2d array, y-coordinate) –
x0 (int, index used to truncate a 2d array like xx[y0:y1, x0:x1]) –
x1 (int, index used to truncate a 2d array like xx[y0:y1, x0:x1]) –
y0 (int, index used to truncate a 2d array like xx[y0:y1, x0:x1]) –
y1 (int, index used to truncate a 2d array like xx[y0:y1, x0:x1]) –
- Returns
xx[y0
- Return type
y1, x0:x1], yy[y0:y1, x0:x1]
- tflow.velocity.truncateXYZ(xxx, yyy, zzz, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None)
Returns a truncated grid
- Parameters
xxx (3d array, x-coordinate) –
yyy (3d array, y-coordinate) –
zzz (3d array, z-coordinate) –
x0 (int, index used to truncate a 3d array like xxx[y0:y1, x0:x1, z0:z1]) –
x1 (int, index used to truncate a 3d array like xxx[y0:y1, x0:x1, z0:z1]) –
y0 (int, index used to truncate a 3d array like xxx[y0:y1, x0:x1, z0:z1]) –
y1 (int, index used to truncate a 3d array like xxx[y0:y1, x0:x1, z0:z1]) –
z0 (int, index used to truncate a 3d array like xxx[y0:y1, x0:x1, z0:z1]) –
z1 (int, index used to truncate a 3d array like xxx[y0:y1, x0:x1, z0:z1]) –
- Returns
xxx[y0
- Return type
y1, x0:x1, z0:z1], yyy[y0:y1, x0:x1, z0:z1], zzz[y0:y1, x0:x1, z0:z1]
- tflow.velocity.write_hdf5_dict(filename, datadict, attrdict=None, overwrite=False, verbose=True)
Writes data in data_dict = {‘varname0’: var0, ‘varname1’: var1, …} to a h5 file - A quick function to write multiple data to a h5 file
- Parameters
filepath (str) – … file path where data will be stored. (Do not include extension- .h5)
datadict (dict, a collection of data to be stored in the h5 file) –
… data_dict = {‘varname0’: var0, ‘varname1’: var1, …} … data will be stored in the h5 file under the group /varname0, /varname1, …
and can be accessed by … with h5py.File(filepath, mode=’r’):
data = hf[key][:]
attrdict (dict, default: None, metadata of the data) –
… Attributes of data to be stored in the h5 file … Organize the attributes of a variable like this:
attrdict = {‘varname0’: {‘attr0’: value0, ‘attr1’: value1, …}, …} … attrdict = {‘piv000’: {‘int_win’: 32, ‘date’: 01012020, ‘software’: ‘DaVis’},
’piv001’: {‘int_win’: 16, ‘date’: 01012020, ‘software’: ‘PIVLab’}, …}
bool (overwrite, default: False) –
verbose (bool, default: True) – … print where the data is stored
- Returns
- Return type
None
- tflow.velocity.zoom(qty, xxx, yyy, zzz, zf=2, bounds_error=False)
A quick function to linearly interpolate 3D data by an integer factor … xxx, yyy, zzz = np.meshgrid(x,y,z) … Returns data and positional grids at different resolution
- Parameters
qty (3d array, a regular grid (data at (x, y, z)) –
xxx (3d array, a regular grid (x component of the position)) –
yyy (3d array, a regular grid (y component of the position)) –
zzz (3d array, a regular grid (z component of the position)) –
zf (float, (positive real number)) – … a zoom factor
bounds_error –
- Returns
qty_ (3d array, a regular grid (data at (x, y, z) at a higher resolution))
xxx_ (3d array, a regular grid (x component of the position at a higher resolution))
yyy_ (3d array, a regular grid (y component of the position at a higher resolution))
zzz_ (3d array, a regular grid (z component of the position at a higher resolution))
Plotting module
tflow.graph module
Module for plotting and saving figures
- class tflow.graph.Arrow3D(xs, ys, zs, *args, **kwargs)
Bases:
matplotlib.patches.FancyArrowPatch
- draw(renderer)
Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (.Artist.get_visible returns False).
- Parameters
renderer (.RendererBase subclass.) –
Notes
This method is overridden in the Artist subclasses.
- class tflow.graph.FormatScalarFormatter(fformat='%03.1f', offset=True, mathText=True)
Bases:
matplotlib.ticker.ScalarFormatter
Ad-hoc class to subclass matplotlib.ticker.ScalarFormatter in order to alter the number of visible digits on color bars
- class tflow.graph.LineDrawer(ax)
Bases:
object
- Class which allows users to draw lines/splines by clicking pts on the plot
… Default: lines/splines are closed. … make sure that matplotlib backend is interactive
- Procedure for self.draw_lines() or self.draw_splines:
It uses plt.ginput() 1. Add a point by a left click 2. Remove a point by a right click 3. Stop interaction (move onto the next line to draw)
- Example
# Pass matplotlib.axes._subplots.AxesSubplot object whose coordinates are used for extracting pts ld = LineDrawer(ax)
# Draw lines/splines ld.draw_lines(n=5) # Draw 5 lines (connecting 5 set of points) # ld.draw_splines(n=2) # Or draw 2 splines based on the clicked points
xs, ys = ld.xs, ld.ys # Retrieve x and y coords of pts used to draw lines/splines # xis, yis = ld.xis, ld.yis # Retrieve x and y coords for each spline
# plot the first contour plt.plot(xs[0], ys[0]
# for example, I could feed this contour to compute a line integral using vel.compute_circulation()
- close()
- draw_lines(n=1, close=True)
- draw_splines(n=1, npt=100, n_sp=1000, close=True)
- get_contour(npt=100, close=True)
- return_pts_on_splines()
- spline_fit(x, y, n=1000)
- class tflow.graph.PointFinder(ax, xx, yy, weight=None)
Bases:
object
- find_local_center_of_mass(kernel_radius=2)
- get_local_center_of_mass(npt=100, kernel_radius=2)
- get_pts(npt=100)
- tflow.graph.add_arrow_to_line(axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8], head_width=15, transform=None, **kwargs)
- tflow.graph.add_arrow_to_line2D(axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8], arrowstyle='-|>', head_width=15, transform=None)
Add arrows to a matplotlib.lines.Line2D at selected locations.
axes: line: Line2D object as returned by plot command arrow_locs: list of locations where to insert arrows, % of total length arrowstyle: style of the arrow arrowsize: size of the arrow transform: a matplotlib transform instance, default to data coordinates
arrows: list of arrows
- tflow.graph.add_arrow_to_line3D(axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8], head_width=15, lw=1, transform=None, **kwargs)
Add arrows to a matplotlib.lines.Line2D at selected locations.
Example
# plotting fig = plt.figure() ax = fig.add_subplot(111, projection=’3d’)
x = np.linspace(0, 10, 11) y = np.linspace(0, 10, 11) z = np.zeros(11) line, = ax.plot(x,y,z, alpha=1, lw=3, color=’k’) add_arrow_to_line3D(ax, line, arrow_locs=np.linspace(0., 1., 5), alpha=0.3)
axes: line: Line2D object as returned by plot command arrow_locs: list of locations where to insert arrows, % of total length arrowstyle: style of the arrow arrowsize: size of the arrow transform: a matplotlib transform instance, default to data coordinates
arrows: list of arrows
- tflow.graph.add_color_wheel(fig=None, fignum=1, figsize=(7.54, 7.54), rect=[0.68, 0.65, 0.2, 0.2], cmap=None, cmapname='hsv', norm=None, values=[- 3.141592653589793, 3.141592653589793], n=2056, ring=True, text='Phase', fontsize=11, ratio=1, text_loc_ratio=0.35, text_loc_angle=3.3615041393410787, **kwargs)
- tflow.graph.add_colorbar(mappable, fig=None, ax=None, fignum=None, location='right', label=None, fontsize=None, option='normal', tight_layout=True, ticklabelsize=None, aspect='equal', ntick=5, tickinc=None, size='5%', pad=0.15, caxAspect=None, fformat='%03.1f', labelpad=1, **kwargs)
Adds a color bar
- e.g.
fig = plt.figure() img = fig.add_subplot(111) ax = img.imshow(im_data) colorbar(ax)
- Parameters
mappable –
location –
- tflow.graph.add_colorbar_alone(ax, values, cmap='magma', label=None, fontsize=None, option='normal', fformat=None, tight_layout=True, ticklabelsize=None, ticklabel=None, aspect=None, location='right', color='k', size='5%', pad=0.15, **kwargs)
Add a colorbar to a figure without a mappable … It creates a dummy mappable with given values
… LOCATION OF CAX fig, ax = graph.set_fig(1, 111) w, pad, size = 0.1, 0.05, 0.05 graph.add_colorbar_alone(ax, [0, 1], pad=float2pc(pad), size=float2pc(size), tight_layout=False) graph.add_subplot_axes(ax, [1-w-(1-1/(1.+pad+size)), 0.8, w, 0.2])
- Parameters
ax (Axes instance) –
values (1D array-like- min and max values of values are found from this array) –
cmap (str, cmap instance) –
label (str, label of the color bar) –
fontsize (float, fontsize of the label) –
option (str, choose from 'normal' and 'scientific') –
'scientific' (... if) –
1x10^exponent (the color bar is shown in a scientific format like) –
fformat (str, default: None equivalent to "%03.1f") –
tight_layout (bool, if True, fig.tight_layout() is called.) –
ticklabelsize (float) –
ticklabel (1d array-like) –
aspect –
it. (... Adding a color bar may distort the aspect ratio. Fix) –
'equal' (if aspect ==) – ax.set_aspect(‘equal’)
location –
color –
kwargs –
- Returns
- Return type
cb
- tflow.graph.add_colorbar_old(mappable, fig=None, ax=None, fignum=None, label=None, fontsize=11, vmin=None, vmax=None, cmap='jet', option='normal', **kwargs)
Adds a color bar (Depricated. replaced by add_colorbar) :param mappable: :type mappable: image like QuadMesh object to which the color bar applies (NOT a plt.figure instance) :param ax: :type ax: Parent axes from which space for a new colorbar axes will be stolen :param label:
- tflow.graph.add_discrete_colorbar(ax, colors, vmin=0, vmax=None, label=None, fontsize=None, option='normal', tight_layout=True, ticklabelsize=None, ticklabel=None, aspect=None, **kwargs)
- tflow.graph.add_secondary_xaxis(ax, functions=None, loc='top', label='', log=False, **kwargs)
Adds a secondary x-axis at the top … Must pass a pair of mapping functions between a current x and a new x
- e.g.
- def deg2rad(x):
return x * np.pi / 180
- def rad2deg(x):
return x * 180 / np.pi
add_secondary_xaxis(ax, functions=(deg2rad, rad2deg))
- Parameters
ax –
functions –
- Returns
- Return type
secax
- tflow.graph.add_secondary_yaxis(ax, functions=None, loc='right', label='', log=False, **kwargs)
Adds a secondary yaxis at the top … Must pass a pair of mapping functions between a current x and a new x
- e.g.
- def deg2rad(y):
return y * np.pi / 180
- def rad2deg(y):
return y * 180 / np.pi
add_secondary_yaxis(ax, functions=(deg2rad, rad2deg))
- Parameters
ax –
functions –
- Returns
- Return type
secax
- tflow.graph.add_subplot_axes(ax, rect, axisbg='w', alpha=1, **kwargs)
Creates a sub-subplot inside the subplot (ax) rect: list, [x, y, width, height] e.g. rect = [0.2,0.2,0.7,0.7]
- Parameters
ax –
rect (list, [x, y, width, height] e.g. rect = [0.2,0.2,0.7,0.7]) –
axisbg (background color of the newly created axes object) –
- Returns
- Return type
subax, Axes class object
- tflow.graph.addtext(ax, text='text goes here', x=0, y=0, color='k', option=None, npartition=15, **kwargs)
Adds text to a plot. You can specify the position where the texts will appear by ‘option’ | tl2 tc2 tr2 | | tl tc tr | | tl3 tc3 tr3 | | | | cl2 | | cl cc cr | | cl3 | | | | bl2 br2 | | bl bc br | | bl3 br3 |
- Parameters
ax (with a text) –
subplot –
text –
x –
y –
fontsize –
color –
option (default locations) –
kwargs –
Returns –
ax –
------- –
- tflow.graph.adjust_colorbar(cb, fontsize=11, label=None, labelpad=1, tick_fontsize=11, ticks=None)
A helper to modify basic features of a matplotlib Colorbar object
- tflow.graph.apply_custom_cyclers(ax, color=['r', 'b', 'g', 'y'], linestyle=['-', '-', '-', '-'], linewidth=[3, 3, 3, 3], marker=['o', 'o', 'o', 'o'], s=[0, 0, 0, 0], **kwargs)
This is a simple example to apply a custom cyclers for particular plots. … This simply updates the rcParams so one must call this function BEFORE ceration of the plots. … e.g.
fig, ax = set_fig(1, 111) apply_custom_cyclers(ax, color=[‘r’, ‘b’, ‘g’, ‘y’]) ax.plot(x1, y1) ax.plot(x2, y2) …
- Parameters
ax (mpl.axes.Axes instance) –
color (list of strings, color) –
linewidths (list of float values, linewidth) –
linestyles (list of strings, linestyle) –
marker (list of strings, marker) –
s (list of float values, marker size) –
- Returns
- Return type
None
- tflow.graph.approximate_fraction(x, e)
Return the fraction with the lowest denominator that differs from x by no more than e.
- tflow.graph.arrow(x, y, dx, dy, ax=None, fig=None, fignum=1, subplot=111, figsize=None, **kwargs)
Adds an arrow on a canvas … Specify an arrow by its starting point (x, y) and its direction (dx, dy)
- Parameters
x –
y –
dx –
dy –
ax –
fig –
fignum –
subplot –
figsize –
kwargs –
- tflow.graph.arrow3D(x, y, z, dx, dy, dz, lw=3, arrowstyle='-|>', color='r', mutation_scale=20, ax=None, fig=None, fignum=1, subplot=111, figsize=None, xlabel='x (mm)', ylabel='y (mm)', zlabel='z (mm)', **kwargs)
- tflow.graph.axhband(ax, y0, y1, x0=None, x1=None, color='C1', alpha=0.2, **kwargs)
Make a horizontal band between y0 and y1 (highlighting effect) :param ax: :type ax: plt.axes.axes object :param x0: :type x0: x-coordinate of the left of a band (x0 < x1). As a default, x0, x1 = ax.get_xlim() :param x1: :type x1: x-coordinate of the right of a band (x0 < x1) :param y0: :type y0: y-coordinate of the bottom of a band (y0 < y1) :param y1: :type y1: y-coordinate of the top of a band (y0 < y1) :param color: :type color: color of a band :param alpha: :type alpha: alpha of a band :param kwargs: :type kwargs: kwargs for ax.fill_between()
- tflow.graph.axhline(ax, y, x0=None, x1=None, color='black', linestyle='--', linewidth=1, zorder=0, **kwargs)
Draw a horizontal line at y=y from xmin to xmax :param y: :param x:
- tflow.graph.axvband(ax, x0, x1, y0=None, y1=None, color='C1', alpha=0.2, **kwargs)
Make a vertical band between x0 and x1 (highlighting effect) :param ax: :type ax: plt.axes.axes object :param x0: :type x0: x-coordinate of the left of a band (x0 < x1) :param x1: :type x1: x-coordinate of the right of a band (x0 < x1) :param y0: :type y0: y-coordinate of the bottom of a band (y0 < y1) :param y1: :type y1: y-coordinate of the top of a band (y0 < y1). As a default, y0, y1 = ax.get_ylim() :param color: :type color: color of a band :param alpha: :type alpha: alpha of a band :param kwargs: :type kwargs: kwargs for ax.fill_between()
- tflow.graph.axvline(ax, x, y0=None, y1=None, color='black', linestyle='--', linewidth=1, zorder=0, **kwargs)
Draw a vertical line at x=x from ymin to ymax :param x: :param y:
- tflow.graph.bin_and_errorbar(x_, y_, xerr=None, n_bins=100, mode='linear', bin_center=True, return_std=False, fignum=1, ax=None, marker='o', fillstyle='full', linestyle='None', linewidth=1, label=None, mfc='white', subplot=None, legend=False, figsize=None, maskon=False, thd=1, capsize=5, set_bottom_zero=False, symmetric=False, set_left_zero=False, return_stats=False, **kwargs)
Takes scattered data points (x, y), bin them (compute avg and std), then plots the results with error bars
- Parameters
x (array-like) –
y (array-like) –
xerr (must be a scalar or numpy array with shape (N,1) or (2, N)... [xerr_left, xerr_right]) – … if xerr==0, it removes the error bars in x.
yerr (must be a scalar or numpy array with shape (N,) or (2, N)... [yerr_left, yerr_right]) –
n_bins (int, number of bins used to compute a histogram between xmin and xmax) –
mode (str, default: 'linear', options are 'linear' and 'log'. Select either linear binning or logarithmic binning) –
… If “linear”, it computes statistics using evenly separated bins between xmin and xmax. … If “log”, it uses bins evenly separted in the log space. (It assumes that xmin>0)
i.e. The bin edges are like (10^-1.0, 10^-0.5), (10^-0.5, 10^0), (10^0, 10^0.5), and so on.
bin_center (bool, default: True.) – … passed to get_binned_stats()
return_std (bool, default: False.) – … passed to get_binned_stats() … If False, it uses standard errors as error bars, instead of using standard deviations
fignum (int, figure number) –
ax (Axes object, default: None) – … If given, this becomes the Axes on which the results are plotted
marker (str, default: 'o', marker style) –
fillstyle (str, default: 'full'. Options: 'full', 'none'. See matplotlib scatter for more details) –
linestyle (str, default:'None') –
linewidth (float, linewidth of the error bars) –
label (str, label for a legend) –
mfc (str, default:'white', marker face color) – … Use this with fillstyle=’none’ in order to change the face color of the marker. … Common usage: empty circles- fillstyle=’none’, mfc=’white’
subplot (int, three-digit number. e.g.-111) –
legend (bool, default: False. If True, ax.legend is called at the end.) –
figsize (tuple, figure size in inches) –
maskon (bool, default: False) – … This hides “suspicious” data points / outliers. … See the docstr of get_mask4erroneous_pts() for more details
thd (float, threshold value used for get_mask4erroneous_pts() to determine the outliers) –
capsize (float, width of the error bars) –
return_stats (bool, default: False) – … If True, it returns the binned results (that are being plotted): x[mask], y[mask], xerr[mask], yerr[mask]
kwargs (passed to ax.errorbar()) –
- Returns
If not return_stats (default), – fig, ax: a Figure instance, an Axes instance
If return_stats – fig, ax, x[mask], y[mask], xerr[mask], yerr[mask]: a Figure instance, an Axes instance, binned results (x, y, x_err, y_err)
- tflow.graph.cdf(data, nbins=100, return_data=False, vmax=None, vmin=None, fignum=1, figsize=None, subplot=None, **kwargs)
Plots a cummulative distribution function of ND data … a wrapper for np.histogram and matplotlib … Returns fig, ax, (optional: bins, hist)
- Parameters
data (nd-array, list, or tuple, data used to get a histogram/pdf) –
nbins (int, umber of bins) –
return_data (bool, If True, it returns fig, ax, bins (centers of the bins), hist (counts or probability density values)) –
vmax (float, data[data>vmax] will be ignored during counting.) –
vmin (float, data[data<vmin] will be ignored during counting.) –
fignum (int, figure number (the argument called "num" in matplotlib)) –
figsize (tuple, figure size in inch (width x height)) –
subplot (int, matplotlib subplot notation. default: 111) –
density (bool, If True, it plots the probability density instead of counts.) –
analyze (bool If True, it adds mean, mode, variane to the plot.) –
kwargs (other kwargs passed to plot() of the velocity module) –
- Returns
fig (matplotlib.Figure instance)
ax (matplotlib.axes.Axes instance)
(Optional)
bins (1d array, bin centers)
hist (1d array, probability density vales or counts)
- tflow.graph.choose_colors(**kwargs)
Equivalent of sns.choose_cubehelix_palette()
- Example: COLOR CURVES BASED ON A QUANTITY ‘Z’
# What is Z? z = [0, 0.25, 0.5, 0.75, 1] # Choose colors colors = graph.choose_colors() # Set the colors as a default color cycle set_default_color_cycle(n=len(z), colors=colors) # Plot your data… plot(x1, y1) # color1 plot(x2, y2) # color2 … # Add a colorbar (On the same figure) add_colorbar_alone(plt.gca(), z, colors=colors) # plot a stand-alone colorbar in the figure # Add a colorbar (On the different figure) plot_colorbar(z, colors=colors, fignum=2) # plot a stand-alone colorbar on a new figure
- Parameters
kwargs –
- Returns
- Return type
colors
- tflow.graph.clf(fignum=None)
- tflow.graph.close(*argv, **kwargs)
- tflow.graph.cname2hex(cname)
Converts a color registered on matplotlib to a HEX code :param cname:
- tflow.graph.color_axis(ax, locs=['bottom', 'left', 'right'], colors=['k', 'C0', 'C1'], xlabel_color=None, ylabel_color=None, xtick_color=None, ytick_color=None)
Colors the axes (axis, ticks, and a label)
- Parameters
ax (axes.Axes instance) –
locs (list of strings, locations of the axes. choose from 'bottom', 'left', 'right', 'top') –
colors (list of strings, colors of the axes. e.g. ['k', 'C0', 'C1']) –
xlabel_color (str, color of xlabel. If None, the same colors as "colors" are used.) –
ylabel_color (str, color of ylabel. If None, the same colors as "colors" are used.) –
xtick_color (str, color of xtick. If None, the same colors as "colors" are used.) –
ytick_color (str, color of ytick. If None, the same colors as "colors" are used.) –
- tflow.graph.color_plot(x, y, z, subplot=None, fignum=1, figsize=None, ax=None, vmin=None, vmax=None, log10=False, label=None, cbar=True, cmap='magma', symmetric=False, enforceSymmetric=True, aspect='equal', option='scientific', ntick=5, tickinc=None, crop=None, fontsize=None, ticklabelsize=None, cb_kwargs={}, return_cb=False, **kwargs)
- Parameters
x (2d array) –
y (2d array) –
z (2d array) –
subplot (int, default is 111) –
fignum –
figsize –
ax –
vmin –
vmax –
log10 –
label –
cbar –
cmap –
symmetric –
aspect (str, 'equal' or 'auto) –
option –
ntick –
tickinc –
crop –
kwargs –
cb_kwargs (dict, kwargs for add_colorbar()) – … e.g. {“fformat”: %.0f}
return_cb (bool, default: False) – … if True, this function returns fig, ax, cc, cb (colorbar instance)
- Returns
fig
ax
cc (QuadMesh instance)
cb (colorbar instance (optional))
- tflow.graph.colorbar(fignum=None, label=None, fontsize=11)
Use is DEPRICATED. This method is replaced by add_colorbar(mappable) I keep this method for old codes which might have used this method :param fignum: :param label:
- tflow.graph.contour(x, y, psi, levels=10, vmin=None, vmax=None, subplot=None, fignum=1, figsize=None, ax=None, clabel=True, fontsize=9, inline=True, fmt='%1.3f', label_kwargs={}, **kwargs)
Plot contours.
- Parameters
x (2d array) –
y (2d array) –
psi (2d array) –
levels (int or 1d array-like) – … If int (n), it plots n contours. … If array-like, it plots contours at the corresponding levels.
vmin (int) – … plots contours at the levels in (vmin, vmax)
vmax (int) – … plots contours at the levels in (vmin, vmax)
subplot (int) –
fignum (int) –
figsize (tuple) –
ax (matplotlib.ax.Axes instance) –
fontsize – … passed to ax.clabel()
inline (bool, default: True) – … passed to ax.clabel()
fmt (str, default: "%.1.3f") – … passed to ax.clabel()
label_kwargs – … passed to ax.clabel()
kwargs (dict) – … passed to ax.contour()
- Returns
fig, ax, ctrs
… ctrs (a QuadContourSet instance)
- tflow.graph.countcolorcycle(color_cycle=<itertools.cycle object>)
- tflow.graph.create_cmap_from_colors(colors_list, name='newmap')
- tflow.graph.create_cmap_using_values(colors=None, color1='greenyellow', color2='darkgreen', color3=None, n=100)
Create a colormap instance from a list … same as mpl.colors.LinearSegmentedColormap.from_list() :param colors: :param color1: :param color2: :param n:
- tflow.graph.create_colorbar(values, cmap='viridis', figsize=None, orientation='vertical', label='qty (mm)', fontsize=11, labelpad=0, ticks=None, **kwargs)
Creates a horizontal/vertical colorbar for reference using pylab.colorbar()
- Parameters
values (1d array-like, used to specify the min and max of the colorbar) –
cmap (cmap instance or str, default: 'viridis') –
figsize (tuple, figure size in inches, default: None) –
orientation (str, 'horizontal' or 'vertical') –
label (str, label of the color bar) –
fontsize (fontsize for the label and the ticklabel) –
labelpad (float, padding for the label) –
ticks (1d array, tick locations) –
- tflow.graph.create_weight_shifted_cmap(cmapname, ratio=0.75, vmin=None, vmax=None, vcenter=None, n=500)
Creates a cmap instance of a weight-shifted colormap
- Parameters
cmapname (str) –
ratio –
vmin –
vmax –
vcenter –
n –
- tflow.graph.default_figure_params()
- tflow.graph.draw_box(ax, xx, yy, w_box=351.0, h_box=351.0, xoffset=0, yoffset=0, linewidth=5, scalebar=True, sb_length=50.0, sb_units='$mm$', sb_loc=(0.95, 0.1), sb_txtloc=(0.0, 0.4), sb_lw=10, sb_txtcolor='white', fontsize=None, facecolor='k', fluidcolor=None, bounding_box=True, bb_lw=1, bb_color='w')
Draws a box and fills the surrounding area with color (default: skyblue) Adds a scalebar by default … drawn box center coincides with the center of given grids(xx, yy) … in order to shift the center of the box, use xoffset any yoffset :param ax: :type ax: matplotlib.axes.Axes instance :param xx: x coordinates :type xx: 2d numpy array :param yy: y coordinates :type yy: 2d numpy array :param w_box: width of the box- used to be set as 325 :type w_box: float/int :param h_box: height of the box- used to be set as 325 :type h_box: float/int :param xoffset: real number to shift the box center in the x direction :type xoffset: float/int :param yoffset: real number to shift the box center in the x direction :param linewidth: linewidth of drawn box :type linewidth: int :param scalebar: … draws a scalebar inside the drawn box :type scalebar: bool (default: True) :param sb_length: … length of the scale bar in physical units.
…… In principle, this can be float. If you want that, edit the code where ax.text() is called. …… Generalizing to accept the float requires a format which could vary everytime, so just accept integer.
- Parameters
sb_units (str) – … units of the sb_length. Default: ‘$mm$’
sb_loc (tuple, (x, y)) – … location of the scale bar. Range: [0, 1] … the units are with respect the width and height of the box
sb_txtloc (tuple, (x, y)) – … location of the TEXT of the scale bar. Range: [0, 1] … x=0: LEFT of the scale bar, x=1: RIGHT of the scale bar … y=0: LEFT of the scale bar, x=1: RIGHT of the scale bar
sb_lw (float) – … line width of the scale bar
facecolor –
fluidcolor –
- tflow.graph.draw_circle(ax, x, y, r, linewidth=1, edgecolor='r', facecolor='none', fill=False, **kwargs)
Draws a circle on the axes (ax)
- Parameters
ax (matplotlib axes object) –
x (float) –
y (float) –
r (float) –
linewidth (float) –
edgecolor –
facecolor –
fill –
kwargs –
- tflow.graph.draw_cuboid(ax, xx, yy, zz, color='c', lw=2, **kwargs)
Draws a cuboid (projection=’3d’)
- tflow.graph.draw_power_triangle(ax, x, y, exponent, w=None, h=None, facecolor='none', edgecolor='r', alpha=1.0, flip=False, fontsize=11, set_base_label_one=False, beta=20, zorder=100, x_base=None, y_base=None, x_height=None, y_height=None, **kwargs)
Draws a triangle which indicates a power law in the log-log plot.
- Parameters
ax (matplotlib.axes._subplots.AxesSubplot object) – … get it like plt.gca()
x (float / int) – … x coordinate of the triangle drawn on the plot
y (float / int) – … x coordinate of the triangle drawn on the plot
exponent (float / int) – … exponent of the power law … Y = X^exponent
w (float / int) – … number of decades for the drawn triangle to span on the plot … By default, this function draws a triangle with size of 0.4 times the width of the plot
h (float / int) – … number of decades for the drawn triangle to span on the plot
facecolor (str) – … face color of the drawn triangle, default: ‘none’ (transparent) … passed to mpatches.PathPatch object
edgecolor (str) – … edge color of the drawn triangle, default: ‘r’ … passed to mpatches.PathPatch object
alpha (float [0, 1]) – … alpha value of the drawn triangle
flip (bool) – … If True, it will flip the triangle horizontally.
fontsize (float / int) – … fontsize of the texts to indicate the exponent aside the triangle
set_base_label_one (bool, default: False) – … If True, it will always annotate the base as ‘1’ and alter the text for the height accordingly. … By default, it will annotate the base and the height using the closest integer pair.
beta (float / int, default: 20) – … This is used to control the spacing between the text and the drawn triangle … The higher beta is, the less spacing between the text and the triangle
zorder (zorder of triangle, default: 0) –
kwargs (the other kwargs will be passed to ax.text()) –
- tflow.graph.draw_rectangle(ax, x, y, width, height, angle=0.0, linewidth=1, edgecolor='r', facecolor='none', **kwargs)
Draws a rectangle in a figure (ax) :param ax: :param x: :param y: :param width: :param height: :param angle: :param linewidth: :param edgecolor: :param facecolor: :param kwargs:
- tflow.graph.draw_sphere(ax, xc, yc, zc, r, color='r', **kwargs)
- tflow.graph.draw_sphere_wireframe(ax, xc, yc, zc, r, color='r', lw=1, **kwargs)
Draws a sphere using a wireframe :param ax: :param xc: :param yc: :param zc: :param r: :param color: :param lw: :param kwargs:
- tflow.graph.dummy_scalarMappable(values, cmap)
Returns a dummy scalarMappable that can be used to make a stand-alone color bar e.g.
sm = dummy_scalarMappable([0, 100], ‘viridis’) fig = plt.figure(1) fig.colorbar(sm, pad=0.1)
- Parameters
values (list, array, this is used to specify the range of the color bar) –
cmap (str, cmap object) –
- Returns
- Return type
sm
- tflow.graph.embed_2dplot_in_3d(pp, qq, qty, zdir='z', offset=0, cmap='viridis', vmin=None, vmax=None, fignum=1, subplot=111, ax=None, figsize=None, zorder=0, alpha=1.0, edgecolors='none', lw=0)
This embeds a 2d plot/image in 3D plot. The 2d plot points in +z(+y, or +x) direction. … This function should be used for a visualization purposes since it is not scientifically informative! … Use ax.plot_surface to insert a 2d plot on an arbitrary surface embedded in 3D. … This function can be usd to show three 2D projections of a 3D data.
- Parameters
pp (2d array, x coordinate of the 2d plot) –
qq (2d array, y coordinate of the 2d plot) –
qty (2d array, data of the 2d plot) –
zdir (str, direction of the normal vector. choices are 'z', 'x', 'y') –
offset (float,) –
cmap (str, cmap instance,) –
vmin (float, colormap spans from vmin to vmap) –
vmax (float, colormap spans from vmin to vmap) –
fignum (int, number of the figure) –
subplot (int, subplot of the figure (three digit notation, default: 111)) –
figsize (tuple, figure size in inches) –
zorder (int, zorder of the produced surface) –
alpha (float, alpha of the embedded plot) –
edgecolors (str, edge color that is passed to ax.plot_surface()- default: 'none') –
lw (float, linewidth that is passed to ax.plot_surface()- default: 0) –
- Returns
- Return type
fig, ax, surf
- tflow.graph.errorbar(x, y, xerr=0.0, yerr=0.0, fignum=1, marker='o', fillstyle='full', linestyle='None', label=None, mfc='white', subplot=None, legend=False, legend_remove_bars=False, figsize=None, maskon=False, thd=1, capsize=10, xmax=None, xmin=None, ax=None, **kwargs)
errorbar plot
- Parameters
x (array-like) –
y (array-like) –
xerr (must be a scalar or numpy array with shape (N,1) or (2, N)... [xerr_left, xerr_right]) –
yerr (must be a scalar or numpy array with shape (N,) or (2, N)... [yerr_left, yerr_right]) –
fignum –
label –
color –
subplot –
legend –
kwargs –
- Returns
fig
ax
- tflow.graph.errorfill(x, y, yerr, fignum=1, color=None, subplot=None, alpha_fill=0.3, ax=None, label=None, legend=False, figsize=None, maskon=False, thd=1, xmin=None, xmax=None, smooth=False, smoothlog=False, window_len=5, window='hanning', set_bottom_zero=False, set_left_zero=False, symmetric=False, return_xy=False, **kwargs)
- tflow.graph.float2pc(x)
Converts a float into a percentage expression :param x:
- Returns
- Return type
a string in float (e.g. 0.0052)
- tflow.graph.force2showLogMajorTicks(ax, subs=[1.0], numticks=9, axis='both')
Force to show the minor ticks in the logarithmic axes … the minor ticks could be suppressed due to the limited space :param ax: :type ax: Axes instance :param subs: :type subs: str, list, or np.array, ‘all’ is equivalent to np.arange(1, 10) :param … to: :param numticks: :type numticks: int, make this integer high to show the minor ticks
- tflow.graph.force2showLogMinorTicks(ax, subs='all', numticks=9, axis='both')
Force to show the minor ticks in the logarithmic axes … the minor ticks could be suppressed due to the limited space :param ax: :type ax: Axes instance :param subs: :type subs: str, list, or np.array, ‘all’ is equivalent to np.arange(1, 10) :param numticks: :type numticks: int, make this integer high to show the minor ticks
- tflow.graph.get_binned_stats(arg, var, n_bins=100, mode='linear', bin_center=True, return_std=False)
Make a histogram out of a pair of 1d arrays. … Returns arg_bins, var_mean, var_err … The given arrays could contain nans and infs. They will be ignored.
- Parameters
arg (1d array, controlling variable) –
var (1d array, data array to be binned) –
n_bins (int, default: 100) –
mode (str, deafult: 'linear') – If ‘linear’, var will be sorted to equally spaced bins. i.e. bin centers increase linearly. If ‘log’, the bins will be not equally spaced. Instead, they will be equally spaced in log. … bin centers will be like… 10**0, 10**0.5, 10**1.0, 10**1.5, …, 10**9
return_std (bool) – If True, it returns the STD of the statistics instead of the error = STD / np.sqrt(N-1)
- Returns
arg_bins (1d array, bin centers)
var_mean (1d array, mean values of data in each bin)
var_err (1d array, std of data in each bin)
- tflow.graph.get_color_from_cmap(cmap='viridis', n=10, lut=None, reverse=False)
A simple function which returns a list of RGBA values from a cmap (evenly spaced) … If one desires to assign a color based on values, use get_colors_and_cmap_using_values() … If one prefers to get colors between two colors of choice, use get_color_list_gradient() :param cmapname: :type cmapname: str, standard cmap name :param n: :type n: int, number of colors :param lut: … If lut is not None it must be an integer giving the number of entries desired in the lookup table,
and name must be a standard mpl colormap name.
- Parameters
int – … If lut is not None it must be an integer giving the number of entries desired in the lookup table, and name must be a standard mpl colormap name.
- :param… If lut is not None it must be an integer giving the number of entries desired in the lookup table,
and name must be a standard mpl colormap name.
- Returns
- Return type
colors
- tflow.graph.get_color_list_gradient(color1='greenyellow', color2='darkgreen', color3=None, n=100, return_cmap=False)
Returns a list of colors in RGB between color1 and color2 Input (color1 and color2) can be RGB or color names set by matplotlib … color1-color2-color3
- Parameters
color1 –
color2 –
n (length of the returning list) –
- Returns
- Return type
color_list
- tflow.graph.get_colors_and_cmap_using_values(values, cmap=None, color1='greenyellow', color2='darkgreen', color3=None, vmin=None, vmax=None, n=100)
Returns colors (list), cmap instance, mpl.colors.Normalize instance assigned by the …
- Parameters
values (1d array-like,) –
cmap (str or matplotlib.colors.Colormap instance) –
color1 –
color2 –
vmin –
vmax –
n –
- Returns
- Return type
colors, cmap, norm
- tflow.graph.get_contours(ctrs, close_ctr=True, thd=0.5, min_length=0, levels=None)
Returns positions of contours drawn by ax.contour() … each contour has a different length.
- Parameters
ctrs (QuadContourSet instance (output of ax.contour)) –
close_ctr (bool) – … If True, returned points on the contours would be closed.
thd (float) –
… Relevant parameter if close_ctr is True … Let the beginning and the end of a contour be R1 and R2.
If |R1 - R2| < thd, it considers the contour closed.
- Returns
verts – … verts[n] stores (x, y) of the n-th contour … xn, yn = verts[n][:, 0], verts[n][:, 1]
- Return type
list
- tflow.graph.get_current_backend()
- tflow.graph.get_data_from_fig_plot(fig, axis_number=0)
Returns a list of data included in the figure … this function extracts data points for fig.ax.lines … Any other data must be returned
- Parameters
fig –
axis_number –
- tflow.graph.get_data_from_fig_scatter(ax)
Retrieves x, y from a scatter plot
- tflow.graph.get_default_color_cycle()
- tflow.graph.get_first_n_colors_from_color_cycle(n)
- tflow.graph.get_first_n_default_colors(n)
- tflow.graph.get_markers()
Returns a list of available markers for ax.scatter()
- tflow.graph.get_mask4erroneous_pts(x, y, thd=1)
Retruns a mask that can be sued to hide erroneous data points for 1D plots … e.g. x[mask] and y[mask] hide the jumps which appear to be false to human eyes … Uses P = dy/dx / y to determine whether data points appear to be false
If P is high, we’d expect a jump. thd is a threshold of P.
- Parameters
x (1d array) –
y (1d array) –
thd (float, threshold on P (fractional dy/dx)) –
- Returns
mask
- Return type
1d bool array
- tflow.graph.get_plot_data_from_fig(*args, **kwargs)
Depricated. Use get_data_from_fig_plot
- tflow.graph.get_scatter_data_from_fig(fig, axis_number=0)
Return x, y data of scattered data in a figure instance … It requires a different code to extract scattered data from a Figure instance, compared to plt.plot() output (type: line?) … Scattered data are stored as an collections.collection object.
- Parameters
fig (matplotlib.Figure object) –
axis_number (int, number to specify which axis user refers to. ax = fig.axes[axis_number]) –
- Returns
data_list
- Return type
list, each element of a list is a 2d array which store x,y coordinates of the scattered data points
- tflow.graph.get_sfmt()
- tflow.graph.hex2rgb(hex)
Converts a HEX code to RGB in a numpy array :param hex: :type hex: str, hex code. e.g. #B4FBB8
- Returns
rgb
- Return type
numpy array. RGB
- tflow.graph.imgScatter(x, y, imgs, img_x=None, img_y=None, subax_size=0.06, cmap='viridis', vmin=None, vmax=None, cbar=True, cb_pad='2%', cb_size='5%', cb_option='scientific', cb_label=None, axLim=(None, None, None, None), fignum=1, figsize=(7.54, 7.54), **kwargs)
Scatter plots images (2d arrays) … This function creates additional Axes on top of the master Axes instance.
To do1: one should be able to plot on the master Axes; however, this fails even with altering the zorder values. To do2: Should one be able to pass a list of imag_x as well?- this would enable plotting imgs with different resolutions :param x: :type x: 1d array-like, x-coordinates of the image locations :param y: :type y: 1d array-like, y-coordinates of the image locations :param imgs: :type imgs: list, list of images (2d arrays :param img_x: … Otherwise, it calls imshow(imgs[i]). :type img_x: 2d array (optional), x grid of the images- if given, this calls color_plot(img_x, img_y, imgs[i]). :param img_y: … Otherwise, it calls imshow(imgs[i]). :type img_y: 2d array (optional), y grid of the images- if given, this calls color_plot(img_x, img_y, imgs[i]). :param subax_size: :type subax_size: float (0, 1], default:0.06, the size of the subaxes (inner plots) :param cmap: :type cmap: str/cmap object- a color map of the images :param vmin: :type vmin: float, default:None- color bar range [vmin, vmax] :param vmax: :type vmax: float, default:None- color bar range [vmin, vmax] :param cbar: :type cbar: boolean, default:False- To toggle a color bar, vmin and vmax must be given. This is because each image could be drawn with a different color bar range. :param cb_pad: :type cb_pad: str, default:”2%” (with respect to the figure width)- Do not pass a float. :param cb_size: :type cb_size: str, default:”2%” (with respect to the figure width)- Do not pass a float. :param cb_option: :type cb_option: str, color bar notation, choose from ‘normal’ and ‘scientific’ :param cb_label: :type cb_label: str, label of the color bar :param axLim: :type axLim: 1d array-like (xmin, xmax, ymin, ymax)- x- and y-limits of the master axes :param kwargs: :type kwargs: dict, this gets passed to either imshow() or color_plot()
- Returns
fig, ax, axes, cb
- Return type
Figure, Axes (master), list of Axes, a color bar object
- tflow.graph.imshow(arr, xmin=0, xmax=1, ymin=0, ymax=1, cbar=True, vmin=0, vmax=0, fignum=1, subplot=111, figsize=(7.54, 7.54), ax=None, interpolation='nearest', cmap='bwr', cb_kwargs={}, **kwargs)
- Parameters
arr (array-like or PIL image) –
xmin (float [0., 1.)- extent=(xmin, xmax, ymin, ymax) The bounding box in data coordinates that the image will fill.) –
xmax (float (0., 1.]- extent=(xmin, xmax, ymin, ymax) The bounding box in data coordinates that the image will fill.) –
ymin (float [0., 1.)- extent=(xmin, xmax, ymin, ymax) The bounding box in data coordinates that the image will fill.) –
ymax (float (0., 1.]- extent=(xmin, xmax, ymin, ymax) The bounding box in data coordinates that the image will fill.) –
cbar (bool, If True, fig.colorbar(ImageAxes instance, **cb_kwargs) is called.) –
vmin (float, image intensity ranges from vmin to vmax) –
vmax (float, image intensity ranges from vmin to vmax) –
fignum (int, figure number) –
subplot (int, three-digit integer to specify a subplot) –
figsize (tuple, figure size- e.g. (8,8)) –
interpolation ('none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36',) – ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’, ‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’, ‘sinc’, ‘lanczos’.
cmap (str, color map used for plt.imshow) –
cb_kwargs (dict, color bar keyward arguments can be passed in this dictionary like {'shrink': 0.5, 'pad':0.05}) – https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html
- Returns
fig, ax, ima, cc
- Return type
Figure, Axes, AxesImage, Colorbar instances
- tflow.graph.labelaxes(ax, xlabel, ylabel, **kwargs)
- tflow.graph.labelaxes_multicolor(ax, list_of_strings, list_of_colors, axis='x', anchorpad=0, **kwargs)
this function creates axes labels with multiple colors ax specifies the axes object where the labels should be drawn list_of_strings is a list of all of the text items list_if_colors is a corresponding list of colors for the strings axis=’x’, ‘y’, or ‘both’ and specifies which label(s) should be drawn
- tflow.graph.legend(ax, remove=False, **kwargs)
loc: best 0, upper right 1, upper left 2, lower left 3, lower right 4, right 5, center left 6, center right 7, lower center 8, upper center 9, center 10 :param ax: :param kwargs:
- tflow.graph.list_available_backends()
- tflow.graph.make_ax_symmetric(ax, axis='y')
Makes the plot symmetric about x- or y-axis
- tflow.graph.make_ticks_scientific(ax, axis='both', **kwargs)
Make tick labels display in a scientific format
- Some other useful lines about tick formats
ax.set_xticks(np.arange(0, 1.1e-3, 0.5e-3)) ax.set_yticks(np.arange(0, 1.1e-3, 0.25e-3)) ax.tick_params(axis=’x’, labelsize=20) ax.tick_params(axis=’y’, labelsize=20) ax.xaxis.offsetText.set_fontsize(20) ax.yaxis.offsetText.set_fontsize(20)
- Parameters
ax (axes.Axes instance) –
- tflow.graph.pc2float(s)
Converts a percentage expression (str) to float e.g. pc2float(5.2%) returns 0.0052 :param s: :type s: str, e.g. “5.2%”
- Returns
- Return type
a floating number (e.g. 0.0052)
- tflow.graph.pdf(data, nbins=100, return_data=False, vmax=None, vmin=None, fignum=1, figsize=None, subplot=None, density=True, analyze=False, **kwargs)
Plots a probability distribution function of ND data … a wrapper for np.histogram and matplotlib … Returns fig, ax, (optional: bins, hist)
- Parameters
data (nd-array, list, or tuple, data used to get a histogram/pdf) –
nbins (int, number of bins) –
return_data (bool, If True, it returns fig, ax, bins (centers of the bins), hist (counts or probability density values)) –
vmax (float, data[data>vmax] will be ignored during counting.) –
vmin (float, data[data<vmin] will be ignored during counting.) –
fignum (int, figure number (the argument called "num" in matplotlib)) –
figsize (tuple, figure size in inch (width x height)) –
subplot (int, matplotlib subplot notation. default: 111) –
density (bool, If True, it plots the probability density instead of counts.) –
analyze (bool If True, it adds mean, mode, variane to the plot.) –
kwargs (other kwargs passed to plot() of the velocity module) –
- Returns
fig (matplotlib.Figure instance)
ax (matplotlib.axes.Axes instance)
(Optional)
bins (1d array, bin centers)
hist (1d array, probability density vales or counts)
- tflow.graph.pie(sizes, labels=None, explode=None, autopct='%1.1f%%', startangle=90, shadow=False, sort=True, fignum=1, figsize=None, subplot=None, fig=None, ax=None, **kwargs)
A wrapper for plt.pie … a main difference from the original plt.plot is the sorting feature. It automatically sorts the portions from the largest to smallest. … If one
- tflow.graph.plot(x, y=None, fmt='-', fignum=1, figsize=None, label='', color=None, subplot=None, legend=False, fig=None, ax=None, maskon=False, thd=1, xmin=None, xmax=None, set_bottom_zero=False, symmetric=False, set_left_zero=False, smooth=False, smoothlog=False, window_len=5, window='hanning', custom_cycler=None, custom_cycler_dict={'color': ['r', 'b', 'g', 'y'], 'linestyle': ['-', '-', '-', '-'], 'linewidth': [3, 3, 3, 3], 'marker': ['o', 'o', 'o', 'o'], 's': [0, 0, 0, 0]}, return_xy=False, **kwargs)
plot a graph using given x,y fignum can be specified any kwargs from plot can be passed
- tflow.graph.plot3d(x, y, z, fignum=1, figsize=None, label='', color=None, subplot=None, fig=None, ax=None, labelaxes=True, aspect='auto', **kwargs)
plot a 3D graph using given x, y, z
- tflow.graph.plot_colorbar(values, cmap='viridis', colors=None, ncolors=100, fignum=1, figsize=None, orientation='vertical', label=None, labelpad=5, fontsize=11, option='normal', fformat=None, ticks=None, tick_params=None, **kwargs)
Plots a stand-alone colorbar
- Parameters
values (1d array-like, these values are used to create a colormap) –
cmap (str, cmap object) –
colors (list of colors, if given, it overwrites 'cmap'.) – … For custom colors/colormaps, the functions below could be handy. …… colors = graph.choose_colors() # sns.choose_cubehelix_palette() …… colors = graph.get_color_list_gradient(color1=’red’, color2=’blue’) # linearly segmented colors
ncolors –
fignum –
figsize –
orientation –
label –
labelpad –
fontsize –
option (str, if 'scientific', it uses a scientific format for the ticks) –
fformat –
ticks –
tick_params –
kwargs –
- Returns
fig, cax, cb
- Return type
Figure instance, axes.Axes instance, Colorbar instance
- tflow.graph.plot_date(dates, y, fignum=1, figsize=None, label='', color=None, subplot=None, legend=False, fig=None, ax=None, set_bottom_zero=False, **kwargs)
A function to plot values against dates with format “2020-01-01”
- Parameters
dates (1d array-like of dates- each entry must be in the format "YYYY-MM-DD") –
y (1d array-like) –
fignum (int, fignure number) –
figsize (tuple, figure size e.g.- (8, 8)) –
label (label kwarg in plt.plot_date) –
color (str, color kwarg in plt.plot_date) –
subplot (int, 3-digit notation to specify a subplot) –
legend (bool) –
fig (mpl.figure.Figure instance- if given, it will just return this instance at the end) –
ax (mpl.axes.Axes instance- if given, it plots the given inputs on this subplot.) –
set_bottom_zero (bool, if True, it sets the ymin=0) –
kwargs (the keyword arguments will be passed to plt.plot_date()) –
- Returns
fig, ax
- Return type
matplotlib.figure.Figure instance, matplotlib.axes.Axes instance
- tflow.graph.plot_fit_curve(xdata, ydata, func=None, fignum=1, subplot=111, ax=None, figsize=None, linestyle='--', xmin=None, xmax=None, add_equation=True, eq_loc='bl', color=None, label='fit', show_r2=False, return_r2=False, p0=None, bounds=(- inf, inf), maskon=True, thd=1, **kwargs)
Plots a fit curve given xdata and ydata :param xdata: :type xdata: 1d array :param ydata: :type ydata: 1d array :param func: :type func: a function to be fit- e.g. lambda x, a, b: a*x+b :param fignum: :type fignum: int, figure number :param subplot: :type subplot: int, three-digit number to specify a subplot location :param ax: :type ax: Axes instance- If given, it plots on the :param figsize: :param linestyle: :param xmin: :param xmax: :param add_equation: :param eq_loc: :param color: :param label: :param show_r2: :param return_r2: :param p0: :param bounds: :param maskon: :param thd: :param kwargs:
- Returns
fig, ax (A Figure object, an Axes object)
popt, pcov (fit results, a covariance matrix)
- tflow.graph.plot_interpolated_curves(x, y, zoom=2, fignum=1, figsize=None, label='', color=None, subplot=None, legend=False, fig=None, ax=None, maskon=False, thd=1, return_interp_func=False, **kwargs)
plot a graph using given x, y fignum can be specified any kwargs from plot can be passed
- tflow.graph.plot_isosurface(qty, isovalue, xxx, yyy, zzz, cmap='Spectral', r=None, xc=0, yc=0, zc=0, fill_value=0, fignum=1, subplot=None, lw=1, figsize=(8, 8), labelaxes=True, **kwargs)
Plots a isosurface given a 3D data, value at which isosurface is defined, 3D grids in Cartesian coordinates) … the isosurface is extracted by the marching cube algorithm
- Parameters
qty (3D array, a scalar field) –
isovalue (float, the value at which the isosurface is extracted) –
xxx (3D array, x component of the positional grid) –
yyy (3D array, y component of the positional grid) –
zzz (3D array, z component of the positional grid) –
cmap (str, name of the color map used to plot the isosurface) –
r (float,) –
provided (... If) –
zz**2) (it sets qty[R > r] = fill_value where R = np.sqrt(xx**2 + yy**2 +) –
boundaries (... This is used for a simple fitering the problematic outliers near the) –
xc (float/int, x-coordinate of the origin in case r is not None) –
yc (float/int, y-coordinate of the origin in case r is not None) –
zc (float/int, z-coordinate of the origin in case r is not None) –
fill_value (float/int) –
None (... If r is not) –
zz**2) –
fignum (int, figure number (>=1)) –
subplot (int, e.g. 121, 111, 331, default=None) –
matplotlib (... the three digit notaton for the) –
figsize (tuple, figure size in inches e.g.- (8, 8)) –
labelaxes (bool, default True) –
True (... If) –
x(mm) (it labels each axis as) –
y(mm) –
z(mm) –
- Returns
fig, ax
- Return type
matplotlib.figure.Figure instance, matplotlib.axes.Axes instance,
- tflow.graph.plot_multicolor(x, y=None, colored_by=None, cmap='viridis', fignum=1, figsize=None, subplot=None, fig=None, ax=None, maskon=False, thd=1, linewidth=2, vmin=None, vmax=None, verbose=True, **kwargs)
plot a graph using given x,y fignum can be specified any kwargs from plot can be passed
org source: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html
- tflow.graph.plot_saddoughi(fignum=1, fig=None, ax=None, figsize=None, label='Re$_{\\lambda} \\approx 600 $ \n SV, 1994', color='k', alpha=0.6, subplot=None, cc=1, legend=False, plotEk=False, **kwargs)
plot universal 1d energy spectrum (Saddoughi, 1992)
E(k)=C epsilon^(2/3)k^(-5/3), E11(k)=C1 epsilon^(2/3)k^(-5/3) # # In iso, homo, turbulence, C1 = 18/55 C. (Pope 6.242) # c = 1.6 # c1 = 18. / 55. * c
- tflow.graph.plot_saddoughi_struc_func(fignum=1, fig=None, ax=None, figsize=None, label='Re$_{\\lambda} \x07pprox 600 $ \n Saddoughi and Veeravalli, 1994', color='k', alpha=0.6, subplot=None, legend=False, **kwargs)
Plots the second order structure function on Saddoughi & Veeravalli, 1994
- Parameters
fignum –
fig –
ax –
figsize –
label –
color (str, array-like (1d)) –
alpha –
subplot –
legend –
marker (str or list) – … Unlike the plt.scatter(), this accepts a list for markers. A useful feature if one wants to plot with different markers
kwargs –
- Returns
- Return type
fig, ax
- tflow.graph.plot_spline(x_, y_, order=3, fignum=1, figsize=None, subplot=None, fig=None, ax=None, log=False, label='', color=None, legend=False, maskon=False, thd=1.0, **kwargs)
Plots a spline representation of a curve (x against y)
- Parameters
x (1d array-like) –
y (1d array-like) –
order (int, order of spline interpolation) –
fignum (int, figure number, default=1) –
figsize (tuple, figure size e.g. (8, 8) in inch) –
int (subplot#) –
notation (e.g.- 121- matplotlib shorthand) –
fig (matplotlib.figure.Figure instance, default: None) –
ax (matplotlib.axes.Axes instance, default: None) – … If passed, this function plots a curve on the given ax.
label (str, label of the curve) –
color (str, color e.g.- 'r' for red, 'b' for blue. Consult mpl website for the full color code.) –
legend (bool, If True, ax.legend() is called.) –
maskon (bool, If True, it uses get_mask4erroneous_pts() to spot potentially erroneous values, and hides them.) –
thd (float, This argument is only relevant if maskon=True. This is a parameter which controls the tolerance of the jumpiness of hte plot.) – … The higher thd is, the less inputs gets hide.
kwargs (dict, The other keyword arguments gets passed to ax.plot()) –
- Returns
fig, ax
- Return type
matplotlib.figure.Figure instance, matplotlib.axes.Axes instance
- tflow.graph.plot_surface(x, y, z, shade=True, fig=None, ax=None, fignum=1, subplot=None, figsize=None, azdeg=0, altdeg=65)
plot_surface for the graph module … By default, it enables the shading feature
- Parameters
x –
y –
z –
shade –
fignum –
subplot –
figsize –
- tflow.graph.plot_with_arrows(x, y=None, fignum=1, figsize=None, label='', color=None, subplot=None, legend=False, fig=None, ax=None, maskon=False, thd=1, **kwargs)
Add doc later :param x: :param y: :param fignum: :param figsize: :param label: :param color: :param subplot: :param legend: :param fig: :param ax: :param maskon: :param thd: :param kwargs:
- tflow.graph.plot_with_varying_alphas(x, y=None, color='#1f77b4', alphas=None, fignum=1, figsize=None, subplot=None, fig=None, ax=None, xmin=None, xmax=None, maskon=False, thd=1, linewidth=2, **kwargs)
Plots a curve with varying alphas (e.g. fading curves) … plt.plot(x, y, alpha=alpha) does not allow varying alpha. … A workaround for this is to use LineCollection. i.e. create lines for each segment, then assign different alpha values
- Parameters
x –
y –
color (color of the line) –
alphas (list/array with the same length as x and y) – … default: alphas = 1 - np.linspace(0, 1, len(x)) (linearly fade)
x –
y –
color –
alphas –
fignum –
figsize –
subplot –
fig –
ax –
xmin –
xmax –
maskon –
thd –
linewidth –
kwargs –
- tflow.graph.plotfunc(func, x, param, fignum=1, subplot=111, ax=None, label=None, color=None, linestyle='-', legend=False, figsize=None, **kwargs)
plot a graph using the function fun fignum can be specified any kwargs from plot can be passed Use the homemade function refresh() to draw and plot the figure, no matter the way python is called (terminal, script, notebook)
- tflow.graph.quiver(x, y, u, v, subplot=None, fignum=1, figsize=None, ax=None, inc_x=1, inc_y=1, inc=None, color='k', vmin=None, vmax=None, units='inches', scale=None, key=True, key_loc=[0.08, 1.06], key_length=None, key_label=None, key_units='mm/s', key_labelpos='E', key_pad=25.0, key_fmt='.1f', key_kwargs={}, aspect='equal', **kwargs)
Wrapper for plt.quiver()
Some tips: … plt.quiver() autoscales the arrows. This may be problematic if you want to show them with absolute scales. … I got a workaround for you. You can control this by toggling a boolean “absolute” …… If “absolute” is False, it autoscales. …… If “absolute” is True, you must supply “scale” (float) ……… e.g. Plot two quiver plots with the same scale
fig1, ax1, Q1 = quiver(x1, y1, u1, v1, scale=4, fignum=1, key_length=50) quiver(x2, y2, u2, v2, scale=4, fignum=2, key_length=50) # scale could be Q1.scale
- ………… This ensures to plot the arrows with the same scale with the same quiver key.
This is essential to create an animation of quiver plots to avoid distraction.
- Parameters
x –
y –
u –
v –
subplot –
fignum –
figsize –
ax –
inc_x –
inc_y –
inc –
color –
vmin –
vmax –
absolute –
u_ref –
key –
key_loc –
key_length –
key_label –
key_units –
key_labelpos –
key_pad –
key_fmt –
key_kwargs –
aspect –
kwargs –
- tflow.graph.quiver3d(udata, normalize=False, mag=1, inc=1, xinc=None, yinc=None, zinc=None, umin=0, umax=None, vmin=0, vmax=None, add_bounding_box=True, notebook=True, show=True, save=False, savepath='./vectorfield.png', verbose=True, **kwargs)
3D Quiver plot using pyvista
- Parameters
udata (4d array with shape (3, y, x, z)) –
normalize (bool, default: False. If True, it ignores the magnitude in udata. All vectors have the magnitude of 1.) – … This is handy if you would like to assess the directions of the field.
mag (float greater than 0, default:1. udata*mag gets plotted. Sometimes, it is necessary to multiply a scalar to see the quivers.) –
inc (int, default:1. Increment of quivers to be plotted- if inc=1, it plots all vectors in udata.) – If inc=2, it plots vectors every 2 xsteps, 2ysteps, and 2zsteps. i.e. 1/8 of vectors in udata gets plotted
xinc (int, default:1. Increment of quivers to be plotted along the x-axis (the third index of udata)) –
yinc (int, default:1. Increment of quivers to be plotted along the y-axis (the second index of udata)) –
zinc (int, default:1. Increment of quivers to be plotted along the z-axis (the fourth index of udata)) –
vmin (float, default: 0. The color range is specified by [vmin, vmax]) –
vmax (float, default: None. The default is the maximum value in udata) –
add_bounding_box (bool, default: True. If True, it draws a bounding box of udata) –
save (bool, default: False. If True, it saves an image (png) at savepath.) –
savepath (str, a path where an image gets saved if save is True.) –
verbose (bool, default: True. If False, it suppresses print outputs.) –
- Returns
plobj, a
- Return type
pyvista.Plotter instance, returned object of pyvista.Plotter.add_arrows()
- tflow.graph.resample(x, y, n=100, mode='linear')
Resample x, y … this is particularly useful to crete a evenly spaced data in log from a linearly spaced data, and vice versa
- Parameters
x (1d array) –
y (1d array) –
n (int, number of points to resample) –
mode (str, options are "linear" and "log") –
- Returns
x_new, y_rs
- Return type
1d arrays of new x and new y
- tflow.graph.reset_figure_params()
- tflow.graph.reset_sfmt(fformat='%03.1f')
- tflow.graph.save(path, ext='pdf', close=False, verbose=True, fignum=None, dpi=None, overwrite=True, tight_layout=False, savedata=True, transparent=True, bkgcolor='w', **kwargs)
Save a figure from pyplot
- Parameters
path (string) – The path (and filename, without the extension) to save the figure to.
ext (string (default='png')) – The file extension. This must be supported by the active matplotlib backend (see matplotlib.backends module). Most backends support ‘png’, ‘pdf’, ‘ps’, ‘eps’, and ‘svg’.
ext – The file extension. This must be supported by the active matplotlib backend (see matplotlib.backends module). Most backends support ‘png’, ‘pdf’, ‘ps’, ‘eps’, and ‘svg’.
close (boolean (default=True)) – Whether to close the figure after saving. If you want to save the figure multiple times (e.g., to multiple formats), you should NOT close it in between saves or you will have to re-plot it.
verbose (boolean (default=True)) – Whether to print information about when and where the image has been saved.
fignum –
dpi –
overwrite –
tight_layout –
savedata –
transparent –
bkgcolor –
kwargs –
- tflow.graph.scatter(x, y, ax=None, fig=None, fignum=1, figsize=None, marker='o', fillstyle='full', label=None, subplot=None, legend=False, maskon=False, thd=1, xmin=None, xmax=None, alpha=1.0, set_bottom_zero=False, symmetric=False, set_left_zero=False, **kwargs)
plot a graph using given x,y fignum can be specified any kwargs from plot can be passed Use the homemade function refresh() to draw and plot the figure, no matter the way python is called (terminal, script, notebook)
- tflow.graph.scatter3d(x, y, z, ax=None, fig=None, fignum=1, figsize=None, marker='o', fillstyle='full', label=None, subplot=None, legend=False, labelaxes=True, **kwargs)
plot a graph using given x,y fignum can be specified any kwargs from plot can be passed Use the homemade function refresh() to draw and plot the figure, no matter the way python is called (terminal, script, notebook)
- tflow.graph.set_axes_equal(ax)
Make axes of 3D plot have equal scale so that spheres appear as spheres, cubes as cubes, etc.. This is one possible solution to Matplotlib’s ax.set_aspect(‘equal’) and ax.axis(‘equal’) not working for 3D.
- Input
ax: a matplotlib axis, e.g., as output from plt.gca().
- tflow.graph.set_color_cycle(cmapname='tab10', ax=None, n=10, colors=None)
Sets a color cycle of a particular Axes instance
sns_palettes = [‘deep’, ‘muted’, ‘bright’, ‘pastel’, ‘dark’, ‘colorblind’] # sns_palettes matplotlab cmap names: ‘tab10’ (default cmap of mpl), ‘tab20’, ‘Set1’, ‘Set2’ etc. (https://matplotlib.org/stable/tutorials/colors/colormaps.html) … One may specify the color cycles using the existing color maps (seaborn and matplotlib presets)
or a list of colors specified by a user.
… For the presets, pass a name of the colormap like “tab10” (mpl default), “muted” (seaborn defualt) … For a more customized color cycle, pass a list of colors to ‘colors’.
- Parameters
cmapname (str, name of the cmap like 'viridis', 'jet', etc.) –
n (int, number of colors) –
colors (list, a list of colors like ['r', 'b', 'g', 'magenta']) –
- Returns
- Return type
None
- tflow.graph.set_color_cycle_custom(ax, colors=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
Sets a color cycle using a list :param ax: :param colors: :type colors: list of colors in rgb/cnames/hex codes
- tflow.graph.set_color_cycle_gradient(ax, color1='greenyellow', color2='navy', n=10)
- tflow.graph.set_default_color_cycle(name='tab10', n=10, colors=None, reverse=False)
Sets a color cycle for plotting
sns_palettes = [‘deep’, ‘muted’, ‘bright’, ‘pastel’, ‘dark’, ‘colorblind’] # sns_palettes matplotlab cmap names: ‘tab10’ (default cmap of mpl), ‘tab20’, ‘Set1’, ‘Set2’ etc. (https://matplotlib.org/stable/tutorials/colors/colormaps.html) … One may specify the color cycles using the existing color maps (seaborn and matplotlib presets)
or a list of colors specified by a user.
… For the presets, pass a name of the colormap like “tab10” (mpl default), “muted” (seaborn defualt) … For a more customized color cycle, pass a list of colors to ‘colors’.
- Parameters
name (str, name of the cmap) –
n (int, number of colors) –
colors (list, a list of colors like ['r', 'b', 'g', 'magenta']) –
- Returns
- Return type
None
- tflow.graph.set_fig(fignum, subplot=111, dpi=100, figsize=None, custom_cycler=False, custom_cycler_dict={'color': ['r', 'b', 'g', 'y'], 'linestyle': ['-', '-', '-', '-'], 'linewidth': [3, 3, 3, 3], 'marker': ['o', 'o', 'o', 'o'], 's': [0, 0, 0, 0]}, **kwargs)
Returns Figure and Axes instances … a short sniplet for
plt.figure(fignum, dpi=dpi, figsize=figsize) plt.subplot(subplot, **kwargs)
- Parameters
fignum (int, figure number) –
subplot (int, A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5) Note that this can only be used if there are no more than 9 subplots.) –
dpi (int,) –
figsize (tuple, figure size) –
custom_cycler (bool, If True, it enables users to customize a plot style (color cycle, marker cycle, linewidth cycle etc.)) – … The customized cycler could be passed to custom_cycler_dict.
custom_cycler_dict (dict, A summary of a plotting style.) –
- … E.g.- default_custom_cycler = {‘color’: [‘r’, ‘b’, ‘g’, ‘y’],
’linestyle’: [‘-’, ‘-’, ‘-’, ‘-‘], ‘linewidth’: [3, 3, 3, 3], ‘marker’: [‘o’, ‘o’, ‘o’, ‘o’], ‘s’: [0,0,0,0]}
… The dictionary is turned into a list of cyclers, and passed to ax.set_prop_cycle(custom_cycler).
kwargs (Visit plt.subplot(**kwargs) for available kwargs) –
- Returns
fig (Figure instance)
ax (Axes instance)
- tflow.graph.set_fontsize_scientific_text(ax, fontsize)
Set fontsize for the scientific format
- Parameters
fontsize (int) –
- tflow.graph.set_grid_invisible(ax)
Makes the background grid invisible :param ax: :type ax: axes.Axes instance
- Returns
- Return type
None
- tflow.graph.set_pane_invisible(ax)
Makes the background pane invisible
- Parameters
ax (axes.Axes instance) –
- Returns
- Return type
None
- tflow.graph.set_standard_pos(ax)
Sets standard positions for added texts in the plot left: 0.025, right: 0.75 bottom: 0.10 top: 0.90 xcenter: 0.5 ycenter:0.5 :param ax:
- Returns
top, bottom, right, left, xcenter, ycenter
- Return type
float, position
- tflow.graph.set_xtick_interval(ax, tickint)
Sets x-tick interval as tickint :param ax: :type ax: Axes object :param tickint: :type tickint: float, tick interval
- tflow.graph.set_ytick_interval(ax, tickint)
Sets y-tick interval as tickint :param ax: :type ax: Axes object :param tickint: :type tickint: float, tick interval
- tflow.graph.setaxes(ax, xmin, xmax, ymin, ymax, **kwargs)
- tflow.graph.show()
- tflow.graph.show_plot_styles()
Prints available plotting styles
- tflow.graph.simple_legend(ax, facecolor='white', **kwargs)
Removes the errorbars from the legend
- tflow.graph.simplest_fraction_in_interval(x, y)
Return the fraction with the lowest denominator in [x,y].
- tflow.graph.skipcolor(numskip, color_cycle=<itertools.cycle object>)
Skips numskip times in the color_cycle iterator Can be used to reset the color_cycle
- tflow.graph.smooth(x, window_len=11, window='hanning', log=False)
smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with a given signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal.
- input:
x: the input signal window_len: the dimension of the smoothing window; should be an odd integer window: the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’
flat window will produce a moving average smoothing.
- output:
the smoothed signal
example:
t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.filter
TODO: the window parameter could be the window itself if an array instead of a string NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
- tflow.graph.smooth1d(x, window_len=11, window='hanning', log=False)
smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with a given signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal.
- input:
x: the input signal window_len: the dimension of the smoothing window; should be an odd integer window: the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’
flat window will produce a moving average smoothing.
- output:
the smoothed signal
example:
t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.filter
TODO: the window parameter could be the window itself if an array instead of a string NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
- tflow.graph.streamplot(x, y, u, v, subplot=None, fignum=1, figsize=None, ax=None, density=[1.0, 1.0], aspect='equal', **kwargs)
Plots streamlines (2D)
- Parameters
x (2d array) –
y (2d array) –
u (2d array) –
v (2d array) –
subplot (int) –
fignum (int) –
figsize (tuple) –
ax (matplotlib.ax.Axes instance) –
density (1d array-like) – … density of streamlines
aspect (str, default: "equal") – … options: “equal”, “auto”
kwargs (dict) – … passed to ax.streamplot()
- tflow.graph.suptitle(title, fignum=None, tight_layout=True, rect=[0, 0.03, 1, 0.95], **kwargs)
Add a centered title to the figure. If fignum is given, it adds a title, then it reselects the figure which selected before this method was called. … this is because figure class does not have a suptitle method. … :param title: :param fignum: :param kwargs:
- tflow.graph.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
Reminder for myself how tight_layout works with the ect option fig.tight_layout(rect=rect) :param fig: :param rect:
- tflow.graph.title(ax, title, **kwargs)
ax.set_title(title, **kwargs) … if you want more space for the tile, try “pad=50”
- Parameters
ax –
title –
subplot –
kwargs –
- tflow.graph.tologlog(ax=None, **kwargs)
- tflow.graph.tosemilogx(ax=None, **kwargs)
- tflow.graph.tosemilogy(ax=None, **kwargs)
- tflow.graph.update_figure_params(params)
update a default matplotlib setting e.g. params = { ‘legend.fontsize’: ‘x-large’,
‘figure.figsize’: (15, 5), ‘axes.labelsize’: ‘x-large’, ‘axes.titlesize’:’x-large’, ‘xtick.labelsize’:’x-large’, ‘ytick.labelsize’:’x-large’}
… pylab.rcParams.update(params) :param params: :type params: dictionary
- Returns
- Return type
None
- tflow.graph.use_backend(name='agg')
- tflow.graph.use_plot_style(stylename)
Reminder for me how to set a plotting style
- tflow.graph.use_symmetric_ylim(ax)