Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 25 additions & 36 deletions openfast_toolbox/io/amrwind_file.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Read AMR-Wind NETCDF file

"""
import os
import xarray as xr
import numpy as np

Expand All @@ -25,12 +26,12 @@ def priority(): return 60 # Priority in weio.read fileformat list between 0=high
def __init__(self, filename=None, timestep=None, output_frequency=None, **kwargs):
self.filename = filename
self.amrwind_dt = timestep
self.output_dt = timestep * output_frequency
self.output_dt = timestep * output_frequency if timestep else None

if filename:
self.read(**kwargs)

def read(self, group_name):
def read(self, filename=None, group_name=None):
"""
Parameters
----------
Expand All @@ -51,40 +52,28 @@ def read(self, group_name):
raise Exception('File is empty:',self.filename)


ds = xr.open_dataset(self.filename,group=group_name)

coordinates = {"x":(0,"axial"), "y":(1,"lateral"),"z":(2,"vertical")}
c = {}
for coordinate,(i,desc) in coordinates.items():
c[coordinate] = xr.IndexVariable(
dims=[coordinate],
data=np.sort(np.unique(ds['coordinates'].isel(ndim=i))),
attrs={"description":"{0} coordinate".format(desc),"units":"m"}
)
c["t"] = xr.IndexVariable(
dims=["t"],
data=ds.num_time_steps*self.output_dt,
attrs={"description":"time from start of simulation","units":"s"}
)

self.nt = len(c["t"])
self.nx = len(c["x"])
self.ny = len(c["y"])
self.nz = len(c["z"])

coordinates = {"x":(0,"axial","u"), "y":(1,"lateral","v"),"z":(2,"vertical","w")}
v = {}
for coordinate,(i,desc,u) in coordinates.items():
v[u] = xr.DataArray(np.reshape(getattr(ds,"velocity{0}".format(coordinate)).values,(self.nt,self.nx,self.ny,self.nz)),
coords=c,
dims=["t","x","y","z"],
name="{0} velocity".format(desc),
attrs={"description":"velocity along {0}".format(coordinate),"units":"m/s"})

ds = xr.Dataset(data_vars=v, coords=v[u].coords)
ds.attrs = {"original file":self.filename}

self.data = ds
ds = xr.open_dataset(self.filename,group=group_name)
if self.output_dt is None:
time = xr.open_dataset(self.filename)['time'].values
self.output_dt = float(time[1] - time[0])

xyz = ds['coordinates'].values
axes, idx = zip(*(np.unique(xyz[:, i], return_inverse=True) for i in range(3)))
self.nt = ds.sizes['num_time_steps']
self.nx, self.ny, self.nz = map(len, axes)
if self.nx * self.ny * self.nz != len(xyz):
raise ValueError('Sampling points are not on an axis-aligned grid')

c = {"t": ("t", np.arange(self.nt) * self.output_dt,
{"description": "time from start of simulation", "units": "s"})}
v = {}
for k, u, desc, a in zip("xyz", "uvw", ("axial", "lateral", "vertical"), axes):
c[k] = (k, a, {"description": "{0} coordinate".format(desc), "units": "m"})
vel = np.full((self.nt, self.nx, self.ny, self.nz), np.nan)
vel[:, idx[0], idx[1], idx[2]] = ds["velocity" + k].values
v[u] = (("t", "x", "y", "z"), vel, {"description": "velocity along {0}".format(k), "units": "m/s"})

self.data = xr.Dataset(v, coords=c, attrs={"original file": self.filename})


def write(self, filename=None):
Expand Down
3 changes: 2 additions & 1 deletion openfast_toolbox/io/fast_input_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import pandas as pd
import re
try:
from .file import File, WrongFormatError, BrokenFormatError
from .file import File, WrongFormatError, BrokenFormatError, EmptyFileError
except:
File = dict
class WrongFormatError(Exception): pass
class BrokenFormatError(Exception): pass
class EmptyFileError(Exception): pass

__all__ = ['FASTInputFile']

Expand Down
11 changes: 3 additions & 8 deletions openfast_toolbox/io/turbsim_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,14 +850,11 @@ def fromAMRWind(self, filename, timestep, output_frequency, sampling_identifier,

obj = AMRWindFile(filename,timestep,output_frequency, group_name=sampling_identifier)

self["u"] = np.ndarray((3,obj.nt,obj.ny,obj.nz))

xloc = float(obj.data.x[0]) if xloc is None else xloc
if verbose:
print("Grabbing the slice at x={0} m".format(xloc))
self['u'][0,:,:,:] = np.swapaxes(obj.data.u.sel(x=xloc).values,1,2)
self['u'][1,:,:,:] = np.swapaxes(obj.data.v.sel(x=xloc).values,1,2)
self['u'][2,:,:,:] = np.swapaxes(obj.data.w.sel(x=xloc).values,1,2)
plane = obj.data.sel(x=xloc)
self['u'] = np.stack([plane.u.values, plane.v.values, plane.w.values])
self['t'] = obj.data.t.values

self['y'] = obj.data.y.values
Expand All @@ -873,12 +870,10 @@ def fromAMRWind(self, filename, timestep, output_frequency, sampling_identifier,
if verbose:
print("Setting the TurbSim file reference height to z={0} m".format(self["zRef"]))

self['uRef'] = float(obj.data.u.sel(x=xloc).sel(y=0).sel(z=self["zRef"]).mean().values)
self['uRef'] = None
self['zRef'], self['uRef'], bHub = self.hubValues()

if fileout is not None:
filebase = os.path.splitext(filename)[1]
fileout = filebase+".bts"
if verbose:
print("===> {0}".format(fileout))
self.write(fileout)
Expand Down
5 changes: 3 additions & 2 deletions openfast_toolbox/tools/fatigue.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def equivalent_load(time, signal, m=3, Teq=1, bins=100, method='rainflow_windap'
if len(time)<=1:
raise Exception()
if type(time[0]) is np.datetime64:
T = T/np.timedelta64(1,'s') # or T.item().total_seconds()
T = (time[-1]-time[0])/np.timedelta64(1,'s')
else:
T = time[-1]-time[0] # time length of signal (s). Will fail for signal of length 1
if T==0:
Expand Down Expand Up @@ -1205,7 +1205,8 @@ def test_eqload_cornercases(self):
time= [np.datetime64('2023-10-01'), np.datetime64('2023-10-02')]
signal= [0,1]
Leq= equivalent_load(time, signal, m=3, Teq=1, bins=100, method='rainflow_windap')
np.testing.assert_equal(Leq, np.nan)
Leq_s= equivalent_load([0, 86400], signal, m=3, Teq=1, bins=100, method='rainflow_windap')
np.testing.assert_almost_equal(Leq, Leq_s)

# Constant signal
time =[0,1]
Expand Down
2 changes: 1 addition & 1 deletion openfast_toolbox/tools/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def pdf_histogram(y,nBins=50, norm=True, count=False):
dx = xh[1] - xh[0]
xh = xh[:-1] + dx/2
if count:
yh = yh / (len(n)*dx) # TODO DEBUG /VERIFY THIS
yh = yh / (yh.sum()*dx)
else:
yh = yh / (nBins*dx)
if norm:
Expand Down