Exemple #1
0
def discreteWaveletAnalysis(vx, wDict):
    from utilities import dataFromDict
    try:
        import pywt
    except:
        sys.exit(' Library pywt not installed. Exiting ...')

    # nlevel = 4
    order = 'freq'  # "normal"
    wavelet = dataFromDict('wavelet', wDict, allowNone=False)
    nlevel = dataFromDict('nlevel', wDict, allowNone=False)
    if (wavelet in pywt.wavelist()):
        try:
            wp = pywt.WaveletPacket(vx, wavelet, 'sym', maxlevel=nlevel)
        except:
            print(" Wrong wavelet type given. Reverting to default 'db2'. ")
            wavelet = 'db2'
            wp = pywt.WaveletPacket(vx, wavelet, 'sym', maxlevel=nlevel)

    nodes = wp.get_level(nlevel, order=order)
    labels = [n.path for n in nodes]
    values = np.array([n.data for n in nodes], 'd')
    values = abs(values)

    return values, labels
Exemple #2
0
def addImagePlotDict(fig, RDict):
    global cmaps

    R = dataFromDict('R', RDict, allowNone=False)
    ex = dataFromDict('extent', RDict, allowNone=True)
    ttl = dataFromDict('title', RDict, allowNone=True)
    xlbl = dataFromDict('xlabel', RDict, allowNone=True)
    ylbl = dataFromDict('ylabel', RDict, allowNone=True)
    gOn = dataFromDict('gridOn', RDict, allowNone=False)
    lOn = dataFromDict('limsOn', RDict, allowNone=False)
    cm = dataFromDict('cmap', RDict, allowNone=True)
    orig = dataFromDict('origin', RDict, allowNone=True)

    ax = addFigAxes(fig)
    im = ax.imshow(np.real(R), origin=orig, extent=ex, aspect='auto', cmap=cm)

    ax.set_title(ttl)
    ax.set_xlabel(xlbl)
    ax.set_ylabel(ylbl)
    ax.grid(gOn)

    if (lOn):
        cbar = userColormapSettings(fig, im, np.max(R), np.min(R))
    else:
        cbar = fig.colorbar(im)

    return fig
Exemple #3
0
def continuousWaveletAnalysis(vx, wDict):
    from utilities import dataFromDict
    import pywt

    wavelet = dataFromDict('wavelet', wDict, allowNone=False)
    nfreqs = dataFromDict('nfreqs', wDict, allowNone=False)
    dt = dataFromDict('dt', wDict, allowNone=False)
    linearFreq = dataFromDict('linearFreq', wDict, allowNone=True)
    if (linearFreq):
        scales = 1. / np.arange(1, nfreqs)
    else:
        scales = np.arange(1, nfreqs)

    cfs, freq = pywt.cwt(vx, scales, wavelet, dt)

    return cfs, freq
Exemple #4
0
def plotCiXY(fig, pDict):
    fn = dataFromDict('filename', pDict, allowNone=False)
    Cx = dataFromDict('Cx', pDict, allowNone=True)
    Cy = dataFromDict('Cy', pDict, allowNone=True)
    linemode = dataFromDict('lm', pDict, allowNone=False)
    logOn = dataFromDict('logOn', pDict, allowNone=True)
    revAxes = dataFromDict('revAxes', pDict, allowNone=True)
    ylims = dataFromDict('ylims', pDict, allowNone=True)
    xlims = dataFromDict('xlims', pDict, allowNone=True)

    labelStr = labelString(fn)

    if (Cx is None): Cx = 1.
    if (Cy is None): Cy = 1.

    d, v, v_l, v_u = ciDataFromFile(fn)

    ax = fig.add_axes([0.15, 0.075, 0.8,
                       0.81])  #[left, up, width, height], fig.add_subplot(111)

    d, xp, yp, v_l, v_u = ciScaleVals(d, v, v_l, v_u, Cx, Cy, revAxes)

    if (revAxes):
        xlb = 'V(d)'
        ylb = 'd'
    else:
        ylb = 'V(d)'
        xlb = 'd'

    if (logOn):
        if (revAxes):
            plotf = ax.semilogx
            fillbf = ax.fill_betweenx
        else:
            plotf = ax.semilogy
            fillbf = ax.fill_between
    else:
        plotf = ax.plot
        if (revAxes):
            fillbf = ax.fill_betweenx
        else:
            fillbf = ax.fill_between

    lines = plotf( xp, yp, linestyle_stack(lm=linemode), lw=3.5, \
      label=labelStr, color=color_stack(lm=linemode))
    linef = fillbf(d,
                   v_u,
                   v_l,
                   facecolor='white',
                   edgecolor='white',
                   alpha=0.25)
    ax.set_ybound(lower=ylims[0], upper=ylims[1])
    ax.set_xbound(lower=xlims[0], upper=xlims[1])
    ax.set_xlabel(xlb)
    ax.set_ylabel(ylb)

    return fig
