예제 #1
0
파일: mst_ex.py 프로젝트: youngung/rs
def main_plot_flow_all(hkl='211',sin2psimx=0.5,
                       psi_nbin=1,pmargin=None,iplot_rs=False,
                       path=''):
    """  """
    fns = read(hkl,prefix=path)
    fig = wf(nw=3,nh=1,left=0.2,uw=3.5,
             w0=0,w1=0.3,right=0,iarange=True)
    ax1,ax2,ax3 = fig.axes
    axes_label.__eqv__(ax1,ft=10)
    errors = []
    for i in range(len(fns)):
        fn = fns[i]
        strain_path = fn.split('_')[0]
        untargz(fn)
        model_rs, fwgt, fdsa \
            = rs_ex.ex_consistency(
                sin2psimx=sin2psimx,
                psi_nbin=psi_nbin,
                hkl=hkl,iplot=iplot_rs,
                pmargin=pmargin,path=path)
        fwgt.get_eqv(); fdsa.get_eqv()

        e = find_err(fwgt,fdsa)
        ax3.plot(fwgt.epsilon_vm,e)
        errors.append([fwgt.epsilon_vm,e])

        ax1.plot(fwgt.epsilon_vm,fwgt.sigma_vm,
                 'bx-',label='Weighted Avg', alpha=1.0)
        ax1.plot(fdsa.epsilon_vm,fdsa.sigma_vm,
                 'kx',label='Diff. Stress Analsysis', alpha=1.0)
        ax2.plot(fwgt.sigma[0,0],fwgt.sigma[1,1],'b+')
        ax2.plot(fdsa.sigma[0,0],fdsa.sigma[1,1],'k+')

        ## connector
        npoints = len(fwgt.sigma[0,0])
        wgtx = fwgt.sigma[0,0]; wgty = fwgt.sigma[1,1]
        dsax = fdsa.sigma[0,0]; dsay = fdsa.sigma[1,1]
        for j in range(npoints):
            ax2.plot([wgtx[j],dsax[j]],[wgty[j],dsay[j]],'k-',alpha=0.5)
        plt.show();plt.draw()

    ax1.set_xlim(-0.1,1.1); ax1.set_ylim(-50,700);
    ax2.set_xlim(-10,1000); ax2.set_ylim(-10,1000)
    ax2.set_aspect('equal')
    ax2.set_xlabel(r'$\bar{\Sigma}_{11}$',dict(fontsize=15))
    ax2.set_ylabel(r'$\bar{\Sigma}_{22}$',dict(fontsize=15))
    ax2.locator_params(nbins=3)
    ax2.grid('on'); plt.show()

    fig.savefig('flow_allpaths_%s.pdf'%(hkl))
    plt.close(fig)

    return np.array(errors)[0]
