def ex_01(fns=[
    'powder_collection_25JUL12/25JUL12_0002Data1Phi-90.txt',
    'powder_collection_25JUL12/25JUL12_0002Data2Phi0.txt',
    'powder_collection_25JUL12/25JUL12_0002Data3Phi45.txt',
    'powder_collection_25JUL12/25JUL12_0002Data4Phi135.txt'
]):
    from MP.lib.mpl_lib import wide_fig as wf
    from MP.lib.mpl_lib import fancy_legend
    from MP.lib.axes_label import __deco__ as deco

    fig = wf(nh=1, nw=1, uw=4, left=0.2)
    ax = fig.axes[0]
    ehkl_dat = []
    for i in xrange(len(fns)):
        sign_sin2psi, ehkl, dspacing, psi = read(fns[i], iopt=0, isort=True)
        ax.plot(sign_sin2psi,
                ehkl,
                '-x',
                label=fns[i].split('Phi')[1].split('.')[0])
        ehkl_dat.append(ehkl)

    print 'mean:', np.array(ehkl_dat).mean()
    print 'std:', np.array(ehkl_dat).std()
    deco(iopt=0, ft=15, ax=ax, ipsi_opt=1)
    fancy_legend(ax=ax, size=10, ncol=2)
Exemple #2
0
def influence_of_cnts_stats(
        ss=3,bounds=[0.,0.3257],
        nbins=13, sigmas=[1e-5, 2e-5, 5e-5, 1e-4],
        nsample=5,intp_opt=0,iplot=False):
    from MP.lib import mpl_lib,axes_label
    import matplotlib.pyplot as plt

    if iplot==False:
        plt.ioff()

    fancy_legend = mpl_lib.fancy_legend
    wide_fig     = mpl_lib.wide_fig
    deco         = axes_label.__deco__
    fig = wide_fig(nw=2,nh=1);
    ax1=fig.axes[0]; ax2=fig.axes[1]

    M = []
    for i in range(len(sigmas)):
        Y = []
        for j in range(nsample):
            x, y = influence_of_nbin_scatter(
                ss=ss,bounds=bounds,
                nbins=[nbins],
                iscatter=True,nsample=1,
                iwgt=True,sigma=sigmas[i],
                intp_opt=intp_opt,
                iplot=False)
            Y.append(y)
        Y = np.array(Y).T
        M = []; S=[]
        for k in range(len(x)):
            M.append(Y[k].mean())
            S.append(Y[k].std())
        ax1.plot(x,M,label='%6.0e'%sigmas[i])
        ax2.errorbar(x,M,yerr=S,label='%6.0e'%sigmas[i])

    if type(ss).__name__=='int':
        ax1.plot(x[::ss],np.zeros((len(x[::ss]),)),'o',mec='r',mfc='None',ms=8)
        ax2.plot(x[::ss],np.zeros((len(x[::ss]),)),'o',mec='r',mfc='None',ms=8)
    elif type(ss).__name__=='list':
        ax1.plot(x[ss],np.zeros((len(x[ss]),)),'o',mec='r',mfc='None',ms=8)
        ax2.plot(x[ss],np.zeros((len(x[ss]),)),'o',mec='r',mfc='None',ms=8)

    ax1.set_ylim(0.,); ax1.set_xlim(0.,ax1.get_xlim()[1]*1.05)
    ax1.set_title(r'Error in $\varepsilon^\mathrm{hkl}$')
    deco(iopt=8,ft=15,ax=ax1)
    fancy_legend(ax=ax1, size=7,ncol=2)
    ax2.set_ylim(0.,); ax2.set_xlim(0.,ax2.get_xlim()[1]*1.05)
    ax2.set_title(r'Error in $\varepsilon^\mathrm{hkl}$')
    deco(iopt=8,ft=15,ax=ax2)
    fancy_legend(ax=ax2, size=7,ncol=2)

    fig.savefig('ee.pdf')
    if iplot==False:
        plt.close('all')
        plt.ion()
    return x, M, S
Exemple #3
0
def influence_of_nbin(
        ss=3,bounds = [0,0.5],
        nbins = [11, 19, 25, 51],
        iscatter=False,
        sigma=1e-5,
        iwgt=False,
        intp_opt=0,
        iplot=False,):

    """
    Influence of psi bin size

    Arguments
    =========
    ss = 3
    bounds = [0.0, 0.5]
    nbins = [11, 19, 25, 51]
    iscatter = False
    iwgt     = False
    intp_opt = 0   (Interpolation option)
    iplot    = False
    """
    if iplot:
        from MP.lib import mpl_lib,axes_label
        import matplotlib.pyplot as plt
        fancy_legend = mpl_lib.fancy_legend
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig = wide_fig(nw=1,nh=1);ax=fig.axes[0]

    Y = []
    for i in range(len(nbins)):
        nb = nbins[i]
        fw, e = influence_of_intp(
            ss=ss, bounds=bounds,
            psi_nbin = nb,iplot=False,
            iscatter=iscatter,sigma=sigma,
            iwgt=iwgt,
            intp_opt=intp_opt,
            )
        x = fw.epsilon_vm[::]
        y = e[::]
        if iplot: ax.plot(x,y,label=nb)
        Y.append(y)

    if type(ss).__name__=='int':    dum=ss
    elif type(ss).__name__=='list': dum =len(ss)

    if iplot:
        fancy_legend(ax=ax,size=10)
        deco(iopt=8,ft=15,ax=ax)
        fig.savefig('ss%i_err.pdf'%dum)
        plt.close('all')

    ## Y [nbins, nsteps]
    return x, Y