Exemple #5
0
def continuousWaveletAnalysis(vx, wDict):
    from utilities import dataFromDict
    try:
        import pywt
    except:
        sys.exit(' Library pywt not installed. Exiting ...')

    wavelet = dataFromDict('wavelet', wDict, allowNone=False)
    nfreqs = dataFromDict('nfreqs', wDict, allowNone=False)
    dt = dataFromDict('dt', wDict, allowNone=False)
    linearFreq = dataFromDict('linearFreq', wDict, allowNone=True)
    if (linearFreq):
        scales = 1. / np.arange(1, nfreqs)
    else:
        scales = np.arange(1, nfreqs)

    cfs, freq = pywt.cwt(vx, scales, wavelet, dt)

    return cfs, freq
Exemple #6
0
def addContourf(X, Y, Q, CfDict=None):
    Xdims = np.array(X.shape)
    figDims = 12. * (Xdims[::-1].astype(float) / np.max(Xdims))
    #figDims  = (11,11)
    #figDims  = (9,11)
    fig = plt.figure(figsize=figDims)
    #fig, ax = plt.subplots()
    ax = addFigAxes(fig)

    # Default values
    labelStr = ' Q(X,Y) '
    titleStr = ' Title:  Q(X,Y) '
    cm = None
    vx = None
    vn = None
    levels = None
    N = 12

    if (CfDict is not None):
        titleStr = dataFromDict('title', CfDict, allowNone=False)
        labelStr = dataFromDict('label', CfDict, allowNone=False)
        cm = dataFromDict('cmap', CfDict, allowNone=True)
        N = dataFromDict('N', CfDict, allowNone=True)
        vn = dataFromDict('vmin', CfDict, allowNone=True)
        vx = dataFromDict('vmax', CfDict, allowNone=True)
        levels = dataFromDict('levels', CfDict, allowNone=True)
        if (N is None): N = 12

    #print(' vmax = {}, vmin = {} '.format(vx,vn))
    #levels = [-1e-6, -1e-7, 0, 1e-7, 1e-6]
    #CO = plt.contourf(X,Y,Q, levels )

    if (levels is not None):
        CO = ax.contourf(X, Y, Q, levels, cmap=cm, vmin=vn, vmax=vx)
    else:
        CO = ax.contourf(X, Y, Q, N, cmap=cm, vmin=vn, vmax=vx)

    ax.set_title(titleStr)

    cbar = fig.colorbar(CO)
    if (vx is not None): cbar.vmax = vx
    if (vn is not None): cbar.vmin = vn
    cbar.ax.set_ylabel(labelStr,
                       fontsize=20,
                       fontstyle='normal',
                       fontweight='book',
                       fontname='serif')
    return CO
