Ejemplo n.º 1
0
def extract_point(InFolder, OutFolder, timezone, xy, skip=1, col=None):
    if col is None:
        col = ["u", "v", "w", "p", "vorticity_1", "vorticity_2", "vorticity_3"]
    dirs = sorted(os.listdir(InFolder))
    data = pd.read_hdf(InFolder + dirs[0])
    NewFrame = data.loc[data["x"] == xy[0]]
    TemFrame = NewFrame.loc[NewFrame["y"] == xy[1]]
    ind = TemFrame.index.values[0]
    xarr = np.zeros((np.size(timezone), np.size(col)))
    j = 0
    for i in range(np.size(dirs)):
        if i % skip == 0:
            with timer("Extracting probes"):
                frame = pd.read_hdf(InFolder + dirs[i])
                frame = frame.iloc[ind]
                xarr[j, :] = frame[col].values
                j = j + 1
    probe = np.hstack((timezone.reshape(-1, 1), xarr))
    col.insert(0, "t")
    np.savetxt(
        OutFolder + "x" + str(xy[0]) + "y" + str(xy[1]) + ".dat",
        probe,
        fmt="%.8e",
        delimiter="  ",
        header=", ".join(col),
    )
Ejemplo n.º 2
0
def reattach_loc(InFolder, OutFolder, timezone, loc=-0.015625, skip=1, opt=2):
    dirs = sorted(os.listdir(InFolder))
    xarr = np.zeros(np.size(timezone))
    j = 0
    if opt == 1:
        data = pd.read_hdf(InFolder + dirs[0])
        grouped = data.groupby(['x', 'y'])
        data = grouped.mean().reset_index()
        # NewFrame = data.query("x>=9.0 & x<=13.0 & y==-2.99703717231750488")
        NewFrame = data.query("x>=7.5 & x<=13.0")
        TemFrame = NewFrame.loc[NewFrame["y"] == -2.99703717231750488]
        ind = TemFrame.index.values
        for i in range(np.size(dirs)):
            if i % skip == 0:
                with timer("Computing reattaching point " + dirs[i]):
                    frame = pd.read_hdf(InFolder + dirs[i])
                    frame = frame.iloc[ind]
                    xarr[j] = frame.loc[frame["u"] >= 0.0, "x"].head(1)
                    j = j + 1
    else:
        for i in range(np.size(dirs)):
            if i % skip == 0:
                with timer("Computing reattaching point " + dirs[i]):
                    frame = pd.read_hdf(InFolder + dirs[i])
                    grouped = frame.groupby(['x', 'y'])
                    frame = grouped.mean().reset_index()
                    xy = dividing_line(frame, loc=loc)
                    xarr[j] = np.max(xy[:, 0])
                    j = j + 1
    reatt = np.vstack((timezone, xarr)).T
    np.savetxt(
        OutFolder + "Reattach.dat",
        reatt,
        fmt="%.8e",
        delimiter="  ",
        header="t, x",
    )
    return (reatt)
Ejemplo n.º 3
0
def bubble_area(InFolder,
                OutFolder,
                timezone,
                loc=-0.015625,
                step=3.0,
                skip=1,
                cutoff=None):
    dirs = sorted(os.listdir(InFolder))
    area = np.zeros(np.size(timezone))
    j = 0
    if cutoff is None:
        cutoff = -0.015625
    else:
        assert isinstance(cutoff, float), \
            'cutoff:{} is not a float'.format(cutoff.__class__.__name__)
    for i in range(np.size(dirs)):
        if i % skip == 0:
            with timer("Bubble area at " + dirs[i]):
                dataframe = pd.read_hdf(InFolder + dirs[i])
                grouped = dataframe.groupby(['x', 'y'])
                dataframe = grouped.mean().reset_index()
                xy_org = dividing_line(dataframe, loc=loc)
                if (np.max(xy_org[:, 1]) < cutoff):
                    ind = np.argmax(xy_org[:, 1])
                    xy = xy_org[ind:, :]
                    area[j] = trapz(xy[:, 1] + step, xy[:, 0])
                    area[j] = area[j] + 0.5 * xy[0, 0] * (0 - xy[0, 1])
                else:
                    xy = xy_org
                    area[j] = trapz(xy[:, 1] + step, xy[:, 0])
                #ind = np.argmax(xy_new[:, 1])
                # if xy[ind, 1] < cutoff:
                #    area[j] = area[j] + 0.5 * xy[ind, 0] * (0 - xy[ind, 1])
            j = j + 1
    area_arr = np.vstack((timezone, area)).T
    np.savetxt(
        OutFolder + "BubbleArea.dat",
        area_arr,
        fmt="%.8e",
        delimiter="  ",
        header="area",
    )
    return area