Exemple #4
0
def influence_of_nbin(
        ss=3,bounds = [0,0.5],
        nbins = [11, 19, 25, 51],
        iscatter=False,
        sigma=1e-5,
        iwgt=False,
        intp_opt=0,
        iplot=False,):

    """
    Influence of psi bin size

    Arguments
    =========
    ss = 3
    bounds = [0.0, 0.5]
    nbins = [11, 19, 25, 51]
    iscatter = False
    iwgt     = False
    intp_opt = 0   (Interpolation option)
    iplot    = False
    """
    if iplot:
        from MP.lib import mpl_lib,axes_label
        import matplotlib.pyplot as plt
        fancy_legend = mpl_lib.fancy_legend
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig = wide_fig(nw=1,nh=1);ax=fig.axes[0]

    Y = []
    for i in xrange(len(nbins)):
        nb = nbins[i]
        fw, e = influence_of_intp(
            ss=ss, bounds=bounds,
            psi_nbin = nb,iplot=False,
            iscatter=iscatter,sigma=sigma,
            iwgt=iwgt,
            intp_opt=intp_opt,
            )
        x = fw.epsilon_vm[::]
        y = e[::]
        if iplot: ax.plot(x,y,label=nb)
        Y.append(y)

    if type(ss).__name__=='int':    dum=ss
    elif type(ss).__name__=='list': dum =len(ss)

    if iplot:
        fancy_legend(ax=ax,size=10)
        deco(iopt=8,ft=15,ax=ax)
        fig.savefig('ss%i_err.pdf'%dum)
        plt.close('all')

    ## Y [nbins, nsteps]
    return x, Y
def ex_01(fns=[
        'powder_collection_25JUL12/25JUL12_0002Data1Phi-90.txt',
        'powder_collection_25JUL12/25JUL12_0002Data2Phi0.txt',
        'powder_collection_25JUL12/25JUL12_0002Data3Phi45.txt',
        'powder_collection_25JUL12/25JUL12_0002Data4Phi135.txt']):
    from MP.lib.mpl_lib import wide_fig as wf
    from MP.lib.mpl_lib import fancy_legend
    from MP.lib.axes_label import __deco__ as deco

    fig = wf(nh=1,nw=1,uw=4,left=0.2); ax=fig.axes[0]
    ehkl_dat = []
    for i in range(len(fns)):
        sign_sin2psi,ehkl,dspacing,psi = read(fns[i],iopt=0,isort=True)
        ax.plot(sign_sin2psi,ehkl,'-x',label=fns[i].split('Phi')[1].split('.')[0])
        ehkl_dat.append(ehkl)


    print 'mean:', np.array(ehkl_dat).mean()
    print 'std:', np.array(ehkl_dat).std()
    deco(iopt=0,ft=15,ax=ax,ipsi_opt=1)
    fancy_legend(ax=ax,size=10,ncol=2)
Exemple #6
0
def error_est(
        path='BB',psi_nbin=21,
        sin2psimx=0.5,
        hkls=['200','220','211','310'],
        iplot_rs=False):
    """
    """
    from MP.lib.axes_label import __deco__ as deco
    fig = wf(nw=1,nh=1,left=0.2,uw=3.5,
             w0=0,w1=0.3,right=0,iarange=True)
    ax=fig.axes[0]
    for i in range(len(hkls)):
        err = main_plot_flow_all(
            hkl=hkls[i],sin2psimx=sin2psimx,
            psi_nbin=psi_nbin,pmargin=None,
            iplot_rs=iplot_rs,path=path)
        eps_vm, e = err
        ax.plot(eps_vm,e,label=hkls[i])
    deco(iopt=8,ft=15,ax=ax)
    ax.legend(loc='best',fontsize=9)
    fig.savefig('error_dsa_%s.pdf'%path)
    return fig
Exemple #7
0
def error_est(
        path='BB',psi_nbin=21,
        sin2psimx=0.5,
        hkls=['200','220','211','310'],
        iplot_rs=False):
    """
    """
    from MP.lib.axes_label import __deco__ as deco
    fig = wf(nw=1,nh=1,left=0.2,uw=3.5,
             w0=0,w1=0.3,right=0,iarange=True)
    ax=fig.axes[0]
    for i in xrange(len(hkls)):
        err = main_plot_flow_all(
            hkl=hkls[i],sin2psimx=sin2psimx,
            psi_nbin=psi_nbin,pmargin=None,
            iplot_rs=iplot_rs,path=path)
        eps_vm, e = err
        ax.plot(eps_vm,e,label=hkls[i])
    deco(iopt=8,ft=15,ax=ax)
    ax.legend(loc='best',fontsize=9)
    fig.savefig('error_dsa_%s.pdf'%path)
    return fig