예제 #2
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
예제 #3
0
def ex_consistency(
        ifig=50,nxphi=3,exp_ref=[],exp_lab=[],mod_ext=None,
        mod_ref='STR_STR.OUT',sin2psimx=None,iscatter=False,
        sigma=5e-5,psimx=None,psi_nbin=1,ig_sub=True,istep=None,
        hkl=None,iplot=True,iwind=False,wdeg=2,ipsi_opt=1,
        fn_sff=None,pmargin=None,path='',sf_ext=None,ig_ext=None,
        vf_ext=None,iwgt=False,verbose=False,ilog=False,
        dec_inv_frq=1,dec_interp=1,theta_b=None,ird=1.):
    """
    Consistency check between 'weighted average' stress and
    the stress obtained following the stress analysis method
    (SF, IG strain)

    ----------------------------------------
    ## Data visualization options
    ifig = 50
    nxphi     : display only first nxphi of results
                along phi axis
    hkl       : hkl of plane, for the sake of labels.
    path      : place holder for strain path

    ----------------------------------------
    ## Data process parameters
    #1. Main options
    sf_ext    : Overwrite stress factor
    ig_ext    : Overwrite IG strain
    vf_ext    : Overwrite grain volume fraction (nstp,nphi,npsi)
    iscatter (False) : introducing a random scattering of 'ehkl'

    #2. tilting angle restriction/treatments
    sin2psimx : limiting the maximum sin2psi values, with which
                stress-fitting is carried out
    psimx     : limiting the maximum psi value
    psi_nbin  : If other than 1, limit the number of data

    #3. IG strain-specific
    ig_sub    : flag whether or not subtract the IG strain

    #4. DEC related
    dec_inv_frq   : Inverse Frequency of DEC measures along EVM (nstp)
    dec_interp: Interpolation method for the incomplete DEC

    #5. Misc.
    exp_ref   : experimental reference
    mod_ref   : model's weighted average flow curves are given

    ----------------------------------------
    ## misc. options
    iplot (True) : flag whether or not MPL plot is performed
    ipsi_opt 0: sin2psi
             1: sign(psi) * sin2psi
             2: psi
    istep     : If other than None, analysis is carried out
                only for the given istep

    ----------------------------------------
    ## debugging options
    verbose   : False
    ilog      : False

    ----------------------------------------
    ## Diffraction condition parameters
    theta_b   : None (Bragg's angle)
    ird       : Intensity expected for random distribution
    """
    if ilog:
        fn = 'ex_consistency.log'
        f = open(fn,'w')
        write_args(
            f=f,ihead=True,ifig=ifig,nxphi=nxphi,exp_ref=exp_ref,
            exp_lab=exp_lab,mod_ext=mod_ext,mod_ref=mod_ref,
            sin2psimx=sin2psimx,iscatter=iscatter,sigma=sigma,
            psimx=psimx,psi_nbin=psi_nbin,ig_sub=ig_sub,
            istep=istep,hkl=hkl,iplot=iplot,iwind=iwind,
            wdeg=wdeg,ipsi_opt=ipsi_opt,fn_sff=fn_sff,
            pmargin=pmargin,path=path,sf_ext=sf_ext,
            ig_ext=ig_ext,vf_ext=vf_ext,iwgt=iwgt,
            verbose=verbose,ilog=ilog)
        f.close()
        print 'log has been saved to ',fn

    from rs import ResidualStress,u_epshkl,\
        u_epshkl_geom_inten,filter_psi,filter_psi3,\
        psi_reso,psi_reso2,psi_reso3,psi_reso4

    from mst_ex import use_intp_sfig, return_vf
    from MP.mat import mech # mech is a module

    FlowCurve = mech.FlowCurve

    if iplot:
        from matplotlib import pyplot as plt
        from matplotlib.backends.backend_pdf import PdfPages
        from MP.lib import mpl_lib,axes_label
        plt.ioff()
        wide_fig     = mpl_lib.wide_fig
        fancy_legend = mpl_lib.fancy_legend
        ## Collection of figures at various plastic strains
        fe   = PdfPages('all_ehkl_fits_%s_%s.pdf'%(hkl,path))
        fs   = PdfPages('all_stress_factors_%s_%s.pdf'%(hkl,path))
        f_er = PdfPages('all_Ei-ehkl-e0_%s_%s.pdf'%(hkl,path))
        fig1 = wide_fig(ifig,nw=2,nh=1,left=0.2,uw=3.5,
                        w0=0,w1=0.3,right=0,iarange=True)

        ## ax1: Equivalent Stress/Strain
        ## ax2: Stress path in the plane stress space (RD/TD)
        ax1 = fig1.axes[0]; ax2 = fig1.axes[1]
        pass

    #------------------------------------------------------------#
    ## i_ip = 1: ioption for the model data
    model_rs = ResidualStress(
        mod_ext=mod_ext,fnmod_ig='igstrain_fbulk_ph1.out',
        fnmod_sf='igstrain_fbulk_ph1.out',i_ip=1)

    ## Process the sf/eps0/ehkl/wgt and so forth
    ## according to the parameters given
    ivf_ext=True; isf_ext=True; iig_ext=True
    if type(sf_ext)==type(None):isf_ext=False
    if type(ig_ext)==type(None):iig_ext=False
    if type(vf_ext)==type(None):ivf_ext=False

    """
    ## final data should be saved to
    'model_sfs'
    'model_igs'
    'model_ehkl'
    And eventually to 'model_tdats' inside the loop
    """

    ## SF/IG/ehkl
    model_ehkls = np.copy(model_rs.dat_model.ehkl)
    if isf_ext and iig_ext:
        model_sfs = sf_ext.copy()
        model_igs = ig_ext.copy()
    elif isf_ext!=iig_ext:
        raise IOError, 'isf_ext should equal to iig_ext'
    ## if isf_ext False and isf_ext False
    else:
        model_sfs = model_rs.dat_model.sf.copy()
        model_igs = model_rs.dat_model.ig.copy()

    ## VF
    if not(ivf_ext): model_vfs, model_ngr = return_vf()
    else: model_vfs = vf_ext.copy()

    ## whether or not vf would be used as weights in
    ## the least-sq estimator
    if not(iwgt): wgt = None # overwrite wgt

    # Apply process
    # 0. Use of interpolated SF?
    # 1. Limit the range of sin2psi (or psi)
    # 2. Finite number of tiltings
    # 3. Assign tdat
    # 4. Perturb ehkl (common)
    # 5. Filter based on vf?

    ## Unstaged but the 'raw' arrays
    raw_psis = model_rs.dat_model.psi.copy()
    raw_vfs  = model_vfs.copy()
    raw_ehkl = np.copy(model_rs.dat_model.ehkl)
    raw_sfs  = model_sfs.copy()

    ## staged arrays for stress estimation
    model_rs.psis = model_rs.dat_model.psi.copy()
    model_rs.phis = model_rs.dat_model.phi.copy()
    model_rs.npsi = len(model_rs.psis)
    model_rs.nphi = len(model_rs.phis)
    sin2psis_init = np.sin(model_rs.psis)**2

    # 0. Use interpolated SF

    _sf_, _ig_ = use_intp_sfig(
        dec_inv_frq,iopt=dec_interp,
        iplot=False,iwgt=False)
    ## swapping axes to comply with what is used
    ## in dat_model.sf
    _sf_ = _sf_.sf.swapaxes(1,3).swapaxes(2,3)
    _sf_ = _sf_ *1e6

    # 0.5 Mask DEC where volume fraction
    ## model_ngr or model_vfs
    for i in range(len(model_vfs)):
        for j in range(len(model_vfs[i])):
            for k in range(len(model_vfs[i][j])):
                if model_ngr[i,j,k]==0:
                    _sf_[i,:,j,k]=np.nan
                    # _ig_[i,j,k]=np.nan
                    raw_sfs[i,:,j,k]=np.nan
                    model_sfs[i,:,j,k]=np.nan
                    raw_ehkl[i,j,k] = np.nan
                for m in range(6):
                    if _sf_[i,m,j,k]==0 or raw_sfs[i,m,j,k]==0:
                        # print 'encountered zero sf'
                        _sf_[i,m,j,k] = np.nan
                        raw_sfs[i,m,j,k] = np.nan
                        model_sfs[i,m,j,k] = np.nan
                        raw_ehkl[i,j,k] = np.nan

    # 1. Limit the range of sin2psi (or psi)
    if type(sin2psimx)!=type(None) or \
       type(psimx)!=type(None):
        if type(sin2psimx)!=type(None):
            bounds=[0., sin2psimx]
        elif type(psimx)!=type(None):
            bounds=[0.,np.sin(psimx*np.pi/180.)**2]

        raw_sfs,model_sfs,model_igs,model_vfs,\
            model_ehkls,raw_psis,_sf_,raw_vfs\
            = filter_psi3(
                sin2psis_init,bounds,
                raw_sfs,model_sfs,model_igs,model_vfs,
                model_ehkls,raw_psis,_sf_,raw_vfs)

        ## reduce the psis in model_rs
        model_rs.psis, = filter_psi3(
            sin2psis_init,bounds,
            model_rs.psis.copy())
        model_rs.npsi = len(model_rs.psis)

    DEC_interp = _sf_.copy()

    # 2. Finite number of tiltings
    if psi_nbin!=1:
        model_sfs, model_igs, model_vfs, \
            model_ehkls, _sf_ \
            = psi_reso4(
                model_rs.psis, psi_nbin,
                model_sfs,model_igs,
                model_vfs,model_ehkls,_sf_)
        model_rs.psis, = psi_reso4(
            model_rs.psis.copy(),psi_nbin,
            model_rs.psis.copy())
        model_rs.npsi = len(model_rs.psis)

    # 3. Assign tdat
    if ig_sub: model_tdats = model_ehkls - model_igs
    else: model_tdats = model_ehkls.copy()

    # 4. Perturb ehkl (common)
    if iscatter:
        nstp, nphi, npsi = model_ehkls.shape
        tdats = np.zeros((nstp,nphi,npsi))
        for istp in range(nstp):
            for iphi in range(nphi):
                # ## Previous perturbation rule
                # tdats[istp,iphi,:] = u_epshkl(
                #     model_tdats[istp,iphi],
                #     sigma=sigma)

                ## New perturbation rule
                if type(theta_b).__name__== 'NoneType':
                    raise IOError, 'theta_b should be given'
                for ipsi in range(npsi):
                    ## multitudes of random
                    mrd = model_vfs[istp,iphi,ipsi]/ird
                    tdats[istp,iphi,ipsi] = u_epshkl_geom_inten(
                        e     = model_tdats[istp,iphi,ipsi],
                        sigma = sigma,
                        psi   = model_rs.psis[ipsi],

                        ## need to calculate the below...
                        theta_b = theta_b,
                        mrd = mrd)

    else: tdats=model_tdats.copy()

    ## end of data process
    #------------------------------------------------------------#

    if mod_ext==None: mod_ref='STR_STR.OUT'
    else: mod_ref='%s.%s'%(mod_ref.split('.')[0],
    mod_ext)

    flow_weight = FlowCurve(name='Model weighted')
    flow_weight.get_model(fn=mod_ref)
    ## calc Von Mises stress/strain
    flow_weight.get_eqv()

    if len(flow_weight.epsilon_vm)<5: lc='k.'
    else:                             lc='k-'

    if iplot:
        ax1.plot(
            flow_weight.epsilon_vm,
            flow_weight.sigma_vm,
            lc,label=r'$\langle \sigma^c \rangle$',
            alpha=1.0)
        axes_label.__eqv__(ax1,ft=10)

    ## plot all stress factors at individual
    ## deformation levels

    stress = []
    if verbose or True: print '%8s%8s%8s%8s%8s%8s'%(
        'S11','S22','S33','S23','S13','S12')

    ################################################
    ## *Serial* Loop over the deformation steps
    ref_psis = model_rs.psis.copy()
    nstp = model_rs.dat_model.nstp

    # nstp = 3 ## debugging

    for istp in range(nstp):
        """
        Dimensions of data arrays for:
        ==============================
        sf     (nstp, k, nphi, npsi)
        ig     (nstp, nphi, npsi)
        ehkl   (nstp, nphi, npsi)
        strain (nstp, 6)
        vf     (nstp, nphi, npsi)
        """

        if iplot==False and istep!=None:
            nstp=1
            istp = istep

        print 'processing: %2.2i/%2.2i'%(istp,nstp)
        #model_rs.sf = model_sfs[istp].copy()

        ## filter signals where any data is nan
        ref = _sf_[istp].copy()
        inds = []

        ## masking can be improved by being
        ## specific on phi axis -> require fix in RS.rs
        # for iphi in range(len(ref[0])):
        for ipsi in range(len(ref_psis)):
            if not(np.isnan(ref[0:2,:,ipsi]).any()):
                inds.append(ipsi)

        model_rs.sf  = _sf_[istp][:,:,inds]
        model_rs.psis = ref_psis[inds]
        model_rs.npsi = len(model_rs.psis)
        model_rs.eps0 = model_igs[istp][:,inds]
        model_rs.ehkl = model_ehkls[istp][:,inds]
        model_rs.tdat = tdats[istp][:,inds]

        #-----------------------------------#
        ## find the sigma ...
        s11 = model_rs.dat_model.\
              flow.sigma[0,0][istp]
        s22 = model_rs.dat_model.\
              flow.sigma[1,1][istp]

        ## find the stress by fitting
        ## the elastic strains
        dsa_sigma = model_rs.find_sigma(
            ivo=[0,1],
            init_guess=[0,0,0,0,0,0],#[s11,s22,0,0,0,0],
            weight = wgt) # None

        if verbose or True:
            for i in range(6): print '%+7.1f'%(dsa_sigma[i]),
            print ''
        stress.append(dsa_sigma)

        full_Ei = np.zeros((model_rs.nphi,len(raw_psis)))
        for iphi in range(model_rs.nphi):
            for ipsi in range(len(raw_psis)):
                for k in range(2):
                    full_Ei[iphi,ipsi] \
                        = full_Ei[iphi,ipsi]+\
                        raw_sfs[istp,k,iphi,ipsi]*dsa_sigma[k]

        if istep!=None and iplot==False:
            return model_rs, s11,s22, dsa_sigma[0],dsa_sigma[1],\
                raw_psis.copy(),\
                raw_vfs[istp].copy(),raw_sfs[istp].copy(),\
                full_Ei.copy(),\
                DEC_interp[istp].copy()

        #-----------------------------------#
        if istp==0: ileg=True
        else:       ileg=True #False

        if (istep!=None and istp==istep) or\
           (istep==None and istp==nstp-1)\
           and iplot:
            fig2,fig3,fig4=__model_fit_plot__(
                model_rs,ifig=ifig+istp*2+10,
                istp=istp, nxphi=nxphi,stress_wgt=None,
                ivo=None,hkl=hkl,ileg=ileg,iwind=iwind,
                wdeg=wdeg)
        elif iplot:
            plt.ioff()
            f1,f2,f3=__model_fit_plot__(
                model_rs,ifig=ifig+istp*2+10,
                ## stress_wgt: the mechanical stress.
                ## will be used as a reference line
                istp=istp,nxphi=nxphi,stress_wgt=[s11,s22,0,0,0,0],
                wgt=raw_vfs[istp].copy(),wgt_psi=raw_psis,
                full_Ei = full_Ei,
                full_DEC = raw_sfs[istp].copy(),
                DEC_interp = DEC_interp[istp].copy(),
                ivo=[0,1],hkl=hkl,ileg=ileg,iwind=False,
                ipsi_opt=ipsi_opt)
            fs.savefig(f2);fe.savefig(f1);f_er.savefig(f3)
            f1.clf();plt.draw();f2.clf();plt.draw();f3.clf();plt.draw()
            plt.close(f1);plt.close(f2);plt.close(f3);plt.ion()
    # end of the serial loop over deformation steps
    ############################################################

    if iplot: fe.close(); fs.close(); f_er.close()

    stress   = np.array(stress).T # diffraction stress
    flow_dsa = FlowCurve(name='Diffraction Stress')
    flow_dsa.get_6stress(stress)
    flow_dsa.get_33strain(model_rs.dat_model.flow.epsilon)
    flow_dsa.get_eqv()

    ## Various plots
    if iplot:
        ax1.plot(flow_dsa.epsilon_vm,flow_dsa.sigma_vm,'k+',
                 label=r'$\hat{\sigma}^{RS}$')
        for i in range(len(exp_ref)):
            f = exp_ref[i]; lab = exp_lab[i]
            edat = np.loadtxt(f).T
            ax1.plot(edat[0],edat[1],'-',lw=2,label=lab)
            ## ax1.set_ylim(0.,800)
        fancy_legend(ax1,size=10,nscat=2)

    sigma_wgt = flow_weight.sigma

    if iplot:
        ax2.plot(sigma_wgt[0,0],sigma_wgt[1,1],'k-')
        ax2.plot(flow_dsa.sigma[0,0],flow_dsa.sigma[1,1],'k+')

        ## connector
        npoints = len(sigma_wgt[0,0])
        wgtx = sigma_wgt[0,0];      wgty = sigma_wgt[1,1]
        dsax = flow_dsa.sigma[0,0]; dsay = flow_dsa.sigma[1,1]
        for i in range(npoints):
            ax2.plot([wgtx[i],dsax[i]],[wgty[i],dsay[i]],'k-',alpha=0.2)

        ax2.set_ylim(-100,700); ax2.set_xlim(-100,700)
        ax2.set_aspect('equal')
        ax2.set_xlabel(r'$\bar{\Sigma}_{11}$',dict(fontsize=15))
        ax2.set_ylabel(r'$\bar{\Sigma}_{22}$',dict(fontsize=15))
        ax2.locator_params(nbins=3)
        ax2.set_xticks(np.linspace(300,700,3),dict(fontsize=4))
        ax2.set_yticks(np.linspace(300,700,3),dict(fontsize=4))
        ax2.grid('on'); plt.show()

        ## save figures
        fig1.savefig('flow_%s_%s.pdf'%(hkl,path))
        ## fig2.savefig('ehkl_%s_fit_%s.pdf'%(hkl,path))
        ## fig3.savefig('sf_%s_%s.pdf'%(hkl,path))
        ## fig4.savefig('ehkl_fit_err_%s_%s.pdf'%(hkl,path))
        # close figures
        plt.close(fig1); plt.close(fig2); plt.close(fig3); plt.close(fig4)

    return model_rs, flow_weight, flow_dsa