Ejemplo n.º 4
0
def shock_foot(InFolder, OutFolder, timepoints, yval, var, skip=1):
    dirs = sorted(os.listdir(InFolder))
    xarr = np.zeros(np.size(timepoints))
    j = 0
    # if np.size(timepoints) != np.size(dirs):
    #    sys.exit("The input snapshots does not match!!!")
    for i in range(np.size(dirs)):
        if i % skip == 0:
            with timer("Computing shock foot location " + dirs[i]):
                frame = pd.read_hdf(InFolder + dirs[i])
                grouped = frame.groupby(['x', 'y'])
                frame = grouped.mean().reset_index()
                NewFrame = frame.loc[frame["y"] == yval]
                temp = NewFrame.loc[NewFrame["u"] >= var, "x"]
                xarr[j] = temp.head(1)
                j = j + 1
    foot = np.vstack((timepoints, xarr)).T
    np.savetxt(
        OutFolder + "ShockFoot.dat",
        foot,
        fmt="%.8e",
        delimiter="  ",
        header="t, x",
    )
Ejemplo n.º 5
0
def shock_loc(InFolder, OutFolder, timepoints, skip=1):
    dirs = sorted(os.listdir(InFolder))
    fig1, ax1 = plt.subplots(figsize=(10, 4))
    ax1.set_xlim([0.0, 30.0])
    ax1.set_ylim([-3.0, 10.0])
    matplotlib.rc("font", size=18)
    data = pd.read_hdf(InFolder + dirs[0])
    x0 = np.unique(data["x"])
    x1 = x0[x0 > 8.0]
    x1 = x1[x1 <= 30.0]
    y0 = np.unique(data["y"])
    y1 = y0[y0 > -2.5]
    xini, yini = np.meshgrid(x1, y1)
    corner = (xini < 0.0) & (yini < 0.0)
    shock1 = np.empty(shape=[0, 3])
    shock2 = np.empty(shape=[0, 3])
    ys1 = 0.5
    ys2 = 5.0
    j = 0
    # if np.size(timepoints) != np.size(dirs):
    #    sys.exit("The input snapshots does not match!!!")
    for i in range(np.size(dirs)):
        if i % skip == 0:
            with timer("Shock position at " + dirs[i]):
                frame = pd.read_hdf(InFolder + dirs[i])
                grouped = frame.groupby(['x', 'y'])
                frame = grouped.mean().reset_index()
                gradp = griddata((frame["x"], frame["y"]), frame["|gradp|"],
                                 (xini, yini))
                gradp[corner] = np.nan
                cs = ax1.contour(xini,
                                 yini,
                                 gradp,
                                 levels=[0.06],
                                 linewidths=1.2,
                                 colors="gray")
                xycor = np.empty(shape=[0, 2])
                x1 = np.empty(shape=[0, 1])
                x2 = np.empty(shape=[0, 1])
                for isoline in cs.collections[0].get_paths():
                    xy = isoline.vertices
                    xycor = np.append(xycor, xy, axis=0)
                    ax1.plot(xy[:, 0], xy[:, 1], "r:")
                    ind1 = np.where(np.around(xycor[:, 1], 8) == ys1)[0]
                    x1 = np.append(x1, np.mean(xycor[ind1, 0]))
                    ind2 = np.where(np.around(xycor[:, 1], 8) == ys2)[0]
                    x2 = np.append(x2, np.mean(xycor[ind2, 0]))
                x1 = x1[~np.isnan(x1)]
                if np.size(x1) == 0:
                    x1 = 0.0
                else:
                    x1 = x1[0]
                x2 = x2[~np.isnan(x2)]
                if np.size(x2) == 0:
                    x2 = 0.0
                else:
                    x2 = x2[0]
                ax1.plot(x1, ys1, "g*")
                ax1.axhline(y=ys1)
                ax1.plot(x2, ys2, "b^")
                ax1.axhline(y=ys2)
                shock1 = np.append(shock1, [[timepoints[j], x1, ys1]], axis=0)
                shock2 = np.append(shock2, [[timepoints[j], x2, ys2]], axis=0)
                j = j + 1
    np.savetxt(
        OutFolder + "ShockA.dat",
        shock1,
        fmt="%.8e",
        delimiter="  ",
        header="t, x, y",
    )
    np.savetxt(
        OutFolder + "ShockB.dat",
        shock2,
        fmt="%.8e",
        delimiter="  ",
        header="t, x, y",
    )