Exemple #8
0
def influence_of_cnts_stats(
        ## characteristics of an ensemble for stress data
        sigmas=[1e-5, 2e-5, 5e-5, 1e-4],
        bounds=[0.,0.5],
        ss=3,
        nbins=10,
        iwgt=False,
        nsample=4,
        intp_opt=0,
        iplot=False,

        ## diffraction condition
        bragg=78.2,    ## Fe {211} using Cr K-alpha
        ird=0.182,     ## Intensity of random distribution
                       ## for {211} using window of 10 degree.
        DEC_freq_sym=True,
        NCPU=0):
    """
    Influence of counting statistics uncertainty

    With fixing other variables, investigates the
    propagation of counting stat error on to the final
    diffraction stress by examining a number of
    statistical ensembles (nsample) characterized
    by given arguments

    Arguments
    =========
    sigmas      : Pure CSE
    bounds      : Bounds of tilting range
    ss          : Sampling frequency in DECs
    nbins       : How many tilting angles in diffraction
    iwgt        : Do we weight (E-e) by peak intensity?
    nsample     : The number of ensembles.
    intp_opt    : DEC interpolation method
    iplot       : Flag for plotting
    bragg       : Bragg's angle
    ird         : Intensity of random distribution
    DEC_freq_sym: Plotting option for where DECs are sampled.
    NCPU        : The number of CPU cores allowed to run
    """
    from RS.rs_ex import ex_consistency as func

    if iplot:
        import matplotlib.pyplot as plt
        from MP.lib import mpl_lib,axes_label

        fancy_legend = mpl_lib.fancy_legend
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig          = wide_fig(nw=2,nh=1)
        ax1,ax2      = fig.axes[0], fig.axes[1]

    print '\n\n****************'
    print 'test run started'
    print '****************\n\n'
    myrs,flow1,flow2 =func(
        sin2psimx=bounds[1],
        iscatter=True,
        sigma=sigmas[0],
        psi_nbin=nbins,
        ig_sub=True,
        iplot=False, # iplot=True
        dec_inv_frq=ss,
        dec_interp=intp_opt,
    )

    print '\n\n**************'
    print 'test completed'
    print '**************\n\n'
    # return ## debugging

    Y_all = np.zeros((len(sigmas), nsample, flow1.nstp))
    M = []
    ls=['-+','-s','-o','-d','-t']
    import multiprocessing
    from multiprocessing import Pool
    if NCPU==0: NCPU = multiprocessing.cpu_count()
    print 'NCPU: %i'%NCPU
    pool = Pool(processes = NCPU)

    ## function is now wrap_func
    results = []
    for i in range(len(sigmas)):
        results.append([])
        for j in range(nsample):
            results[i].append(
                pool.apply_async(
                    wrap_func,
                    args=(
                        sigmas[i],
                        ss,
                        intp_opt,
                        bounds,
                        nbins
                        )
                    ,))
    ## close/join
    pool.close()
    pool.join()
    ## terminate
    pool.terminate()

    ## below is to post-process the results
    for i in range(len(sigmas)):
        for j in range(nsample):
            x,y = results[i][j].get()
            Y_all[i][j][:] = y[::]

    M = np.zeros((len(sigmas),len(x)))
    S = np.zeros((len(sigmas),len(x)))
    for i in range(len(sigmas)):
        y = Y_all[i][:][:]
        y = y.T[::] ## len(x), nsample
        for k in range(len(x)):
            M[i][k] = y[k].mean()
            S[i][k] = y[k].std()

    nbins = 10
    H  = np.zeros((len(sigmas), len(x), nbins))
    BE = np.zeros((len(sigmas), len(x), nbins+1))
    for i in range(len(sigmas)):
        y = Y_all[i][:][:]
        y = y.T[::] ## len(x), nsample
        for k in range(len(x)):
            hist,bin_edges = np.histogram(y[k],bins=10)
            H[i,k,:] = hist[::]
            BE[i,k,:] = bin_edges[::]

    if iplot:
        for i in range(len(sigmas)):
            ax1.plot(x,M[i],ls[i],mfc='None',color='k',label='%6.0e'%sigmas[i])
            ax2.errorbar(x,M[i],yerr=S[i],color='k',ls=ls[i])
        if type(ss).__name__=='int' and DEC_freq_sym:
            ax1.plot(x[::ss],np.zeros((len(x[::ss]),)),'o',mec='r',mfc='None',ms=8)
            ax2.plot(x[::ss],np.zeros((len(x[::ss]),)),'o',mec='r',mfc='None',ms=8)
        elif type(ss).__name__=='list' and DEC_freq_sym:
            ax1.plot(x[ss],np.zeros((len(x[ss]),)),'o',mec='r',mfc='None',ms=8)
            ax2.plot(x[ss],np.zeros((len(x[ss]),)),'o',mec='r',mfc='None',ms=8)
        ax1.set_ylim(0.,); ax1.set_xlim(0.,ax1.get_xlim()[1]*1.05)
        deco(iopt=9,ft=15,ax=ax1)
        fancy_legend(ax=ax1, size=7,ncol=2,nscat=1)
        ax2.set_ylim(0.,); ax2.set_xlim(0.,ax2.get_xlim()[1]*1.05)
        deco(iopt=9,ft=15,ax=ax2)
        fig.savefig('ee.pdf')
    return x, M, S, H, BE
Exemple #9
0
def influence_of_nbin_scatter(
    ##
    sigma=5e-5,

    ss=1,
    bounds=[0.0, 0.5],
    nbins=[10,10], ## main arg
    iscatter=True,
    nsample=1,
    iwgt=False,
    intp_opt=0,
    iplot=False,):

    """
    Repeat influence_of_nbin examination
    to verify the error in stress analysis
    pertaining to that in eps(hkl,phi,psi)

    Arguments
    =========
    sigma    = 5e-5
    ss       = 1
    bounds   = [0,0.5]
    nbins    = [10,10]
    iscatter = True
    nsample  = 1
    iwgt     = False
    intp_opt = 0
    iplot    = False
    """
    if iplot:
        from MP.lib import mpl_lib,axes_label
        import matplotlib.pyplot as plt
        fancy_legend = mpl_lib.fancy_legend
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig          = wide_fig(nw=2,nh=1);
        ax           = fig.axes[0]
        ax1          = fig.axes[1]

    for i in range(len(nbins)):
        nbin = nbins[i]
        for j in range(nsample):
            x, y = influence_of_nbin(
                ss=ss,bounds=bounds,
                nbins=[nbin], iscatter=iscatter,
                sigma=sigma,
                iwgt=iwgt,
                intp_opt=intp_opt,)

            if i==0 and j==0:
                ## Getting Y array shaped.
                Y = np.zeros((len(nbins),len(x),nsample))

            Y[i,:,j] = y[0][:]

    nbin, nstp, nsamp = Y.shape

    for i in range(nbin):
        e = []; s = []
        for j in range(nstp):
            mean = Y[i,j,:].mean()
            std  = Y[i,j,:].std()
            e.append(mean)
            s.append(std)
        if iplot:
            ax1.plot(x,e,'-o',label=nbins[i])
            ax.errorbar(x,e,yerr=std,fmt='x',label=nbins[i])

    if iplot:
        if type(ss).__name__=='int':
            ax1.plot(x[::ss],np.zeros((len(x[::ss]),)),'r|',ms=12)
            ax.plot(x[::ss],np.zeros((len(x[::ss]),)),'r|',ms=8)
        elif type(ss).__name__=='list':
            ax1.plot(x[ss],np.zeros((len(x[ss]),)),'r|',ms=12)
            ax.plot(x[ss],np.zeros((len(x[ss]),)),'r|',ms=8)

        ax.set_ylim(0.,); ax.set_xlim(0.,ax.get_xlim()[1]*1.05)
        ax1.set_ylim(0.,); ax1.set_xlim(0.,ax1.get_xlim()[1]*1.05)
        fancy_legend(ax=ax, size=7,ncol=2)
        fancy_legend(ax=ax1,size=7,ncol=2)
        deco(iopt=8,ft=15,ax=ax);  deco(iopt=8,ft=15,ax=ax1)

        if type(ss).__name__=='int':    dum=ss
        elif type(ss).__name__=='list': dum =len(ss)
        fig.savefig('ss_%i_err_scatter_nsamp_%i.pdf'%(dum,nsample))
        plt.close('all')
    return x, e