예제 #4
0
def ex_consistency(
        ifig=50,nxphi=3,exp_ref=[],exp_lab=[],mod_ext=None,
        mod_ref='STR_STR.OUT',sin2psimx=None,iscatter=False,
        sigma=5e-5,psimx=None,psi_nbin=1,ig_sub=True,istep=None,
        hkl=None,iplot=True,iwind=False,wdeg=2,ipsi_opt=1,
        fn_sff=None,pmargin=None,path='',sf_ext=None,ig_ext=None,
        vf_ext=None,iwgt=False,verbose=False,ilog=True,
        dec_inv_frq=1,dec_interp=1,theta_b=None,ird=1.,nfrq=None):
    """
    Consistency check between 'weighted average' stress and
    the stress obtained following the stress analysis method
    (SF, IG strain)

    ----------------------------------------
    ## Data visualization options
    ifig = 50
    nxphi     : display only first nxphi of results
                along phi axis
    hkl       : hkl of plane, for the sake of labels.
    path      : place holder for strain path

    ----------------------------------------
    ## Data process parameters
    #1. Main options
    sf_ext    : Overwrite stress factor
    ig_ext    : Overwrite IG strain
    vf_ext    : Overwrite grain volume fraction (nstp,nphi,npsi)
    iscatter (False) : introducing a random scattering of 'ehkl'
    sigma     : Level of standard deviation in the Gaussian distribution
                used to 'perturb' the lattice strain.

    #2. tilting angle restriction/treatments
    sin2psimx : limiting the maximum sin2psi values, with which
                stress-fitting is carried out
    psimx     : limiting the maximum psi value
    psi_nbin  : If other than 1, limit the number of data

    #3. IG strain-specific
    ig_sub    : flag whether or not subtract the IG strain

    #4. DEC related
    dec_inv_frq : Inverse Frequency of DEC measures along EVM (nstp)
    dec_interp: Interpolation method for the incomplete DEC

    #5. Misc.
    exp_ref   : experimental reference
    mod_ref   : model's weighted average flow curves are given

    ----------------------------------------
    ## misc. options
    iplot (True) : flag whether or not MPL plot is performed
    ipsi_opt 0: sin2psi
             1: sign(psi) * sin2psi
             2: psi
    istep     : If other than None, analysis is carried out
                only for the given istep

    ----------------------------------------
    ## debugging options
    verbose   : False
    ilog      : False

    ----------------------------------------
    ## Diffraction condition parameters
    theta_b   : None (Bragg's angle) (given in radian)
    ird       : Intensity expected for random distribution
    nfrq        None
    """
    import time
    from MP import progress_bar
    uet = progress_bar.update_elapsed_time
    t0 = time.time()
    if ilog:
        fn = 'ex_consistency.log'
        f = open(fn,'w')
        write_args(
            f=f,ihead=True,ifig=ifig,nxphi=nxphi,exp_ref=exp_ref,
            exp_lab=exp_lab,mod_ext=mod_ext,mod_ref=mod_ref,
            sin2psimx=sin2psimx,iscatter=iscatter,sigma=sigma,
            psimx=psimx,psi_nbin=psi_nbin,ig_sub=ig_sub,
            istep=istep,hkl=hkl,iplot=iplot,iwind=iwind,
            wdeg=wdeg,ipsi_opt=ipsi_opt,fn_sff=fn_sff,
            pmargin=pmargin,path=path,sf_ext=sf_ext,
            ig_ext=ig_ext,vf_ext=vf_ext,iwgt=iwgt,
            verbose=verbose,ilog=ilog,nfrq=nfrq,
            ird=ird,theta_b=theta_b)
        f.close()
        print 'log has been saved to ',fn

    from rs import ResidualStress,u_epshkl,\
        u_epshkl_geom_inten,filter_psi,filter_psi3,\
        psi_reso,psi_reso2,psi_reso3,psi_reso4

    from mst_ex import use_intp_sfig, return_vf
    from MP.mat import mech # mech is a module

    FlowCurve = mech.FlowCurve

    if iplot:
        from matplotlib import pyplot as plt
        from matplotlib.backends.backend_pdf import PdfPages
        from MP.lib import mpl_lib,axes_label
        plt.ioff()
        wide_fig     = mpl_lib.wide_fig
        fancy_legend = mpl_lib.fancy_legend
        ## Collection of figures at various plastic strains
        fe   = PdfPages('all_ehkl_fits_%s_%s.pdf'%(hkl,path))
        fs   = PdfPages('all_stress_factors_%s_%s.pdf'%(hkl,path))
        f_er = PdfPages('all_Ei-ehkl-e0_%s_%s.pdf'%(hkl,path))
        fig1 = wide_fig(ifig,nw=2,nh=1,left=0.2,uw=3.5,
                        w0=0,w1=0.3,right=0,iarange=True)

        fig_vm = plt.figure(figsize=(3.5,3.5))
        ax_vm = fig_vm.add_subplot(111)

        ## ax1: Equivalent Stress/Strain
        ## ax2: Stress path in the plane stress space (RD/TD)
        ax1 = fig1.axes[0]; ax2 = fig1.axes[1]
        pass

    #------------------------------------------------------------#
    ## i_ip = 1: ioption for the model data
    model_rs = ResidualStress(
        mod_ext=mod_ext,fnmod_ig='igstrain_fbulk_ph1.out',
        fnmod_sf='igstrain_fbulk_ph1.out',i_ip=1)

    ## Process the sf/eps0/ehkl/wgt and so forth
    ## according to the parameters given
    ivf_ext=True; isf_ext=True; iig_ext=True
    if type(sf_ext)==type(None):isf_ext=False
    if type(ig_ext)==type(None):iig_ext=False
    if type(vf_ext)==type(None):ivf_ext=False

    """
    ## final data should be saved to
    'model_sfs'
    'model_igs'
    'model_ehkl'
    And eventually to 'model_tdats' inside the loop
    """

    ## SF/IG/ehkl
    model_ehkls = np.copy(model_rs.dat_model.ehkl)
    if isf_ext and iig_ext:
        model_sfs = sf_ext.copy()
        model_igs = ig_ext.copy()
    elif isf_ext!=iig_ext:
        raise IOError, 'isf_ext should equal to iig_ext'
    ## if isf_ext False and isf_ext False
    else:
        model_sfs = model_rs.dat_model.sf.copy()
        model_igs = model_rs.dat_model.ig.copy()

    ## VF
    if not(ivf_ext): model_vfs, model_ngr = return_vf()
    else: model_vfs = vf_ext.copy()

    ## whether or not vf would be used as weights in
    ## the least-sq estimator
    if not(iwgt): wgt = None # overwrite wgt

    # Apply process
    # 0. Use of interpolated SF?
    # 1. Limit the range of sin2psi (or psi)
    # 2. Finite number of tiltings
    # 3. Assign tdat
    # 4. Perturb ehkl (common)
    # 5. Filter based on vf?

    ## Unstaged but the 'raw' arrays
    raw_psis = model_rs.dat_model.psi.copy()
    raw_vfs  = model_vfs.copy()
    raw_ehkl = np.copy(model_rs.dat_model.ehkl)
    raw_sfs  = model_sfs.copy()

    ## staged arrays for stress estimation
    model_rs.psis = model_rs.dat_model.psi.copy()
    model_rs.phis = model_rs.dat_model.phi.copy()
    model_rs.npsi = len(model_rs.psis)
    model_rs.nphi = len(model_rs.phis)
    sin2psis_init = np.sin(model_rs.psis)**2

    # 0. Use interpolated SF

    _sf_, _ig_ = use_intp_sfig(
        dec_inv_frq,iopt=dec_interp,
        iplot=False,iwgt=False)
    ## swapping axes to comply with what is used
    ## in dat_model.sf
    _sf_ = _sf_.sf.swapaxes(1,3).swapaxes(2,3)
    _sf_ = _sf_ *1e6

    # 0.5 Mask DEC where volume fraction
    ## model_ngr or model_vfs
    for i in xrange(len(model_vfs)):
        for j in xrange(len(model_vfs[i])):
            for k in xrange(len(model_vfs[i][j])):
                if model_ngr[i,j,k]==0:
                    _sf_[i,:,j,k]=np.nan
                    # _ig_[i,j,k]=np.nan
                    raw_sfs[i,:,j,k]=np.nan
                    model_sfs[i,:,j,k]=np.nan
                    raw_ehkl[i,j,k] = np.nan
                for m in xrange(6):
                    if _sf_[i,m,j,k]==0 or raw_sfs[i,m,j,k]==0:
                        # print 'encountered zero sf'
                        _sf_[i,m,j,k] = np.nan
                        raw_sfs[i,m,j,k] = np.nan
                        model_sfs[i,m,j,k] = np.nan
                        raw_ehkl[i,j,k] = np.nan

    # 1. Limit the range of sin2psi (or psi)
    if type(sin2psimx)!=type(None) or \
       type(psimx)!=type(None):
        if type(sin2psimx)!=type(None):
            bounds=[0., sin2psimx]
        elif type(psimx)!=type(None):
            bounds=[0.,np.sin(psimx*np.pi/180.)**2]

        raw_sfs,model_sfs,model_igs,model_vfs,\
            model_ehkls,raw_psis,_sf_,raw_vfs\
            = filter_psi3(
                sin2psis_init,bounds,
                raw_sfs,model_sfs,model_igs,model_vfs,
                model_ehkls,raw_psis,_sf_,raw_vfs)

        ## reduce the psis in model_rs
        model_rs.psis, = filter_psi3(
            sin2psis_init,bounds,
            model_rs.psis.copy())
        model_rs.npsi = len(model_rs.psis)

    DEC_interp = _sf_.copy()

    # 2. Finite number of tiltings
    if psi_nbin!=1:
        model_sfs, model_igs, model_vfs, \
            model_ehkls, _sf_ \
            = psi_reso4(
                model_rs.psis, psi_nbin,
                model_sfs,model_igs,
                model_vfs,model_ehkls,_sf_)
        model_rs.psis, = psi_reso4(
            model_rs.psis.copy(),psi_nbin,
            model_rs.psis.copy())
        model_rs.npsi = len(model_rs.psis)

    # 3. Assign tdat
    if ig_sub: model_tdats = model_ehkls - model_igs
    else: model_tdats = model_ehkls.copy()

    # 4. Perturb ehkl (common)
    if iscatter:
        nstp, nphi, npsi = model_ehkls.shape
        tdats = np.zeros((nstp,nphi,npsi))
        for istp in xrange(nstp):
            for iphi in xrange(nphi):
                # ## Previous perturbation rule
                # tdats[istp,iphi,:] = u_epshkl(
                #     model_tdats[istp,iphi],
                #     sigma=sigma)

                ## New perturbation rule
                if type(theta_b).__name__== 'NoneType':
                    raise IOError, 'theta_b should be given'
                for ipsi in xrange(npsi):
                    ## multitudes of random
                    mrd = model_vfs[istp,iphi,ipsi]/ird
                    tdats[istp,iphi,ipsi] = u_epshkl_geom_inten(
                        e     = model_tdats[istp,iphi,ipsi],
                        sigma = sigma,
                        psi   = model_rs.psis[ipsi],
                        ## need to calculate the below...
                        theta_b = theta_b,
                        mrd = mrd)

    else: tdats=model_tdats.copy()

    ## end of data process
    #------------------------------------------------------------#

    if mod_ext==None: mod_ref='STR_STR.OUT'
    else: mod_ref='%s.%s'%(mod_ref.split('.')[0],
    mod_ext)

    flow_weight = FlowCurve(name='Model weighted')
    flow_weight.get_model(fn=mod_ref)
    ## calc Von Mises stress/strain
    flow_weight.get_eqv()

    if len(flow_weight.epsilon_vm)<5: lc='k.'
    else:                             lc='k-'

    if iplot:
        for a in [ax1,ax_vm]:
            a.plot(
                flow_weight.epsilon_vm,
                flow_weight.sigma_vm,
                lc,label=r'$\langle \sigma^c \rangle$',
                alpha=1.0)
            axes_label.__eqv__(a,ft=10)

    ## plot all stress factors at individual
    ## deformation levels

    stress = []
    if verbose or True: print '%8s%8s%8s%8s%8s%8s'%(
        'S11','S22','S33','S23','S13','S12')

    ################################################
    ## *Serial* Loop over the deformation steps
    ref_psis = model_rs.psis.copy()
    nstp = model_rs.dat_model.nstp

    # nstp = 3 ## debugging

    for istp in xrange(nstp):
        """
        Dimensions of data arrays for:
        ==============================
        sf     (nstp, k, nphi, npsi)
        ig     (nstp, nphi, npsi)
        ehkl   (nstp, nphi, npsi)
        strain (nstp, 6)
        vf     (nstp, nphi, npsi)
        """
        if type(nfrq).__name__=='int':
            if istp % nfrq !=0:
                continue

        if iplot==False and type(istep)!=type(None):
            nstp = 1
            istp = istep

        print 'processing: %2.2i/%2.2i'%(istp,nstp),
        #model_rs.sf = model_sfs[istp].copy()

        ## filter signals where any data is nan
        ref = _sf_[istp].copy()
        inds = []

        ## masking can be improved by being
        ## specific on phi axis -> require fix in RS.rs
        # for iphi in xrange(len(ref[0])):
        for ipsi in xrange(len(ref_psis)):
            if not(np.isnan(ref[0:2,:,ipsi]).any()):
                inds.append(ipsi)

        model_rs.sf  = _sf_[istp][:,:,inds]
        model_rs.psis = ref_psis[inds]
        model_rs.npsi = len(model_rs.psis)
        model_rs.eps0 = model_igs[istp][:,inds]
        model_rs.ehkl = model_ehkls[istp][:,inds]
        model_rs.tdat = tdats[istp][:,inds]

        #-----------------------------------#
        ## find the sigma ...
        s11 = model_rs.dat_model.\
              flow.sigma[0,0][istp]
        s22 = model_rs.dat_model.\
              flow.sigma[1,1][istp]

        ## find the stress by fitting
        ## the elastic strains
        dsa_sigma = model_rs.find_sigma(
            ivo=[0,1],
            init_guess=[0,0,0,0,0,0],#[s11,s22,0,0,0,0],
            weight = wgt) # None

        if verbose or True:
            for i in xrange(6): print '%+7.1f'%(dsa_sigma[i]),
            print ''
        stress.append(dsa_sigma)

        full_Ei = np.zeros((model_rs.nphi,len(raw_psis)))
        for iphi in xrange(model_rs.nphi):
            for ipsi in xrange(len(raw_psis)):
                for k in xrange(2):
                    full_Ei[iphi,ipsi] \
                        = full_Ei[iphi,ipsi]+\
                        raw_sfs[istp,k,iphi,ipsi]*dsa_sigma[k]

        if type(istep)!=type(None) and iplot==False:
            return model_rs, s11,s22, dsa_sigma[0],dsa_sigma[1],\
                raw_psis.copy(),\
                raw_vfs[istp].copy(),raw_sfs[istp].copy(),\
                full_Ei.copy(),\
                DEC_interp[istp].copy()

        #-----------------------------------#
        if istp==0: ileg=True
        else:       ileg=True #False

        if (istep!=None and istp==istep) or\
           (istep==None and istp==nstp-1)\
           and iplot:
            fig2,fig3,fig4=__model_fit_plot__(
                model_rs,ifig=ifig+istp*2+10,
                istp=istp, nxphi=nxphi,stress_wgt=None,
                ivo=None,hkl=hkl,ileg=ileg,iwind=iwind,
                wdeg=wdeg)
        elif iplot:
            plt.ioff()
            f1,f2,f3=__model_fit_plot__(
                model_rs,ifig=ifig+istp*2+10,
                ## stress_wgt: the mechanical stress.
                ## will be used as a reference line
                istp=istp,nxphi=nxphi,stress_wgt=[s11,s22,0,0,0,0],
                wgt=raw_vfs[istp].copy(),wgt_psi=raw_psis,
                full_Ei = full_Ei,
                full_DEC = raw_sfs[istp].copy(),
                DEC_interp = DEC_interp[istp].copy(),
                ivo=[0,1],hkl=hkl,ileg=ileg,iwind=False,
                ipsi_opt=ipsi_opt)
            fs.savefig(f2);fe.savefig(f1);f_er.savefig(f3)
            f1.clf();plt.draw();f2.clf();plt.draw();f3.clf();plt.draw()
            plt.close(f1);plt.close(f2);plt.close(f3);plt.ion()
    # end of the serial loop over deformation steps
    ############################################################

    if iplot: fe.close(); fs.close(); f_er.close()

    stress   = np.array(stress).T # diffraction stress
    flow_dsa = FlowCurve(name='Diffraction Stress')
    flow_dsa.get_6stress(stress)

    if type(nfrq).__name__=='NoneType':
        flow_dsa.get_33strain(model_rs.dat_model.flow.epsilon)
    elif type(nfrq).__name__=='int':
        flow_dsa.get_33strain(model_rs.dat_model.flow.epsilon[:,:,::nfrq])

    flow_dsa.get_eqv()
    sigma_wgt = flow_weight.sigma

    ## Various plots
    if iplot:
        for a in [ax1, ax_vm]:
            a.plot(flow_dsa.epsilon_vm,flow_dsa.sigma_vm,'k+',
                   label=r'$\hat{\sigma}^\mathrm{RS}$')
        for i in xrange(len(exp_ref)):
            f = exp_ref[i]; lab = exp_lab[i]
            edat = np.loadtxt(f).T
            ax1.plot(edat[0],edat[1],'-',lw=2,label=lab)
            ## ax1.set_ylim(0.,800)

        for a in [ax1,ax_vm]:
            fancy_legend(a,size=10,nscat=1)

        ax2.plot(sigma_wgt[0,0],sigma_wgt[1,1],'k-')
        ax2.plot(flow_dsa.sigma[0,0],flow_dsa.sigma[1,1],'k+')

        ## connector
        npoints = len(sigma_wgt[0,0])
        wgtx = sigma_wgt[0,0];      wgty = sigma_wgt[1,1]
        dsax = flow_dsa.sigma[0,0]; dsay = flow_dsa.sigma[1,1]
        # for i in xrange(npoints):
        #     ax2.plot([wgtx[i],dsax[i]],[wgty[i],dsay[i]],'k-',alpha=0.2)

        ax2.set_ylim(-100,700); ax2.set_xlim(-100,700)
        ax2.set_aspect('equal')
        ax2.set_xlabel(r'$\bar{\Sigma}_{11}$ [MPa]',dict(fontsize=15))
        ax2.set_ylabel(r'$\bar{\Sigma}_{22}$ [MPa]',dict(fontsize=15))
        ax2.locator_params(nbins=3)
        ax2.set_xticks(np.linspace(300,700,3),dict(fontsize=4))
        ax2.set_yticks(np.linspace(300,700,3),dict(fontsize=4))
        ax2.grid('on'); plt.show()

        ## save figures
        fig1.savefig('flow_%s_%s.pdf'%(hkl,path))
        fig_vm.savefig('all_flow_vm.pdf',  bbox_inches='tight')
        fig_vm.savefig('all_flow_vm.ps',  bbox_inches='tight')
        ## fig2.savefig('ehkl_%s_fit_%s.pdf'%(hkl,path))
        ## fig3.savefig('sf_%s_%s.pdf'%(hkl,path))
        ## fig4.savefig('ehkl_fit_err_%s_%s.pdf'%(hkl,path))
        # close figures
        try:
            figs=[fig1,fig2,fig3,fig4]
            for f in figs:
                try: plt.close(f)
                except: pass
        except: pass

    uet(time.time()-t0)
    print

    return model_rs, flow_weight, flow_dsa
