Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
0
def DEC_evol(steps = [0,6,9,19]):
    """
    Draw evolution of DECs with respect to plastic deformation
    """
    from MP.mat import mech # mech is a module
    FlowCurve = mech.FlowCurve
    from mst_ex import use_intp_sfig, return_vf
    from rs import ResidualStress, filter_psi3
    model_rs = ResidualStress(
        mod_ext=None,fnmod_ig='igstrain_fbulk_ph1.out',
        fnmod_sf='igstrain_fbulk_ph1.out',i_ip=1)
    fc = FlowCurve(name='Weighted Average')
    fc.get_model(fn='STR_STR.OUT')
    fc.get_eqv()

    phi = model_rs.dat_model.phi
    nphi = model_rs.dat_model.nphi
    psi = model_rs.dat_model.psi
    sin2psi = sin2psi_opt(psi,1)
    DEC_raw = model_rs.dat_model.sf.copy()
    vf_raw, dum = return_vf()
    DEC_raw, psi, sin2psi, vf_raw = filter_psi3(
        sin2psi.copy(), [-0.5,0.5],
        DEC_raw, psi.copy(), sin2psi.copy(), vf_raw.copy())

    ## filter DEC_raw
    DEC_raw[DEC_raw==0]=np.nan
    evm = fc.epsilon_vm.copy()
    nstp = fc.nstp
    fig = plt.figure()
    # steps = [0,3,5,9]
    nstp = len(steps)
    gs=gridspec.GridSpec(
        nstp,nphi,
        wspace=0,hspace=0,left=0.25,right=0.8,top=0.8)

    axes=[]; axev=[]; axs=[]; axv=[]
    for i in range(len(steps)):
        axes.append([])
        axev.append([])
        for j in range(nphi):
            ax = fig.add_subplot(gs[i,j])
            av = ax.twinx()

            axs.append(ax);axes[i].append(ax); axv.append(av); axev[i].append(av)
            ax.locator_params(nbins=4)
            lab1 = r'$\mathbb{F}_{11}$'; lab2 = r'$\mathbb{F}_{22}$'
            ax.plot(sin2psi, DEC_raw[steps[i],0,j,:]*1e6,'k-',label=lab1)
            ax.plot(sin2psi, DEC_raw[steps[i],1,j,:]*1e6,'-',color='gray',label=lab2)
            av.plot(sin2psi, vf_raw[steps[i],j,:],color='gray',linewidth=3,alpha=0.7)
            ax.plot(0,0,'-',color='gray',linewidth=3,alpha=0.7,label='Vol. F')

            if i==len(steps)-1 and j==0: pass
            else:
                mpl_lib.rm_lab(ax,axis='x')
                mpl_lib.rm_lab(ax,axis='y')

            if i==len(steps)-1 and j==nphi-1: pass
            else:
                mpl_lib.rm_lab(av,axis='x')
                mpl_lib.rm_lab(av,axis='y')

    tune_xy_lim(axs)
    tune_x_lim(axs,axis='y')
    tune_xy_lim(axv)
    tune_x_lim(axv,axis='y')

    for i in range(len(steps)):#range(nstp):
        if i ==0: s = r'$\bar{E}^{VM}=%.2f$'%fc.epsilon_vm[steps[i]]
        else:    s = r'$%.2f$'%fc.epsilon_vm[steps[i]]
        axes[i][-1].annotate(
            s=s,
            verticalalignment='center',
            horizontalalignment='center',
            rotation=270,
            size=10,xy=(1.60,0.5),
            xycoords='axes fraction')

    for j in range(nphi):
        s = r'$\phi=%.1f^\circ{}$'%(phi[j]*180./np.pi)
        axes[0][j].annotate(
            s=s,
            horizontalalignment='center',
            size=10,xy=(0.5,1.2),
            xycoords='axes fraction')



    fancy_legend(axes[0][0],size=10,nscat=1,ncol=1,
                 bbox_to_anchor=(-0.1,1))
    deco(ax=axes[-1][0],ft=10,iopt=1,hkl='211',ipsi_opt=1)
    deco(ax=axev[-1][-1],ft=10,iopt=7,hkl='211',ipsi_opt=1)
    axev[-1][-1].grid('off');

    for i in range(len(axv)):
        axv[i].set_ylim(0.,0.3)
        axv[i].locator_params(nbins=4)

    fig.savefig("dec_evol.pdf")
    fig.savefig("dec_evol.png")