size = [9,2]
grid = False
cflevel = np.linspace(0.4, 1.2, 8, endpoint=True)   # contourf level
cmap = 'coolwarm'
contourline=True
ContourlineWidth = 0.6
ContourlineColors = 'k'
# cllevel = np.linspace(0.4, 1.0, 8, endpoint=True)
# -------------------------------------------------------------------------#
# %% Class MyPlot: Data Loading
FoldPath = "plotTest/"
OutFile  = "plotTest/"
# VarList  = ['x [mm]', 'y [mm]', 'z [mm]', 'Vx [m/s]', 'Vy [m/s]', 'Vz [m/s]', 'isValid']
VarList  = ['X','Y','Z','u','v','w']

with timer("Load Meanflow data"):
   Mp = MyPlot()
   Mp.LoadPlt(FoldPath, VarList)

with timer('Normalization'):
   Mp.CoordNorm(R)
   Mp.VarNorm('u',U_inf)
   Mp.VarNorm('v',U_inf)

# %% Plot
plt.rc('text', usetex=True)
plt.rc('grid', linestyle="dashed", color='black',linewidth=0.8,alpha=.5)
fig, ax = plt.subplots(1,4,constrained_layout=True)

cp = [None]*(len(ax))
cl = [None]*(len(ax))
from MyPlot import MyPlot
from scipy.interpolate import griddata
from matplotlib.ticker import AutoMinorLocator

import matplotlib.pyplot as plt
import matplotlib.patches as patches
# plt.rc('text', usetex=True)
# plt.rc('grid', linestyle="dashed", color='black',linewidth=0.5)
FoldPath = "plotTest/TSR2p5/"
OutFile = "plotTest/TSR2p5/"
VarList = ['X', 'Y', 'Z', 'u']
U_inf = 5
Xplane = 2  # X/D

# %% load data
with timer("Load Meanflow data"):
    Mp = MyPlot()
    Mp.LoadPlt(FoldPath, VarList)

# Normalization
with timer('Normalization'):
    Mp.CoordNorm(300.0)
    Mp.VarNorm('u', U_inf)
    # Mp.VarNorm('u',U_inf)

# %% Save data
# with timer('Save flow data'):
#     # Mp.flowdata.to_csv('FlowData.csv')
#     store = pd.HDFStore('FlowData.h5')
#     store['df'] = Mp.flowdata  # save it
#     store['df']  # load it
FoldPath = "Z:\\OpenFOAM\\minghuang-4.1\\run\\AL_VAWT\\TecioneVAWT\\AR1_k2em3_eplson_1em2\\postProcessing\\sampleDict\\5.004323150815\\"

# FoldPath = "Z:\\OpenFOAM\\minghuang-4.1\\run\\AL_VAWT\\TecioneVAWT\\AR2\\postProcessing\\sampleDict\\3.604596474409887\\"

# FoldPath ="Z:\\OpenFOAM\\minghuang-4.1\\run\\AL_VAWT\\TecioneVAWT\\AR3\\postProcessing\\sampleDict\\2.6041686237315\\"

OutPath = "G:\\SURFdrive\\Working\\Paper_writing\\FirstPaper\\3rd_edition\\Figures\\"
casename = "AR" + str(AR)
plane = "UMean_planeXDstar"
saveplot = 0

# VarList  = ['x [mm]', 'y [mm]', 'z [mm]', 'Vx [m/s]', 'Vy [m/s]', 'Vz [m/s]', 'isValid']
VarList = ['X', 'Y', 'Z', 'u', 'v', 'w']
Mp = [None] * (len(planevalue))
with timer("Load Meanflow data"):
    for i in range(len(planevalue)):
        Mp[i] = MyPlot()
        Mp[i].LoadRaw(FoldPath + plane + str(planevalue[i]) + '.raw', VarList)

# %% Plot
plt.rc('text', usetex=True)
plt.rcParams[
    'text.latex.preamble'] = r'\makeatletter \newcommand*{\rom}[1]{\expandafter\@slowromancap\romannumeral #1@} \makeatother'
