Ejemplo n.º 1
0
def macroMacroPDF(name, step, pData, varsDir, weight, mcFiles):
    import seaborn as sns
    from resample import unWeighted_resample
    params = {
        'lines.linewidth': 1.5,
        'backend': 'ps',
        'axes.labelsize': 20,
        'font.size': 20,
        'legend.fontsize': 18,
        'xtick.labelsize': 18,
        'ytick.labelsize': 18,
        'text.usetex': True,
        'font.family': 'serif',
        'legend.edgecolor': 'k',
        'legend.fancybox': False
    }
    matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    matplotlib.rcParams.update(params)

    # read in the original sampled parameter set
    labels = [r'$p$' + r' $(\mathrm{MPa})$', r'$q/p$', r'$n$', r'$C^*$']

    # Monte Carlo sequence
    nSample, numOfObs = weight.shape
    enQOIs = np.zeros([4, nSample])
    for i in range(nSample):
        C, CN, K0, e_r11, e_r21, e_a1, n1, overlap, p1, q1 = np.genfromtxt(
            mcFiles[i]).transpose()
        enQOIs[0, i] = p1[step]
        enQOIs[1, i] = q1[step] / p1[step]
        enQOIs[2, i] = n1[step]
        enQOIs[3, i] = CN[step]
    # importance resampling
    ResampleIndices = unWeighted_resample(weight[:, step], nSample * 10)
    sortedIndex = np.argsort(weight[:, step])
    particles = np.copy(pData)
    particles[0, :] /= 1e9
    particles[2, :] /= 1e3
    particles = particles[:, ResampleIndices]
    enQOIs = enQOIs[:, ResampleIndices]

    # plot figures
    figNO = 0
    fig = plt.figure(figsize=(18 / 2.54, 18 / 2.54))
    sns.set(style="ticks", rc=matplotlib.rcParams)
    for i in range(4):
        for j in range(4):
            figNO += 1
            # plot histograms at the initial and final steps
            ax = fig.add_subplot(4, 4, figNO)
            if i == j:
                # estimate pdf using gaussian kernals
                p0, w0 = getPDF(enQOIs[i, :], min(enQOIs[i, :]),
                                max(enQOIs[i, :]))
                ax2 = ax.twinx()
                ax2.fill_between(p0, w0, alpha=0.63, facecolor='black')
                ax2.tick_params(axis='y', right='off', labelright='off')
                ax.set_ylim(min(p0), max(p0))
            elif j < i:
                cmap = sns.dark_palette("black", as_cmap=True)
                ax = sns.kdeplot(enQOIs[j],
                                 enQOIs[i],
                                 cmap=cmap,
                                 kernel='gau',
                                 n_levels=20,
                                 bw='silverman',
                                 linewidths=0.8)
                ax.grid()
                ax.locator_params(axis='both', tight=True, nbins=2)
                ax.tick_params(axis='both',
                               which='both',
                               bottom='off',
                               top='off',
                               labelbottom='off',
                               right='off',
                               left='off',
                               labelleft='off')
                ax.set_xlim(min(enQOIs[j, :]), max(enQOIs[j, :]))
                ax.set_ylim(min(enQOIs[i, :]), max(enQOIs[i, :]))
            elif j > i:
                cmap = sns.dark_palette("black", as_cmap=True)
                ax.scatter(enQOIs[j, sortedIndex],
                           enQOIs[i, sortedIndex],
                           s=25,
                           c=weight[sortedIndex, step],
                           cmap='Greys')
                ax.grid()
                ax.locator_params(axis='both', tight=True, nbins=2)
                ax.set_xlim(min(enQOIs[j, :]), max(enQOIs[j, :]))
                ax.set_ylim(min(enQOIs[i, :]), max(enQOIs[i, :]))
            if i == 3:
                ax.set_xlabel(labels[j], size=params['font.size'], labelpad=10)
                ax.tick_params(axis='both',
                               which='both',
                               bottom='on',
                               top='off',
                               labelbottom='on',
                               right='off',
                               left='off',
                               labelleft='off',
                               labelsize=params['xtick.labelsize'])
            if j == 0:
                ax.set_ylabel(labels[i], size=params['font.size'], labelpad=10)
                ax.tick_params(axis='both',
                               which='both',
                               bottom='off',
                               top='off',
                               labelbottom='off',
                               right='off',
                               left='on',
                               labelleft='on',
                               labelsize=params['xtick.labelsize'])
            if i == 3 and j == 0:
                ax.tick_params(axis='both',
                               which='both',
                               bottom='on',
                               top='off',
                               labelbottom='on',
                               right='off',
                               left='on',
                               labelleft='on',
                               labelsize=params['xtick.labelsize'])
            if i != 3 and j != 0:
                ax.tick_params(axis='both',
                               which='both',
                               bottom='off',
                               top='off',
                               labelbottom='off',
                               right='off',
                               left='off',
                               labelleft='off')

    plt.tight_layout()
    fig.subplots_adjust(left=0.165,
                        bottom=0.12,
                        right=0.98,
                        top=0.99,
                        hspace=0.1,
                        wspace=0.1)
    plt.savefig('macroMacroUQ_' + varsDir[-8:-1] + '_%i.pdf' % step, dpi=600)
    plt.show()