Exemple #10
0
def influence_of_intp(ss=2,bounds=[0,0.5],
                      psi_nbin=13,iplot=False,
                      hkl=None,
                      iscatter=False,iwgt=False,
                      sigma=5e-5,
                      intp_opt=0):
    """
    Parametric study to demonstrate the uncertainty
    for a fixed intp_opt

    Arguments
    =========
    ss       = 2 (step size)
    bounds   = sin2psi bounds
    psi_nbin = Number of psi data points in use
    iplot    = False
    hkl      = None
    iscatter = False
    iwgt     = False
    sigma    = 5e-5
    intp_opt = 0
    """
    from rs import filter_psi2
    from rs_ex import ex_consistency as main
    from MP.mat.mech import find_err

    if iplot:
        from MP.lib import mpl_lib,axes_label
        import matplotlib.pyplot as plt
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig          = wide_fig(nw=3,nh=1)
        axs          = fig.axes

    ## Use the reduced set over the consistency check
    sf, ig = use_intp_sfig(
        ss=ss,iopt=intp_opt,iplot=False,
        iwgt=False)

    sf_ext = sf.sf.swapaxes(1,-1).swapaxes(-2,-1)[::]*1e6
    ig_ext = ig.ig[::]

    ##
    # Filtering against sin2psi
    sf_ext = filter_psi2(
        obj=sf_ext,sin2psi=sf.sin2psi,
        bounds=bounds)
    ig_ext = filter_psi2(
        obj=ig_ext,sin2psi=sf.sin2psi,
        bounds=bounds)

    ### Reduce binning
    ## consistency check
    rst = main(sin2psimx=bounds[1],
               psi_nbin=psi_nbin,
               sf_ext=sf_ext,ig_ext=ig_ext,
               iplot=iplot,hkl=hkl,
               iscatter=iscatter,
               sigma=sigma,iwgt=iwgt,
               vf_ext=None)

    fw, fd = rst[1], rst[2]

    if iplot:
        axs[0].plot(fw.epsilon_vm,fw.sigma_vm,
                    'b-x',label='Weight Avg.')
        axs[0].plot(fd.epsilon_vm,fd.sigma_vm,
                    'k+',label='Diff Stress')

    if type(ss).__name__=='int':
        x = fd.epsilon_vm[::ss];
        y = fd.sigma_vm[::ss]
    elif type(ss).__name__=='list':
        x = fd.epsilon_vm[ss];
        y = fd.sigma_vm[ss]

    if iplot:
        label='SF/IG acqusition'
        axs[0].plot(x,y,'o',mec='r',mfc='None',
                    alpha=0.8,label=label)
        axs[1].plot(fw.sigma[0,0],fw.sigma[1,1],'b-x')
        axs[1].plot(fd.sigma[0,0],fd.sigma[1,1],'k+')

    npoints = len(fw.sigma[0,0])
    wgtx, wgty = fw.sigma[0,0], fw.sigma[1,1]
    dsax, dsay = fd.sigma[0,0], fd.sigma[1,1]

    if iplot:
        for i in range(npoints):
            axs[1].plot([wgtx[i],dsax[i]],
                        [wgty[i],dsay[i]],
                        'k-',alpha=0.2)

    e = find_err(fw,fd)
    if iplot: axs[2].plot(fw.epsilon_vm, e, 'x')

    if type(ss).__name__=='int' and iplot:
        axs[2].plot(fw.epsilon_vm[::ss],e[::ss],
                    'o',mec='r',mfc='None',label=label)
    elif type(ss).__name__=='list' and iplot:
        axs[2].plot(fw.epsilon_vm[ss],e[ss],
                    'o',mec='r',mfc='None',label=label)

    if type(ss).__name__=='int':    dum=ss
    elif type(ss).__name__=='list': dum =len(ss)

    if iplot:
        axes_label.__eqv__(axs[0],ft=10)
        axs[1].set_aspect('equal')
        axs[1].set_xlabel(r'$\bar{\Sigma}_{11}$',dict(fontsize=15))
        axs[1].set_ylabel(r'$\bar{\Sigma}_{22}$',dict(fontsize=15))
        axs[1].set_ylim(-100,700); axs[1].set_xlim(-100,700)

        axs[0].legend(loc='best',fontsize=10).get_frame().set_alpha(0.5)
        deco(iopt=8,ft=15,ax=axs[2])

        fig.savefig('flow_dd_bin%i_ss%i.pdf'%(psi_nbin,dum))
        plt.close(fig)

    return fw, e