plt.rc('grid', linestyle="dashed", color='black', linewidth=0.8, alpha=.5)
plt.set_cmap('coolwarm')
# plt.tight_layout()
# plt.xlabel('$\it{X/R}$')
fig, ax = plt.subplots(1,
                       len(planevalue),
                       constrained_layout=True,
# FoldPath = "Z:\\OpenFOAM\\minghuang-4.1\\run\\AL_VAWT\\SmallVAWT\\postProcessing\\sampleDict\\2.004\\"

# ----------------------AC NewMesh-----------------------------
FoldPath = "Z:\\scratch\\S_VAWT\\DoubleP10\\postProcessing\\sampleDict\\1.20044579502\\"
# FoldPath = "Z:\\OpenFOAM\\minghuang-4.1\\run\\ActuatorCylinder\\3DAC\\postProcessing\\sampleDict\\2.2\\"

# -----------------------Output path --------------------------
# OutPath  = "D:\\Ming_DOCUMENTS\\Working\\Paper_writing\\SimulationReport\\FIgures\\"
casename = "AC"
plane = "U_planeX"
saveplot = 0

# VarList  = ['x [mm]', 'y [mm]', 'z [mm]', 'Vx [m/s]', 'Vy [m/s]', 'Vz [m/s]', 'isValid']
VarList = ['X', 'Y', 'Z', 'u', 'v', 'w']
Mp = [None] * (len(planevalue))
with timer("Load Meanflow data"):
    for i in range(len(planevalue)):
        Mp[i] = MyPlot()
        Mp[i].LoadRaw(FoldPath + plane + str(planevalue[i]) + '.raw', VarList)
        Mp[i].CoordNorm(2 * R)

# %% Ct U_plane
with timer("Integration"):
    uw = [None] * (len(planevalue))
    Drag = [None] * (len(planevalue))
    KEnergy = [None] * (len(planevalue))
    for i in range(len(planevalue)):
        df = Mp[i].flowdata
        # round(df['u'],2)
        # VarInt = (U_inf - df['u'])*df['u']
        n = 100
from timer_post import timer
from time import time
from MyPlot import MyPlot
from scipy.interpolate import griddata

import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
plt.set_cmap('coolwarm')

# %% Class method
FoldPath = "plotTest/"
OutFile = "plotTest/"
# VarList  = ['x [mm]', 'y [mm]', 'z [mm]', 'Vx [m/s]', 'Vy [m/s]', 'Vz [m/s]', 'isValid']
VarList = ['X', 'Y', 'Z', 'u']
with timer("Load Meanflow data"):
    Mp = MyPlot()
    Mp.LoadPlt(FoldPath, VarList)

with timer('Normalization'):
    Mp.CoordNorm(300.0)

# %%
with timer("Plot Ux on Z/D = 0"):
    # xg, yg = Mp.extract_plane('Z', 0.0,intp='intp', m=200, n=200)
    xg, yg, ExtDf = Mp.ExtractPlane('Z', 0)  # extract Z plane
    # Mp.flowdata = Mp.flowdata.fillna(0)
    Ug = griddata((ExtDf['X'], ExtDf['Y']),
                  ExtDf['u'], (xg, yg),
                  method='linear')
    fig1, ax1 = plt.subplots()
from MyPlot import MyPlot
from scipy.interpolate import griddata
from matplotlib.ticker import AutoMinorLocator

import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.rc('text', usetex=True)
# plt.rc('grid', linestyle="dashed", color='black',linewidth=0.5)

# %% Class MyPlot: Data Loading
FoldPath = "plotTest/"
OutFile = "plotTest/"
# VarList  = ['x [mm]', 'y [mm]', 'z [mm]', 'Vx [m/s]', 'Vy [m/s]', 'Vz [m/s]', 'isValid']
VarList = ['X', 'Y', 'Z', 'u', 'v', 'w', 'u_std', 'Om_y', 'Om_z']
U_inf = 5.0
with timer("Load Meanflow data"):
    Mp = MyPlot()
    Mp.LoadPlt(FoldPath, VarList)

# Processing
with timer('Normalization'):
    # Mp.CoordNorm(150.0)
    Mp.VarNorm('X', 150)
    Mp.VarNorm('Y', 150)
    Mp.VarNorm('Z', 300)
    Mp.VarNorm('u', U_inf)
    Mp.VarNorm('v', U_inf)
    Mp.VarNorm('w', U_inf)
    Mp.VarNorm('u_std', U_inf)
    Mp.VarNorm('Om_y', U_inf / 0.03)
    Mp.VarNorm('Om_z', U_inf / 0.03)