Ejemplo n.º 2
0
def microMacroPDF(name,
                  step,
                  pData,
                  varsDir,
                  weight,
                  mcFiles,
                  loadWeights=False):
    import seaborn as sns
    from resample import unWeighted_resample
    params = {
        'lines.linewidth': 1.5,
        'backend': 'ps',
        'axes.labelsize': 18,
        'font.size': 18,
        'legend.fontsize': 16,
        'xtick.labelsize': 16,
        'ytick.labelsize': 16,
        'text.usetex': True,
        'font.family': 'serif',
        'legend.edgecolor': 'k',
        'legend.fancybox': False
    }
    matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    matplotlib.rcParams.update(params)

    # read in the original sampled parameter set
    Xlabels = [
        r'$E_c$' + r' $(\mathrm{GPa})$', r'$\mu$',
        r'$k_m$' + r' $(\mu\mathrm{Nm)}$', r'$\eta_m$'
    ]
    Ylabels = [r'$p$' + r' $(\mathrm{MPa})$', r'$q/p$', r'$n$', r'$C^*$']
    if loadWeights:
        wPerPair = np.load(varsDir + '/wPerPair%i.npy' % step).item()
    else:
        wPerPair = {}

    # Monte Carlo sequence
    nSample, numOfObs = weight.shape
    enQOIs = np.zeros([4, nSample])
    for i in range(nSample):
        C, CN, K0, e_r11, e_r21, e_a1, n1, overlap, p1, q1 = np.genfromtxt(
            mcFiles[i]).transpose()
        enQOIs[0, i] = p1[step]
        enQOIs[1, i] = q1[step] / p1[step]
        enQOIs[2, i] = n1[step]
        enQOIs[3, i] = CN[step]
    # importance resampling
    ResampleIndices = unWeighted_resample(weight[:, step], nSample * 10)
    particles = np.copy(pData)
    particles[0, :] /= 1e9
    particles[2, :] /= 1e3
    particles = particles[:, ResampleIndices]
    enQOIs = enQOIs[:, ResampleIndices]
    # remove porosity as QOI if iterNO > 0
    if 'iterPF0' not in mcFiles[0]:
        enQOIs = np.vstack([enQOIs[:2, :], enQOIs[-1, :]])
        for i in [9, 10, 11, 12]:
            wPerPair[i] = wPerPair[i + 4]
        Ylabels = [r'$p$' + r' $(\mathrm{MPa})$', r'$q/p$', r'$C^*$']

    # plot figures
    figNO = 0
    fig = plt.figure('microMacroUQ_iterPF' + varsDir[-1] + '_%i' % step,
                     figsize=(12 / 2.54, 12 / 2.54))
    sns.set(style="ticks", rc=matplotlib.rcParams)
    for i in range(enQOIs.shape[0]):
        for j in range(particles.shape[0]):
            figNO += 1
            # plot histograms at the initial and final steps
            ax = fig.add_subplot(enQOIs.shape[0], 4, figNO)
            cmap = sns.dark_palette("black", as_cmap=True)
            #~ ax = sns.kdeplot(,,cmap=cmap,kernel='gau',cut=3,n_levels=20,bw='silverman',linewidths=0.8); ax.grid()
            if loadWeights:
                minScore, maxScore, p0, w0 = wPerPair[figNO]
            else:
                data = np.array([particles[j], enQOIs[i]])
                pMin = [min(particles[j]), min(enQOIs[i])]
                pMax = [max(particles[j]), max(enQOIs[i])]
                minScore, maxScore, p0, w0 = getLogWeightFromGMM(
                    data.T, pMin, pMax, 1e-2)
                wPerPair[figNO] = (minScore, maxScore, p0, w0)
            X, Y = p0
            plt.contour(X,
                        Y,
                        w0,
                        cmap=cmap,
                        levels=np.linspace(minScore - abs(minScore) * 0.1,
                                           maxScore, 10),
                        linewidths=0.7)
            plt.grid()
            ax.locator_params(axis='both', nbins=2)
            ax.tick_params(axis='both',
                           which='both',
                           bottom='off',
                           top='off',
                           labelbottom='off',
                           right='off',
                           left='off',
                           labelleft='off')
            if i == enQOIs.shape[0] - 1:
                ax.set_xlabel(Xlabels[j],
                              size=params['font.size'],
                              labelpad=10)
                ax.tick_params(axis='both',
                               which='both',
                               bottom='on',
                               top='off',
                               labelbottom='on',
                               right='off',
                               left='off',
                               labelleft='off',
                               labelsize=params['xtick.labelsize'])
            if j == 0:
                ax.set_ylabel(Ylabels[i],
                              size=params['font.size'],
                              labelpad=10)
                ax.tick_params(axis='both',
                               which='both',
                               bottom='off',
                               top='off',
                               labelbottom='off',
                               right='off',
                               left='on',
                               labelleft='on',
                               labelsize=params['xtick.labelsize'])
            if i == enQOIs.shape[0] - 1 and j == 0:
                ax.tick_params(axis='both',
                               which='both',
                               bottom='on',
                               top='off',
                               labelbottom='on',
                               right='off',
                               left='on',
                               labelleft='on',
                               labelsize=params['xtick.labelsize'])
            if i != enQOIs.shape[0] - 1 and j != 0:
                ax.tick_params(axis='both',
                               which='both',
                               bottom='off',
                               top='off',
                               labelbottom='off',
                               right='off',
                               left='off',
                               labelleft='off')
            xMin, xMax = ax.get_xlim()
            yMin, yMax = ax.get_ylim()
            dx = (xMax - xMin) / 4
            dy = (yMax - yMin) / 4
            ax.set_xticks(
                np.round([xMin + dx, xMax - dx], int(np.ceil(-np.log10(dx)))))
            ax.set_yticks(
                np.round([yMin + dy, yMax - dy], int(np.ceil(-np.log10(dy)))))
    if not loadWeights: np.save(varsDir + '/wPerPair%i.npy' % step, wPerPair)
    plt.tight_layout()
    fig.subplots_adjust(left=0.21,
                        bottom=0.16,
                        right=0.99,
                        top=0.99,
                        hspace=0.,
                        wspace=0.)
    plt.savefig('microMacroUQ_iterPF' + varsDir[-1] + '_%i.pdf' % step,
                dpi=600)
    #~ plt.show()
    return wPerPair