Exemple #11
0
def plot_sf_psis(
        sff_fn='temp.sff',
        psi_ref=[45.0, 42.4, 39.8, 37.1, 34.3, 31.5,
                 28.5, 25.2, 21.7, 17.5, 12.3, 0]):
    import numpy as np
    import matplotlib.pyplot as plt
    from pepshkl import reader4
    from RS import sff_converter
    from rs_exp import read_IGSF
    from MP.lib import mpl_lib, axes_label
    from RS.rs import find_nearest

    deco = axes_label.__deco__
    wf = mpl_lib.wide_fig

    sff_converter.main(fn=sff_fn,difile=None,itab=True,
                       ieps0=4,  fn_str='STR_STR.OUT')
    SF, IG = read_IGSF(fn=sff_fn,fn_str='STR_STR.OUT')

    tdat,_psis_,_vdat_,_ngrd_ = reader4(
        fn='int_els_ph1.out',ndetector=2,iopt=1)

    ## sorting
    import MP.ssort as sort
    shsort = sort.shellSort
    ss     = sort.ind_swap

    ## sort psi and find ind
    psis, ind = shsort(_psis_)
    nstp, nphi, npsis = np.shape(_vdat_)
    vdat = np.zeros((nstp,nphi,npsis))
    ngrd = np.zeros((nstp,nphi,npsis))

    for istp in range(nstp):
        for iphi in range(nphi):
            dum_v = _vdat_[istp,iphi,:][::]
            vdat[istp,iphi,:] = ss(dum_v[::],ind)[::]

            dum_n = _ngrd_[istp,iphi,:][::]
            ngrd[istp,iphi,:] = ss(dum_n[::],ind)[::]

    ## Find only psi_ref values
    ## sin2psi_ref = np.sin(psi_ref*np.pi/180.)**2
    inds = []
    for i in range(len(psi_ref)):
        inds.append(find_nearest(SF.psi, psi_ref[i]))

    #SF.mask_vol() ## shake off all zero values

    fig=wf(nh=nphi,nw=len(psi_ref),iarange=True)
    figv=wf(nh=nphi,nw=len(psi_ref),iarange=True)
    fe0=wf(nh=nphi,nw=len(psi_ref),iarange=True)
    for iphi in range(nphi):
        for ipsi in range(len(psi_ref)):
            #ax = fig.axes[iphi+nphi*ipsi]
            ax = fig.axes[ipsi+len(psi_ref)*iphi]
            axt = figv.axes[ipsi+len(psi_ref)*iphi]
            aig = fe0.axes[ipsi+len(psi_ref)*iphi]
            if iphi==0:
                ax.set_title(
                    r'$\psi= %3.1f^\circ{}$'%\
                    SF.psi[inds[ipsi]]
                )
                axt.set_title(
                    r'$\psi= %3.1f^\circ{}$'%\
                    SF.psi[inds[ipsi]]
                )
                aig.set_title(
                    r'$\psi= %3.1f^\circ{}$'%\
                    SF.psi[inds[ipsi]]
                )
            if ipsi==0:
                ax.text(0,0,r'$\phi=%3.1f^\circ{}$'%\
                        SF.phi[iphi],transform=ax.transAxes)
                axt.text(0,0,r'$\phi=%3.1f^\circ{}$'%\
                         SF.phi[iphi],transform=axt.transAxes)
                aig.text(0,0,r'$\phi=%3.1f^\circ{}$'%\
                         SF.phi[iphi],transform=aig.transAxes)

                deco(ax,iopt=6)
                deco(axt,iopt=7)

            x = SF.flow.epsilon_vm
            y = SF.sf[:,iphi,inds[ipsi],0] # f11
            ig = IG.ig[:,iphi,inds[ipsi]]
            v = vdat[:,iphi,inds[ipsi]]
            ax.plot(x,y*1e12,'b-o')
            aig.plot(x,ig,'b-o')
            axt.plot(x,v,'r-x')

            axt.set_ylim(0.,0.10)
            ax.set_xlim(0.,1.0)
            aig.set_xlim(0.,1.0)
            aig.set_ylim(-0.002,0.002)