Exemple #7
0
def plotCiDiffXY(fig, pDict):
    f1 = dataFromDict('fileref', pDict, allowNone=False)
    fn = dataFromDict('filename', pDict, allowNone=False)
    Cx = dataFromDict('Cx', pDict, allowNone=True)
    Cy = dataFromDict('Cy', pDict, allowNone=True)
    linemode = dataFromDict('lm', pDict, allowNone=False)
    logOn = dataFromDict('logOn', pDict, allowNone=True)
    revAxes = dataFromDict('revAxes', pDict, allowNone=True)
    ylims = dataFromDict('ylims', pDict, allowNone=True)
    xlims = dataFromDict('xlims', pDict, allowNone=True)

    labelStr = labelString(fn)

    if (Cx is None): Cx = 1.
    if (Cy is None): Cy = 1.

    d1, v1, v1_l, v1_u = ciDataFromFile(f1)
    d2, v2, v2_l, v2_u = ciDataFromFile(fn)

    if (d2[-1] != d1[-1]):
        if (d2[-1] > d1[-1]
            ):  # Quick and dirty handling for cases when d2[-1] > d1[-1]
            idx = (d2 <= d1[-1])  # Take the terms where values match
            d2 = d2[idx]
            v2 = v2[idx]
            v2_l = v2_l[idx]
            v2_u = v2_u[idx]  # Shorten

            # Compute the ratio to match the resolutions (roughly)
            r = np.round((d2[1] - d2[0]) / (d1[1] - d1[0])).astype(int)

            # Use the matching indecies only
            idm = (np.mod((np.arange(len(d1)) + 1), r) == 0)
            d1 = d1[idm]
            v1 = v1[idm]
            v1_l = v1_l[idm]
            v1_u = v1_u[idm]

    Lm = min(len(v2), len(v1))
    d2 = d2[:Lm]
    v2 = v2[:Lm]
    v2_l = v2_l[:Lm]
    v2_u = v2_u[:Lm]
    d1 = d1[:Lm]
    v1 = v1[:Lm]
    v1_l = v1_l[:Lm]
    v1_u = v1_u[:Lm]

    d1, x1, y1, v1_l, v1_u = ciScaleVals(d1, v1, v1_l, v1_u, Cx, Cy, revAxes)
    d2, x2, y2, v2_l, v2_u = ciScaleVals(d2, v2, v2_l, v2_u, Cx, Cy, revAxes)

    xp, yp, dm = ciDiffVals(x1, y1, v1_l, v1_u, x2, y2, v2_l, v2_u, revAxes)

    if (revAxes):
        xlb = 'D(d)'
        ylb = 'd'
    else:
        ylb = 'D(d)'
        xlb = 'd'

    ax = addFigAxes(fig)

    if (logOn):
        if (revAxes):
            plotf = ax.semilogx
            fillbf = ax.fill_betweenx
        else:
            plotf = ax.semilogy
            fillbf = ax.fill_between
    else:
        plotf = ax.plot
        if (revAxes):
            fillbf = ax.fill_betweenx
        else:
            fillbf = ax.fill_between

    lines = plotf( xp, yp, linestyle_stack(lm=linemode), lw=3., \
      label=labelStr+r': $\left< | \Delta | \right>$={:.2g}'.format(dm) , color=color_stack(lm=linemode))
    #label=r': $\left< | \Delta | \right>$={:.2f}'.format(dm) , color=color_stack(lm=linemode))

    #linef = fillbf( d, v_u, v_l, facecolor='gray', alpha=0.25)

    ax.set_ybound(lower=ylims[0], upper=ylims[1])
    ax.set_xbound(lower=xlims[0], upper=xlims[1])
    ax.set_xlabel(xlb)
    ax.set_ylabel(ylb)

    return fig
Exemple #8
0
def plotXX(fig, pDict):
    fileStr = dataFromDict('filename', pDict, allowNone=False)
    logOn = dataFromDict('logOn', pDict, allowNone=False)
    Cx = dataFromDict('Cx', pDict, allowNone=False)
    Cy = dataFromDict('Cy', pDict, allowNone=False)
    revAxes = dataFromDict('revAxes', pDict, allowNone=False)
    linemode = dataFromDict('lm', pDict, allowNone=False)
    linewidth = dataFromDict('lw', pDict, allowNone=False)
    ylims = dataFromDict('ylims', pDict, allowNone=True)
    xlims = dataFromDict('xlims', pDict, allowNone=True)

    try:
        x = np.loadtxt(fileStr)
    except:
        x = np.loadtxt(fileStr, delimiter=',')

    ax = addFigAxes(fig)

    labelStr = labelString(fileStr)
    #lStr = fileStr.rsplit(".", 1)[0]  # Remove the ".dat"
    #rStr = lStr.rsplit("_")[-1]
    #tStr = lStr.split("/", 2)
    #if( tStr[0] is "." ):
    #  lStr = tStr[1]
    #else:
    #  lStr = tStr[0]

    #labelStr = lStr+"_"+rStr

    # Print each column separately
    amax = 0.
    Ny = (x.shape[1] - 1)

    for i in range(Ny):
        if (Ny == 1):
            labelXX = labelStr
        else:
            labelXX = labelStr + '[' + str(i) + ']'

        if (revAxes):
            yp = Cy * x[:, 0]
            xp = Cx * x[:, i + 1]
            dp = xp
        else:
            xp = Cx * x[:, 0]
            yp = Cy * x[:, i + 1]
            dp = yp

        if (logOn):
            if (revAxes):
                xp = np.abs(xp)
                plotf = ax.semilogx
            else:
                yp = np.abs(yp)
                plotf = ax.semilogy
        else:
            plotf = ax.plot


        lines = plotf( xp, yp, \
          linestyle_stack(lm=linemode), linewidth=linewidth, \
            label=labelXX, color=color_stack(lm=linemode))

        lmax = np.abs(np.max(dp))  # Local maximum
        if (lmax > amax): amax = lmax

    #if( amax <5.e-4 and revAxes):
    #  if( revAxes ): ax.xaxis.set_major_formatter(FormatStrFormatter('%.2e'))
    #  else:          ax.yaxis.set_major_formatter(FormatStrFormatter('%.2e'))

    ax.set_ybound(lower=ylims[0], upper=ylims[1])
    ax.set_xbound(lower=xlims[0], upper=xlims[1])

    ax.set_xlabel(" X ")
    ax.set_ylabel(" Y ")
    return fig