Exemplo n.º 4
0
def DEC_evol(steps=[0, 6, 9, 19]):
    """
    Draw evolution of DECs with respect to plastic deformation
    """
    from MP.mat import mech  # mech is a module
    FlowCurve = mech.FlowCurve
    from mst_ex import use_intp_sfig, return_vf
    from rs import ResidualStress, filter_psi3
    model_rs = ResidualStress(mod_ext=None,
                              fnmod_ig='igstrain_fbulk_ph1.out',
                              fnmod_sf='igstrain_fbulk_ph1.out',
                              i_ip=1)
    fc = FlowCurve(name='Weighted Average')
    fc.get_model(fn='STR_STR.OUT')
    fc.get_eqv()

    phi = model_rs.dat_model.phi
    nphi = model_rs.dat_model.nphi
    psi = model_rs.dat_model.psi
    sin2psi = sin2psi_opt(psi, 1)
    DEC_raw = model_rs.dat_model.sf.copy()
    vf_raw, dum = return_vf()
    DEC_raw, psi, sin2psi, vf_raw = filter_psi3(sin2psi.copy(), [-0.5, 0.5],
                                                DEC_raw, psi.copy(),
                                                sin2psi.copy(), vf_raw.copy())

    ## filter DEC_raw
    DEC_raw[DEC_raw == 0] = np.nan
    evm = fc.epsilon_vm.copy()
    nstp = fc.nstp
    fig = plt.figure()
    # steps = [0,3,5,9]
    nstp = len(steps)
    gs = gridspec.GridSpec(nstp,
                           nphi,
                           wspace=0,
                           hspace=0,
                           left=0.25,
                           right=0.8,
                           top=0.8)

    axes = []
    axev = []
    axs = []
    axv = []
    for i in xrange(len(steps)):
        axes.append([])
        axev.append([])
        for j in xrange(nphi):
            ax = fig.add_subplot(gs[i, j])
            av = ax.twinx()

            axs.append(ax)
            axes[i].append(ax)
            axv.append(av)
            axev[i].append(av)
            ax.locator_params(nbins=4)
            lab1 = r'$\mathbb{F}_{11}$'
            lab2 = r'$\mathbb{F}_{22}$'
            ax.plot(sin2psi,
                    DEC_raw[steps[i], 0, j, :] * 1e6,
                    'k-',
                    label=lab1)
            ax.plot(sin2psi,
                    DEC_raw[steps[i], 1, j, :] * 1e6,
                    '-',
                    color='gray',
                    label=lab2)
            av.plot(sin2psi,
                    vf_raw[steps[i], j, :],
                    color='gray',
                    linewidth=3,
                    alpha=0.7)
            ax.plot(0,
                    0,
                    '-',
                    color='gray',
                    linewidth=3,
                    alpha=0.7,
                    label='Vol. F')

            if i == len(steps) - 1 and j == 0: pass
            else:
                mpl_lib.rm_lab(ax, axis='x')
                mpl_lib.rm_lab(ax, axis='y')

            if i == len(steps) - 1 and j == nphi - 1: pass
            else:
                mpl_lib.rm_lab(av, axis='x')
                mpl_lib.rm_lab(av, axis='y')

    tune_xy_lim(axs)
    tune_x_lim(axs, axis='y')
    tune_xy_lim(axv)
    tune_x_lim(axv, axis='y')

    for i in xrange(len(steps)):  #range(nstp):
        if i == 0: s = r'$\bar{E}^{VM}=%.2f$' % fc.epsilon_vm[steps[i]]
        else: s = r'$%.2f$' % fc.epsilon_vm[steps[i]]
        axes[i][-1].annotate(s=s,
                             verticalalignment='center',
                             horizontalalignment='center',
                             rotation=270,
                             size=10,
                             xy=(1.60, 0.5),
                             xycoords='axes fraction')

    for j in xrange(nphi):
        s = r'$\phi=%.1f^\circ{}$' % (phi[j] * 180. / np.pi)
        axes[0][j].annotate(s=s,
                            horizontalalignment='center',
                            size=10,
                            xy=(0.5, 1.2),
                            xycoords='axes fraction')

    fancy_legend(axes[0][0],
                 size=10,
                 nscat=1,
                 ncol=1,
                 bbox_to_anchor=(-0.1, 1))
    deco(ax=axes[-1][0], ft=10, iopt=1, hkl='211', ipsi_opt=1)
    deco(ax=axev[-1][-1], ft=10, iopt=7, hkl='211', ipsi_opt=1)
    axev[-1][-1].grid('off')

    for i in xrange(len(axv)):
        axv[i].set_ylim(0., 0.3)
        axv[i].locator_params(nbins=4)

    fig.savefig("dec_evol.pdf")
    fig.savefig("dec_evol.png")