Exemple #12
0
def influence_of_cnts_stats(
        ## characteristics of an ensemble for
        ## stress data
        sigmas=[1e-5, 2e-5, 5e-5, 1e-4],
        bounds=[0.,0.5],
        ss=3,
        nbins=10,
        iwgt=False,
        nsample=4,
        intp_opt=0,
        iplot=False,

        ## diffraction condition
        bragg=78.2*np.pi/180.,     ## Fe {211} using Cr K-alpha
        #bragg=162.2*np.pi/180.,   ## Fe {310} using Cobalt Radiation.
        ird=0.182,     ## Intensity of random distribution
                       ## for {211} using window of 10 degree.
        ## sample a portion of data.
        nfrq=None,
        DEC_freq_sym=True,
        NCPU=0):
    """
    Propagate errors due to
     1) counting statistics error (CSE)
     2) incomplete DECs (by utilizing only
          a portion of model DECs)
     3) Infinite number of tilting angles in use
     4) Incomplete range of psi angle ranges in use
     5) Geometric distortion (Bragg angle / psi)
     6) Peak intensity: I(phi,psi) / Ird

    With fixing other variables, investigates the
    propagation of counting stat error to final
    diffraction stress by examining a number of
    statistical ensembles <nsample> characterized
    by given arguments

    ## diffraction condition
    #bragg=78.2,  ## Fe {211} using Cr K-alpha
    #bragg=78.2,  ## Fe {310} using Cobalt
    #ird=0.182,     ## Intensity of random distribution

    Arguments
    =========
    sigmas      : Counting Stat Error
    bounds      : Bounds of tilting range
                  (low psi to high psi)
    ss          : Sampling frequency in DECs
    nbins       : How many tilting angles in
                  diffraction
    iwgt        : Do we weight (E-e) by peak intensity?
    nsample     : The number of ensembles
    intp_opt    : DEC interpolation method
    iplot       : Flag for plotting
    bragg       : Bragg's angle
    ird         : Intensity of random distribution
    nfrq        : if not (None) but an integer,
              use it as denominator to 'continue' to skip

              --------------------------
              if istp % nfrq != 0 :
                  continue ! skip
              else:
                  run stress analysis
              --------------------------

    DEC_freq_sym: Plotting option for where DECs are sampled.
    NCPU        : The number of CPU cores allowed to run
    """
    from RS.rs_ex import ex_consistency as func

    if iplot:
        import matplotlib.pyplot as plt
        from MP.lib import mpl_lib,axes_label

        fancy_legend = mpl_lib.fancy_legend
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig          = wide_fig(nw=2,nh=1)
        ax1,ax2      = fig.axes[0], fig.axes[1]

    print '\n\n****************'
    print 'test run started'
    print '****************\n\n'
    myrs,flow_raw,flow2 =func(
        sin2psimx=bounds[1],
        iscatter=False,
        sigma=sigmas[0],
        psi_nbin=nbins,
        ig_sub=True,
        iplot=False, # iplot=True
        dec_inv_frq=ss,
        dec_interp=intp_opt,
        nfrq=nfrq)
    print '\n\n**************'
    print 'test completed'
    print '**************\n\n'

    Y_all = np.zeros((len(sigmas), nsample, flow2.nstp))
    M = []
    ls=['-+','-s','-o','-d','-t']
    import multiprocessing
    from multiprocessing import Pool
    if NCPU==0: NCPU = multiprocessing.cpu_count()
    print 'NCPU: %i'%NCPU
    pool = Pool(processes = NCPU)

    ## function is now wrap_func
    results = []
    for i in xrange(len(sigmas)):
        results.append([])
        for j in xrange(nsample):
            results[i].append(
                pool.apply_async(
                    wrap_func,
                    args=(
                        sigmas[i],
                        ss,
                        intp_opt,
                        bounds,
                        nbins,
                        bragg,
                        ird,nfrq),))

    ## close/join
    pool.close(); pool.join()
    ## terminate
    pool.terminate()

    ## below is to post-process the results
    for i in xrange(len(sigmas)):
        for j in xrange(nsample):
            x,y = results[i][j].get()
            Y_all[i][j][:] = y[::]

    M = np.zeros((len(sigmas),len(x)))
    S = np.zeros((len(sigmas),len(x)))
    for i in xrange(len(sigmas)):
        y = Y_all[i][:][:]
        y = y.T[::] ## len(x), nsample
        for k in xrange(len(x)):
            M[i][k] = y[k].mean()
            S[i][k] = y[k].std()

    nbins = 10
    H  = np.zeros((len(sigmas), len(x), nbins))
    BE = np.zeros((len(sigmas), len(x), nbins+1))
    for i in xrange(len(sigmas)):
        y = Y_all[i][:][:]
        y = y.T[::] ## len(x), nsample
        for k in xrange(len(x)):
            hist,bin_edges = np.histogram(y[k],bins=10)
            H[i,k,:] = hist[::]
            BE[i,k,:] = bin_edges[::]

    if iplot:
        for i in xrange(len(sigmas)):
            ax1.plot(x,M[i],ls[i],mfc='None',color='k',label='%6.0e'%sigmas[i])
            ax2.errorbar(x,M[i],yerr=S[i],color='k',ls=ls[i])
        if type(ss).__name__=='int' and DEC_freq_sym:
            ax1.plot(x[::ss],np.zeros((len(x[::ss]),)),'o',mec='r',mfc='None',ms=8)
            ax2.plot(x[::ss],np.zeros((len(x[::ss]),)),'o',mec='r',mfc='None',ms=8)
        elif type(ss).__name__=='list' and DEC_freq_sym:
            ax1.plot(x[ss],np.zeros((len(x[ss]),)),'o',mec='r',mfc='None',ms=8)
            ax2.plot(x[ss],np.zeros((len(x[ss]),)),'o',mec='r',mfc='None',ms=8)
        # ax1.set_ylim(0.,); ax1.set_xlim(0.,ax1.get_xlim()[1]*1.05)
        deco(iopt=9,ft=15,ax=ax1)
        fancy_legend(ax=ax1, size=7,ncol=2,nscat=1)
        ax2.set_ylim(0.,); ax2.set_xlim(0.,ax2.get_xlim()[1]*1.05)
        deco(iopt=9,ft=15,ax=ax2)
        fig.savefig('ee.pdf')
    return x, M, S, H, BE, flow_raw
Exemple #13
0
def influence_of_nbin_scatter(
    ##
    sigma=5e-5,

    ss=1,
    bounds=[0.0, 0.5],
    nbins=[10,10], ## main arg
    iscatter=True,
    nsample=1,
    iwgt=False,
    intp_opt=0,
    iplot=False,):

    """
    Repeat influence_of_nbin examination
    to verify the error in stress analysis
    pertaining to that in eps(hkl,phi,psi)

    Arguments
    =========
    sigma    = 5e-5
    ss       = 1
    bounds   = [0,0.5]
    nbins    = [10,10]
    iscatter = True
    nsample  = 1
    iwgt     = False
    intp_opt = 0
    iplot    = False
    """
    if iplot:
        from MP.lib import mpl_lib,axes_label
        import matplotlib.pyplot as plt
        fancy_legend = mpl_lib.fancy_legend
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig          = wide_fig(nw=2,nh=1);
        ax           = fig.axes[0]
        ax1          = fig.axes[1]

    for i in xrange(len(nbins)):
        nbin = nbins[i]
        for j in xrange(nsample):
            x, y = influence_of_nbin(
                ss=ss,bounds=bounds,
                nbins=[nbin], iscatter=iscatter,
                sigma=sigma,
                iwgt=iwgt,
                intp_opt=intp_opt,)

            if i==0 and j==0:
                ## Getting Y array shaped.
                Y = np.zeros((len(nbins),len(x),nsample))

            Y[i,:,j] = y[0][:]

    nbin, nstp, nsamp = Y.shape

    for i in xrange(nbin):
        e = []; s = []
        for j in xrange(nstp):
            mean = Y[i,j,:].mean()
            std  = Y[i,j,:].std()
            e.append(mean)
            s.append(std)
        if iplot:
            ax1.plot(x,e,'-o',label=nbins[i])
            ax.errorbar(x,e,yerr=std,fmt='x',label=nbins[i])

    if iplot:
        if type(ss).__name__=='int':
            ax1.plot(x[::ss],np.zeros((len(x[::ss]),)),'r|',ms=12)
            ax.plot(x[::ss],np.zeros((len(x[::ss]),)),'r|',ms=8)
        elif type(ss).__name__=='list':
            ax1.plot(x[ss],np.zeros((len(x[ss]),)),'r|',ms=12)
            ax.plot(x[ss],np.zeros((len(x[ss]),)),'r|',ms=8)

        ax.set_ylim(0.,); ax.set_xlim(0.,ax.get_xlim()[1]*1.05)
        ax1.set_ylim(0.,); ax1.set_xlim(0.,ax1.get_xlim()[1]*1.05)
        fancy_legend(ax=ax, size=7,ncol=2)
        fancy_legend(ax=ax1,size=7,ncol=2)
        deco(iopt=8,ft=15,ax=ax);  deco(iopt=8,ft=15,ax=ax1)

        if type(ss).__name__=='int':    dum=ss
        elif type(ss).__name__=='list': dum =len(ss)
        fig.savefig('ss_%i_err_scatter_nsamp_%i.pdf'%(dum,nsample))
        plt.close('all')
    return x, e