예제 #5
0
파일: rs_ex.py 프로젝트: youngung/rs
def ex_consistency(
        ifig=50,nxphi=3,
        exp_ref=[],exp_lab=[],mod_ext=None,
        mod_ref='STR_STR.OUT',sin2psimx=None,
        iscatter=False,sigma=5e-5,psimx=None,psi_nbin=1,
        ig_sub=True,istep=None,hkl=None,iplot=True,
        iwind=False,wdeg=2,ipsi_opt=1,fn_sff=None,
        pmargin=None,path='',
        sf_ext=None,ig_ext=None,iwgt=False):
    """
    Consistency check between 'weighted average' stress and
    the stress obtained following the stress analysis method
    (SF, IG strain)

    ifig = 50
    nxphi     : display only first nxphi of results
                along phi axis
    exp_ref   : experimental reference
    mode_ref  : model's weighted average flow curves are given
    sin2psimx : limiting the maximum sin2psi values, with which
                stress-fitting is carried out
    iscatter (False) : introducing a random scattering of 'ehkl'
    psimx     : limiting the maximum psi value
    psi_nbin  : If other than 1, limit the number of data
    ig_sub    : flag whether or not subtract the IG strain
    istep     : If other than None, analysis is carried out
                for a specific istep
    hkl       : hkl of plane, for the sake of labels.
    iplot (True) : flag whether or not MPL plot is performed
    ipsi_opt 0: sin2psi
             1: sing(psi) * sin2psi
             2: psi
    pmargin   : portional margin of volume that should exceed to
                contribute to the ehkl/SF/IG in model_rs
    path      : place holder for strain path
    sf_ext    : Overwrite stress factor
    ig_ext    : Overwrite IG strain
    iwgt      : Whether or not accounting for 'weight'
    """
    from rs import ResidualStress,u_epshkl,filter_psi,\
        filter_psi2,psi_reso, psi_reso2, psi_reso3

    from MP.mat import mech # mech is a module
    FlowCurve = mech.FlowCurve

    if iplot:
        from matplotlib import pyplot as plt
        from matplotlib.backends.backend_pdf import PdfPages
        from MP.lib import mpl_lib,axes_label
        wide_fig     = mpl_lib.wide_fig
        fancy_legend = mpl_lib.fancy_legend

        ## Collection of figures at various plastic strains
        fe   = PdfPages('all_ehkl_fits_%s_%s.pdf'%(hkl,path))
        fs   = PdfPages('all_stress_factors_%s_%s.pdf'%(hkl,path))
        f_er = PdfPages('all_Ei-ehkl-e0_%s_%s.pdf'%(hkl,path))

        # fig1 is 'flow_**.pdf'
        fig1 = wide_fig(ifig,nw=2,nh=1,left=0.2,uw=3.5,
                        w0=0,w1=0.3,right=0,iarange=True)

        ## ax1: Equivalent Stress/Strain
        ## ax2: Stress path in the plane stress space (RD/TD)
        ax1 = fig1.axes[0]; ax2 = fig1.axes[1]
        ax2.set_axis_bgcolor('0.95')

    ## i_ip = 1: model case
    model_rs = ResidualStress(
        mod_ext=mod_ext,
        fnmod_ig='igstrain_fbulk_ph1.out',
        fnmod_sf='igstrain_fbulk_ph1.out',
        i_ip=1)

    ## masking array element based on diffraction volume
    model_rs.dat_model.mask_vol()
    if pmargin!=None:
        model_rs.dat_model.mask_vol_margin(pmargin)

    if mod_ext==None: mod_ref='STR_STR.OUT'
    else:             mod_ref='%s.%s'%(
            mod_ref.split('.')[0],mod_ext)

    flow_weight = FlowCurve(name='Model weighted')
    flow_weight.get_model(fn=mod_ref)
    flow_weight.get_eqv() ## calc Von Mises stress/strain

    if len(flow_weight.epsilon_vm)<5: lc='bx'
    else:                             lc='bx-'

    if iplot:
        ax1.plot(flow_weight.epsilon_vm,flow_weight.sigma_vm,
                 lc,label='Weighted avg',alpha=1.0)
        axes_label.__eqv__(ax1,ft=10)

    ## plot all stress factors at individual deformation levels
    stress = []
    print '%8s%8s%8s%8s%8s%8s'%(
        'S11','S22','S33','S23','S13','S12')

    for istp in range(model_rs.dat_model.nstp):
        """
        Dimensions of data arrays for:
        ==============================
        sf     (nstp, k, nphi, npsi)
        ig     (nstp, nphi, npsi)
        ehkl   (nstp, nphi, npsi)
        strain (nstp, 6)
        vf     (nstp, nphi, npsi)
        """
        model_rs.sf   = model_rs.dat_model.sf[istp]
        model_rs.eps0 = model_rs.dat_model.ig[istp]
        model_rs.ehkl = model_rs.dat_model.ehkl[istp]

        ## whether or not intergranular strain is subtracted.
        if ig_sub: model_rs.tdat = model_rs.ehkl - model_rs.eps0
        else:      model_rs.tdat = model_rs.ehkl
        tdat_ref = model_rs.tdat[::]

        ## Inducing 'scatters'
        if iscatter:
            tdat_scatter = []
            for iphi in range(len(tdat_ref)):
                dum = u_epshkl(tdat_ref[iphi],sigma=sigma)
                tdat_scatter.append(dum)
            tdat_scatter = np.array(tdat_scatter)
            model_rs.tdat = tdat_scatter

        model_rs.phis = model_rs.dat_model.phi
        model_rs.psis = model_rs.dat_model.psi
        model_rs.nphi = len(model_rs.phis)
        model_rs.npsi = len(model_rs.psis)
        wgt           = model_rs.dat_model.vf[istp][::]

        if sin2psimx!=None or psimx!=None:
            filter_psi(model_rs,sin2psimx=sin2psimx,psimx=psimx)
            wgt = filter_psi2(
                wgt,sin2psi=np.sin(model_rs.psis)**2,
                bounds =[0., sin2psimx])
            if sf_ext!=None:
                model_rs.sf = sf_ext[istp]
            elif ig_ext!=None:
                model_rs.ig = ig_ext[istp]

        if psi_nbin!=1:
            wgt = psi_reso3(wgt,psi=model_rs.psis,ntot=psi_nbin)
            psi_reso2(model_rs,ntot=psi_nbin)

        #-----------------------------------#
        ## find the sigma ...
        s11 = model_rs.dat_model.flow.sigma[0,0][istp]
        s22 = model_rs.dat_model.flow.sigma[1,1][istp]

        if iwgt: pass
        else: wgt = None # overwrite wgt

        dsa_sigma = model_rs.find_sigma(
            ivo=[0,1],
            init_guess=[0,0,0,0,0,0],
            #init_guess=[s11,s22,0,0,0,0],
            weight = wgt # None
            )

        for i in range(6): print '%+7.1f'%(dsa_sigma[i]),
        print ''
        stress.append(dsa_sigma)
        #-----------------------------------#
        if istp==0: ileg=True
        else:       ileg=False

        if (istep!=None and istp==istep) or\
           (istep==None and istp==model_rs.dat_model.nstp-1)\
           and iplot:
            fig2,fig3,fig4=__model_fit_plot__(
                model_rs,ifig=ifig+istp*2+10,
                istp=istp, nxphi=nxphi, stress_wgt=None,
                ivo=None,hkl=hkl,ileg=ileg,iwind=iwind,
                wdeg=wdeg)
        elif iplot:
            plt.ioff()
            f1,f2,f3=__model_fit_plot__(
                model_rs,ifig=ifig+istp*2+10,istp=istp,
                nxphi=nxphi,stress_wgt=[s11,s22,0,0,0,0],
                ivo=[0,1],hkl=hkl,ileg=ileg,iwind=False,
                ipsi_opt=ipsi_opt)
            fs.savefig(f2);fe.savefig(f1);f_er.savefig(f3)
            plt.close(f1);plt.close(f2);plt.close(f3)
            plt.ion()

    if iplot: fe.close(); fs.close(); f_er.close()

    stress   = np.array(stress).T # diffraction stress
    flow_dsa = FlowCurve(name='Diffraction Stress')
    flow_dsa.get_6stress(stress)
    flow_dsa.get_33strain(model_rs.dat_model.flow.epsilon)
    flow_dsa.get_eqv()
    if iplot:
        ax1.plot(flow_dsa.epsilon_vm,flow_dsa.sigma_vm,'k+',
                 label='Stress Analysis')
        for i in range(len(exp_ref)):
            f = exp_ref[i]; lab = exp_lab[i]
            edat = np.loadtxt(f).T
            ax1.plot(edat[0],edat[1],'-',lw=2,label=lab)
            ## ax1.set_ylim(0.,800)
        fancy_legend(ax1,size=10)

    sigma_wgt = flow_weight.sigma

    if iplot:
        ax2.plot(sigma_wgt[0,0],sigma_wgt[1,1],'bx')
        ax2.plot(flow_dsa.sigma[0,0],flow_dsa.sigma[1,1],'k+')

        ## connector
        npoints = len(sigma_wgt[0,0])
        wgtx = sigma_wgt[0,0];      wgty = sigma_wgt[1,1]
        dsax = flow_dsa.sigma[0,0]; dsay = flow_dsa.sigma[1,1]
        for i in range(npoints):
            ax2.plot([wgtx[i],dsax[i]],[wgty[i],dsay[i]],'k-',alpha=0.2)

        ax2.set_ylim(-100,700); ax2.set_xlim(-100,700)
        ax2.set_aspect('equal')
        ax2.set_xlabel(r'$\bar{\Sigma}_{11}$',dict(fontsize=15))
        ax2.set_ylabel(r'$\bar{\Sigma}_{22}$',dict(fontsize=15))
        ax2.locator_params(nbins=3)
        ax2.set_xticks(np.linspace(300,700,3),dict(fontsize=4))
        ax2.set_yticks(np.linspace(300,700,3),dict(fontsize=4))
        ax2.grid('on'); plt.show()

        ## save figures
        fig1.savefig('flow_%s_%s.pdf'%(hkl,path))
        ## fig2.savefig('ehkl_%s_fit_%s.pdf'%(hkl,path))
        ## fig3.savefig('sf_%s_%s.pdf'%(hkl,path))
        ## fig4.savefig('ehkl_fit_err_%s_%s.pdf'%(hkl,path))
        # close figures
        plt.close(fig1); plt.close(fig2); plt.close(fig3); plt.close(fig4)

    return model_rs, flow_weight, flow_dsa