Exemple #9
0
def quadrantAnalysis(v1, v2, qDict):
    from utilities import dataFromDict

    debug = False

    # Extract data from dict. Using dict makes future modifications easy.
    ijk1 = dataFromDict('ijk1', qDict, allowNone=False)
    ijk2 = dataFromDict('ijk2', qDict, False)
    nkpoints = dataFromDict('nkpoints', qDict, True)
    npx = dataFromDict('npixels', qDict, False)
    axisLim = dataFromDict('axisLim', qDict, False)
    holewidth = dataFromDict('holewidth', qDict, False)
    weighted = dataFromDict('weighted', qDict, True)

    # Create arrays for running loops over the selected coordinates.
    iList = np.arange(ijk1[0], ijk2[0] + 1)
    jList = np.arange(ijk1[1], ijk2[1] + 1)
    kList = np.arange(ijk1[2], ijk2[2] + 1)
    '''
  In quadrant analysis context, using a stride in z-direction is usually not desired.
  By default npoints is None.'''
    if (nkpoints is None): stride = 1
    else: stride = max(((kList[-1] - kList[0]) / nkpoints) + 1, 2)

    # Compute the covariance term (for example, u'w')
    v = v1 * v2

    if (debug):
        print('min(v1)={}, max(v1)={}, min(v2)={}, max(v2)={}'\
          .format(np.abs(np.min(v1)), np.max(v1), np.abs(np.min(v2)), np.max(v2)))

    maxLim = np.abs(axisLim)
    minLim = -1. * maxLim

    # Determine if some grid points are under the ground level.
    k_off = max(groundOffset(v1), groundOffset(v2))
    if (k_off > 0 and debug):
        print(' {}: ground offset (k_off) = {}'.format(filename, k_off))

    x = np.linspace(minLim, maxLim, npx + 1)
    y = np.linspace(minLim, maxLim, npx + 1)
    dx = (maxLim - minLim) / (npx)
    X, Y = np.meshgrid(x, y)
    Qi = np.zeros(np.shape(X), float)

    nTot = 0
    nQ = np.zeros(5, int)  # nQ[0] = nQTot
    SQ = np.zeros(5, float)  # SQ[0] = STot
    '''
  Q1: u'(+), w'(+), OutwardInteraction
  Q2: u'(-), w'(+), Ejection
  Q3: u'(-), w'(-), Inward Interaction
  Q4: u'(+), w'(-), Sweep
  '''

    for i in iList:
        for j in jList:
            for k in kList[::stride]:
                vt = v[:, k + k_off, j, i]

                vt_mean = np.mean(np.abs(vt))

                v1t = v1[:, k + k_off, j, i]
                v2t = v2[:, k + k_off, j, i]

                for l in range(len(vt)):
                    SQ[0] += vt[l]
                    nTot += 1
                    if (np.abs(vt[l]) > (holewidth * vt_mean)):
                        n = np.minimum(int((v1t[l] - minLim) / dx), npx)
                        n = np.maximum(n, 0)
                        m = np.minimum(int((v2t[l] - minLim) / dx), npx)
                        m = np.maximum(m, 0)
                        Qi[m, n] += 1.
                        nQ[0] += 1

                        if (v1t[l] > 0. and v2t[l] > 0.):
                            nQ[1] += 1
                            SQ[1] += vt[l]  # Outward Interaction
                        elif (v1t[l] < 0. and v2t[l] > 0.):
                            nQ[2] += 1
                            SQ[2] += vt[l]  # Ejection
                        elif (v1t[l] < 0. and v2t[l] < 0.):
                            nQ[3] += 1
                            SQ[3] += vt[l]  # Inward Interaction
                        else:  #( v1t[l] > 0 and v2t[l] < 0. ):
                            nQ[4] += 1
                            SQ[4] += vt[l]  # Sweep

    v = None
    v1 = None
    v2 = None
    Qi /= (np.float(nQ[0]) * dx**2)  # Obtain the PDF

    if (weighted):
        Qi *= np.abs(X * Y)

    SQ[0] /= np.float(nTot)  # Total contribution
    SQ[1:] /= nQ[1:].astype(float)  # Average contributions

    # Assemble the result dict
    rDict = dict()
    rDict['nQ'] = nQ
    rDict['SQ'] = SQ
    #rDict['klims']= np.array([ kList[0], kList[-1] ])

    return Qi, X, Y, rDict