Exemple #14
0
def influence_of_intp(ss=2,bounds=[0,0.5],
                      psi_nbin=13,iplot=False,
                      hkl=None,
                      iscatter=False,iwgt=False,
                      sigma=5e-5,
                      intp_opt=0):
    """
    Parametric study to demonstrate the uncertainty
    for a fixed intp_opt

    Arguments
    =========
    ss       = 2 (step size)
    bounds   = sin2psi bounds
    psi_nbin = Number of psi data points in use
    iplot    = False
    hkl      = None
    iscatter = False
    iwgt     = False
    sigma    = 5e-5
    intp_opt = 0
    """
    from rs import filter_psi2
    from rs_ex import ex_consistency as main
    from MP.mat.mech import find_err

    if iplot:
        from MP.lib import mpl_lib,axes_label
        import matplotlib.pyplot as plt
        wide_fig     = mpl_lib.wide_fig
        deco         = axes_label.__deco__
        fig          = wide_fig(nw=3,nh=1)
        axs          = fig.axes

    ## Use the reduced set over the consistency check
    sf, ig = use_intp_sfig(
        ss=ss,iopt=intp_opt,iplot=False,
        iwgt=False)

    sf_ext = sf.sf.swapaxes(1,-1).swapaxes(-2,-1)[::]*1e6
    ig_ext = ig.ig[::]

    ##
    # Filtering against sin2psi
    sf_ext = filter_psi2(
        obj=sf_ext,sin2psi=sf.sin2psi,
        bounds=bounds)
    ig_ext = filter_psi2(
        obj=ig_ext,sin2psi=sf.sin2psi,
        bounds=bounds)

    ### Reduce binning
    ## consistency check
    rst = main(sin2psimx=bounds[1],
               psi_nbin=psi_nbin,
               sf_ext=sf_ext,ig_ext=ig_ext,
               iplot=iplot,hkl=hkl,
               iscatter=iscatter,
               sigma=sigma,iwgt=iwgt,
               vf_ext=None)

    fw, fd = rst[1], rst[2]

    if iplot:
        axs[0].plot(fw.epsilon_vm,fw.sigma_vm,
                    'b-x',label='Weight Avg.')
        axs[0].plot(fd.epsilon_vm,fd.sigma_vm,
                    'k+',label='Diff Stress')

    if type(ss).__name__=='int':
        x = fd.epsilon_vm[::ss];
        y = fd.sigma_vm[::ss]
    elif type(ss).__name__=='list':
        x = fd.epsilon_vm[ss];
        y = fd.sigma_vm[ss]

    if iplot:
        label='SF/IG acqusition'
        axs[0].plot(x,y,'o',mec='r',mfc='None',
                    alpha=0.8,label=label)
        axs[1].plot(fw.sigma[0,0],fw.sigma[1,1],'b-x')
        axs[1].plot(fd.sigma[0,0],fd.sigma[1,1],'k+')

    npoints = len(fw.sigma[0,0])
    wgtx, wgty = fw.sigma[0,0], fw.sigma[1,1]
    dsax, dsay = fd.sigma[0,0], fd.sigma[1,1]

    if iplot:
        for i in xrange(npoints):
            axs[1].plot([wgtx[i],dsax[i]],
                        [wgty[i],dsay[i]],
                        'k-',alpha=0.2)

    e = find_err(fw,fd)
    if iplot: axs[2].plot(fw.epsilon_vm, e, 'x')

    if type(ss).__name__=='int' and iplot:
        axs[2].plot(fw.epsilon_vm[::ss],e[::ss],
                    'o',mec='r',mfc='None',label=label)
    elif type(ss).__name__=='list' and iplot:
        axs[2].plot(fw.epsilon_vm[ss],e[ss],
                    'o',mec='r',mfc='None',label=label)

    if type(ss).__name__=='int':    dum=ss
    elif type(ss).__name__=='list': dum =len(ss)

    if iplot:
        axes_label.__eqv__(axs[0],ft=10)
        axs[1].set_aspect('equal')
        axs[1].set_xlabel(r'$\bar{\Sigma}_{11}$',dict(fontsize=15))
        axs[1].set_ylabel(r'$\bar{\Sigma}_{22}$',dict(fontsize=15))
        axs[1].set_ylim(-100,700); axs[1].set_xlim(-100,700)

        axs[0].legend(loc='best',fontsize=10).get_frame().set_alpha(0.5)
        deco(iopt=8,ft=15,ax=axs[2])

        fig.savefig('flow_dd_bin%i_ss%i.pdf'%(psi_nbin,dum))
        plt.close(fig)

    return fw, e