예제 #6
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
예제 #7
0
def main_plot_flow_all(
        hkl='211',sin2psimx=0.5,psi_nbin=1,
        pmargin=None,iplot_rs=False,
        path=''):
    """
    Arguments
    =========
    hkl='211'
    sin2psimx
    psi_nbin = 1
    pmargin = None
    iplot_rs=False
    path=''
    """
    fns = read(hkl,prefix=path)
    if len(fns)==0:
        raise IOError, 'Check the path, 0 file was found'
    plt.ioff()
    fig = wf(nw=3,nh=1,left=0.2,uw=3.5,
             w0=0,w1=0.3,right=0,iarange=True)
    ax1,ax2,ax3 = fig.axes
    axes_label.__eqv__(ax1,ft=10)
    errors = []
    for i in xrange(len(fns)):
        fn = fns[i]
        strain_path = fn.split('_')[0]
        untargz(fn)
        model_rs, fwgt, fdsa \
            = rs_ex.ex_consistency(
                sin2psimx=sin2psimx,
                psi_nbin=psi_nbin,
                hkl=hkl,iplot=iplot_rs,
                pmargin=pmargin,path=path)
        fwgt.get_eqv(); fdsa.get_eqv()

        e = find_err(fwgt,fdsa)
        ax3.plot(fwgt.epsilon_vm,e)
        errors.append([fwgt.epsilon_vm,e])

        ax1.plot(fwgt.epsilon_vm,fwgt.sigma_vm,
                 'bx-',label='Weighted Avg', alpha=1.0)
        ax1.plot(fdsa.epsilon_vm,fdsa.sigma_vm,
                 'kx',label='Diff. Stress Analsysis', alpha=1.0)
        ax2.plot(fwgt.sigma[0,0],fwgt.sigma[1,1],'b+')
        ax2.plot(fdsa.sigma[0,0],fdsa.sigma[1,1],'k+')

        ## connector
        npoints = len(fwgt.sigma[0,0])
        wgtx = fwgt.sigma[0,0]; wgty = fwgt.sigma[1,1]
        dsax = fdsa.sigma[0,0]; dsay = fdsa.sigma[1,1]
        for j in xrange(npoints):
            ax2.plot([wgtx[j],dsax[j]],[wgty[j],dsay[j]],'k-',alpha=0.5)

    ax1.set_xlim(-0.1,1.1); ax1.set_ylim(-50,700);
    ax2.set_xlim(-10,1000); ax2.set_ylim(-10,1000)
    ax2.set_aspect('equal')
    ax2.set_xlabel(r'$\bar{\Sigma}_{11}$',dict(fontsize=15))
    ax2.set_ylabel(r'$\bar{\Sigma}_{22}$',dict(fontsize=15))
    ax2.locator_params(nbins=3)
    ax2.grid('on'); plt.show()

    plt.ion()
    plt.show();plt.draw()
    fn = 'flow_allpaths_%s.pdf'%(hkl)
    fig.savefig(fn)
    print '%s has been saved.'%fn
    plt.close(fig)

    return np.array(errors)[0]