Exemple #15
0
def plot_sf_psis(
        sff_fn='temp.sff',
        psi_ref=[45.0, 42.4, 39.8, 37.1, 34.3, 31.5,
                 28.5, 25.2, 21.7, 17.5, 12.3, 0]):
    import numpy as np
    import matplotlib.pyplot as plt
    from pepshkl import reader4
    from RS import sff_converter
    from rs_exp import read_IGSF
    from MP.lib import mpl_lib, axes_label
    from RS.rs import find_nearest

    deco = axes_label.__deco__
    wf = mpl_lib.wide_fig

    sff_converter.main(fn=sff_fn,difile=None,itab=True,
                       ieps0=4,  fn_str='STR_STR.OUT')
    SF, IG = read_IGSF(fn=sff_fn,fn_str='STR_STR.OUT')

    tdat,_psis_,_vdat_,_ngrd_ = reader4(
        fn='int_els_ph1.out',ndetector=2,iopt=1)

    ## sorting
    import MP.ssort as sort
    shsort = sort.shellSort
    ss     = sort.ind_swap

    ## sort psi and find ind
    psis, ind = shsort(_psis_)
    nstp, nphi, npsis = np.shape(_vdat_)
    vdat = np.zeros((nstp,nphi,npsis))
    ngrd = np.zeros((nstp,nphi,npsis))

    for istp in xrange(nstp):
        for iphi in xrange(nphi):
            dum_v = _vdat_[istp,iphi,:][::]
            vdat[istp,iphi,:] = ss(dum_v[::],ind)[::]

            dum_n = _ngrd_[istp,iphi,:][::]
            ngrd[istp,iphi,:] = ss(dum_n[::],ind)[::]

    ## Find only psi_ref values
    ## sin2psi_ref = np.sin(psi_ref*np.pi/180.)**2
    inds = []
    for i in xrange(len(psi_ref)):
        inds.append(find_nearest(SF.psi, psi_ref[i]))

    #SF.mask_vol() ## shake off all zero values

    fig=wf(nh=nphi,nw=len(psi_ref),iarange=True)
    figv=wf(nh=nphi,nw=len(psi_ref),iarange=True)
    fe0=wf(nh=nphi,nw=len(psi_ref),iarange=True)
    for iphi in xrange(nphi):
        for ipsi in xrange(len(psi_ref)):
            #ax = fig.axes[iphi+nphi*ipsi]
            ax = fig.axes[ipsi+len(psi_ref)*iphi]
            axt = figv.axes[ipsi+len(psi_ref)*iphi]
            aig = fe0.axes[ipsi+len(psi_ref)*iphi]
            if iphi==0:
                ax.set_title(
                    r'$\psi= %3.1f^\circ{}$'%\
                    SF.psi[inds[ipsi]]
                )
                axt.set_title(
                    r'$\psi= %3.1f^\circ{}$'%\
                    SF.psi[inds[ipsi]]
                )
                aig.set_title(
                    r'$\psi= %3.1f^\circ{}$'%\
                    SF.psi[inds[ipsi]]
                )
            if ipsi==0:
                ax.text(0,0,r'$\phi=%3.1f^\circ{}$'%\
                        SF.phi[iphi],transform=ax.transAxes)
                axt.text(0,0,r'$\phi=%3.1f^\circ{}$'%\
                         SF.phi[iphi],transform=axt.transAxes)
                aig.text(0,0,r'$\phi=%3.1f^\circ{}$'%\
                         SF.phi[iphi],transform=aig.transAxes)

                deco(ax,iopt=6)
                deco(axt,iopt=7)

            x = SF.flow.epsilon_vm
            y = SF.sf[:,iphi,inds[ipsi],0] # f11
            ig = IG.ig[:,iphi,inds[ipsi]]
            v = vdat[:,iphi,inds[ipsi]]
            ax.plot(x,y*1e12,'b-o')
            aig.plot(x,ig,'b-o')
            axt.plot(x,v,'r-x')

            axt.set_ylim(0.,0.10)
            ax.set_xlim(0.,1.0)
            aig.set_xlim(0.,1.0)
            aig.set_ylim(-0.002,0.002)
Exemple #16
0
def influence_of_nbin_scatter(
        ss=3,bounds=[0.0, 0.5],
        nbins=[7, 13, 23, 33],
        iscatter=True,nsample=5,iwgt=True,
        sigma=5e-5,intp_opt=0,iplot=False):
    """
    Repeat influence_of_nbin examination
    to verify the error in stress analysis
    pertaining to that in eps(hkl,phi,psi)
    """
    from MP.lib import mpl_lib,axes_label
    import matplotlib.pyplot as plt
    fancy_legend = mpl_lib.fancy_legend
    wide_fig     = mpl_lib.wide_fig
    deco         = axes_label.__deco__
    if iplot:
        fig = wide_fig(nw=2,nh=1);
        ax=fig.axes[0]
        ax1=fig.axes[1]

    Y = []
    for i in range(nsample):
        x, y = influence_of_nbin(
            ss=ss,bounds=bounds,
            nbins=nbins, iscatter=iscatter,
            sigma=sigma,
            iwgt=iwgt,intp_opt=intp_opt)
        Y.append(y)
    ## Y [nsample, nbin, nstp]
    Y = np.array(Y).swapaxes(0,-1).swapaxes(0,1)
    ## Y [nbin, nstp, nsample]
    nbin, nstp, nsamp = Y.shape

    for i in range(nbin):
        e = []; s = []
        for j in range(nstp):
            mean = Y[i,j,:].mean()
            std  = Y[i,j,:].std()
            e.append(mean)
            s.append(std)
        if iplot:
            ax1.plot(x,e,'-o',label=nbins[i])
            ax.errorbar(x,e,yerr=std,fmt='x',label=nbins[i])

    if iplot:
        if type(ss).__name__=='int':
            ax1.plot(x[::ss],np.zeros((len(x[::ss]),)),'r|',ms=12)
            ax.plot(x[::ss],np.zeros((len(x[::ss]),)),'r|',ms=8)
        elif type(ss).__name__=='list':
            ax1.plot(x[ss],np.zeros((len(x[ss]),)),'r|',ms=12)
            ax.plot(x[ss],np.zeros((len(x[ss]),)),'r|',ms=8)

        ax.set_ylim(0.,); ax.set_xlim(0.,ax.get_xlim()[1]*1.05)
        ax1.set_ylim(0.,); ax1.set_xlim(0.,ax1.get_xlim()[1]*1.05)
        fancy_legend(ax=ax, size=7,ncol=2)
        fancy_legend(ax=ax1,size=7,ncol=2)
        deco(iopt=8,ft=15,ax=ax);  deco(iopt=8,ft=15,ax=ax1)

        if type(ss).__name__=='int':    dum=ss
        elif type(ss).__name__=='list': dum =len(ss)
        fig.savefig('ss_%i_err_scatter_nsamp_%i.pdf'%(dum,nsample))
        plt.close('all')
    return x, e