Esempio n. 1
0
def calculate_rsquared(data,poisson,popt):
    if len(data)==0: return 0.0
    ydata = data[:,1]
    yfit  = prony(data[:,0],*popt)
    if poisson!=0.5:
        ydata = np.hstack((ydata,data[:,2]))
        yfit = np.hstack((yfit, prony(data[:,0],*popt)))
    return CF.rsquared(ydata,yfit)
Esempio n. 2
0
def calculate_rsquared(data, model, popt, t):
    if len(data) == 0: return 0.0
    for char in t:
        if not char in data: continue
        ydata = data[char][:, 1]
        yfit = MU.get_function(model, char)(data[char][:, 0], *popt)
        if 'yfits' in locals():
            ydatas = np.hstack((ydatas, ydata))
            yfits = np.hstack((yfits, yfit))
        else:
            ydatas = ydata
            yfits = yfit
    return CF.rsquared(ydatas, yfits)
Esempio n. 3
0
def calc_fit(OF,cmd,expdata,init_nc,interpBOOL,optfunc,*popt):
    fig,axis = pyplot.subplots(1,1)
    popt_display = np.abs(list(popt))
    popt_display[0] = calc_nc(popt[0],init_nc)
    print '\n********************************************************************'
    print '** Testing with parameters: ',popt_display
    print '********************************************************************'
    # Get the simulation results.
    if not hasattr(calc_fit, "iter"): calc_fit.iter=0
    simdata = optfunc((calc_fit.iter,)+popt)
    if len(simdata)==0:
        print '\n********************************************************************'
        print ' Abaqus failed, we return an average error of 1000.0'
        print '********************************************************************'
        calc_fit.iter = calc_fit.iter + 1
        pyplot.close()
        return 1000.0

    # Loop over multiple simulation results, if necessary.
    NP = 50
    errs = dict()
    cm = pyplot.get_cmap('jet')
    colors = [cm(float(i)/(2*len(simdata))) for i in range(2*len(simdata))]
    cidx = 0
    for T,sdata in simdata.iteritems():
        if T in expdata: edata=expdata[T]
        elif T.endswith('--strain'):
            if 'strain' in expdata: edata=expdata['strain']
            else: continue
        else: U.print_error('Failed to find comparison data for '+T,True)

        # Plot the simulation data.
        axis.plot(1000.0*sdata[:,0],sdata[:,1],'o-',color=colors[cidx],label='Sim '+T)

        # Interpolate the simulation results to remove zigzags and evenly space the points.
        # This is important because otherwise we may weight solutions very heavily at one point
        # in one solution, and completely differently in another.
        u,idx = np.unique(sdata[:,0],return_index=True)
        try:
            if interpBOOL:
                sim_smooth = np.zeros((NP,2))
                sim_smooth[:,0] = np.linspace(min(sdata[idx,0]),max(sdata[idx,0]),NP)
                # xvals = 1.0 - (np.logspace(0,np.log10(NP+1.0),NP,endpoint=True)-1.0)/(NP+1.0)
                # sim_smooth[:,0] = min(sdata[idx,0]) + (max(sdata[idx,0])-min(sdata[idx,0]))*xvals
            else:
                sim_smooth = np.zeros(edata.shape)
                sim_smooth[:,0] = edata[:,0]
            dataF = interp.UnivariateSpline(sdata[idx,0],sdata[idx,1],k=3,s=0)
            sim_smooth[:,1] = dataF(sim_smooth[:,0])
            # Remove any extrapolations, replace with the max calculated value.
            sim_smooth[sim_smooth[:,0]>max(sdata[:,0]),1] = max(sdata[:,1])
            axis.plot(1000.0*sim_smooth[:,0],sim_smooth[:,1],'.--',color=colors[cidx],label='Sim '+T+' (Smoothed)')
        except:
            print '** Failed to smooth simulation data. Proceding with untouched data.'
            sim_smooth = 1.0*sdata[idx,:]
            interpBOOL = True

        # Interpolate the experimental results to find comparable data.
        axis.plot(1000.0*edata[:,0],edata[:,1],'-',color=colors[cidx+1],label='Exp '+T)
        if interpBOOL:
            try:
                dataF = interp.UnivariateSpline(edata[:,0], edata[:,1],k=3,s=0)
                exp_smooth = np.zeros(sim_smooth.shape)
                exp_smooth[:,0] = sim_smooth[:,0]
                exp_smooth[:,1] = dataF(exp_smooth[:,0])
            except:
                U.print_error('Failed to fit a spline to experimental data, consider using the '
                              '--no_interpolate option or adding more datapoints.',True)
        else: exp_smooth = 1.0*edata
        axis.plot(1000.0*exp_smooth[:,0],exp_smooth[:,1],'.--',color=colors[cidx+1],label='Exp '+T+' (Smoothed)')

        # Make the comparison.
        # Try to handle a case where Abaqus failed early, but we have partial results.
        if max(sdata[:,0])<0.666*max(edata[:,0]):
            errs[T] = 1000.0 - 1000.0*max(sdata[:,0])/max(edata[:,0])
            print '\n********************************************************************'
            print ' Abaqus only reached',max(sdata[:,0]),' (out of '+str(max(edata[:,0]))+')!'
            print '********************************************************************'
        else:
            # For errors on max strain, no penalty for being too low.
            if T.endswith('--strain'):
                if max(exp_smooth[:,1])>=max(sim_smooth[:,1]): errs[T]=0.0
                else: errs[T] = 1.0 - CH.rsquared(exp_smooth,sim_smooth)
            else:
                errs[T] = 1.0 - CH.rsquared(exp_smooth,sim_smooth)
        cidx = cidx+2


    # Record to file.
    if calc_fit.iter==0:
        OF.write('# Each row shows the iteration #, the '+str(len(popt))+' parameters,\n')
        OF.write('# and then the '+str(len(errs.keys()))+' errors: '+str(errs.keys())+'\n')
    record_string = str(calc_fit.iter)+','
    for p in popt_display: record_string = record_string + str(p) + ','
    for err in errs.values(): record_string = record_string + str(err) + ','
    OF.write(record_string[:-1]+'\n')

    # Plot settings.
    if cmd=='act':
        axis.set_xlabel('Internal Pressure (kPa)')
        if len(simdata)>1: axis.set_ylabel('Displacement (mm) or Force (N)')
        else:
            if 'linU' in simdata or 'bndU' in simdata:   axis.set_ylabel('Displacement (mm)')
            elif 'linF' in simdata or 'bndF' in simdata: axis.set_ylabel('Force (N)')
    axis.grid()
    # Plot with the same axis every time.
    if not hasattr(calc_fit, "xlim"):
        calc_fit.xlim = axis.get_xlim()
        calc_fit.ylim = axis.get_ylim()
    axis.set_xlim(calc_fit.xlim)
    axis.set_ylim(calc_fit.ylim)
    axis.set_aspect(np.diff(calc_fit.xlim)/np.diff(calc_fit.ylim)) # Square axis.
    err_str = ', '.join("{:}:{:g}".format(key,val) for (key,val) in errs.iteritems())
    title = axis.set_title('\n'.join(textwrap.wrap(str(popt_display),100))+'\nitr='+str(calc_fit.iter)+'\nerrs=['+err_str+']\nerr_sum='+str(sum(errs.values())))
    title.set_y(1.05)
    fig.subplots_adjust(top=0.8)
    L = axis.legend(loc='best',frameon=False,framealpha=0)
    for legobj in L.legendHandles: legobj.set_linewidth(2.0)
    pyplot.tight_layout()
    pyplot.savefig('results--'+str(calc_fit.iter)+'.png')
    pyplot.savefig('results--latest.png')
    pyplot.close()
    print '\n********************************************************************'
    print ' Calculated sum-of-squares error:',errs,'=',sum(errs.values())
    print '********************************************************************'
    calc_fit.iter = calc_fit.iter + 1
    return sum(errs.values())
def calc_fit(act,test,cmd,expdata,matdata,testfunc,*popt):
    fig,ax = pyplot.subplots(1,2,figsize=(10,6))
    print '\n********************************************************************'
    print '** Testing with parameters: ',popt
    print '********************************************************************'
    # Get the simulation results.
    if not hasattr(calc_fit, "iter"): calc_fit.iter=0
    simdata = testfunc((calc_fit.iter,)+popt)
    if len(simdata)==0:
        print '\n********************************************************************'
        print ' Abaqus failed, we return an average error of 1000.0'
        print '********************************************************************'
        calc_fit.iter = calc_fit.iter + 1
        return 1000.0

    # Loop over multiple simulation results, if necessary.
    NP = 50
    errs = dict()
    cm = pyplot.get_cmap('jet')
    colors = [cm(float(i)/(2*len(simdata))) for i in range(2*len(simdata))]
    cidx = 0
    for T,sdata in simdata.iteritems():
        # Plot the simulation data.
        ax[0].plot(1000.0*sdata[:,0],sdata[:,1],'o-',color=colors[cidx],label='Sim '+T)

        # Interpolate the simulation results to remove zigzags and evenly space the points.
        # This is important because otherwise we may weight solutions very heavily at one point
        # in one solution, and completely differently in another.
        u,idx = np.unique(sdata[:,0],return_index=True)
        try:
            sim_smooth = np.zeros((NP,2))
            # sim_smooth[:,0] = np.linspace(min(sdata[idx,0]),max(sdata[idx,0]),NP)
            xvals = 1.0 - (np.logspace(0,np.log10(NP+1.0),NP,endpoint=True)-1.0)/(NP+1.0)
            sim_smooth[:,0] = min(sdata[idx,0]) + (max(sdata[idx,0])-min(sdata[idx,0]))*xvals
            dataF = interp.UnivariateSpline(sdata[idx,0],sdata[idx,1],k=3,s=0)
            sim_smooth[:,1] = dataF(sim_smooth[:,0])
            ax[0].plot(1000.0*sim_smooth[:,0],sim_smooth[:,1],'.--',color=colors[cidx],label='Sim '+T+' (Smoothed)')
        except:
            print '** Failed to smooth simulation data. Proceding with untouched data.'
            sim_smooth = 1.0*sdata[idx,:]

        # Interpolate the experimental results to find comparable data.
        edata = expdata[T]
        ax[0].plot(1000.0*edata[:,0],edata[:,1],'-',color=colors[cidx+1],label='Exp '+T)
        dataF = interp.UnivariateSpline(edata[:,0], edata[:,1],k=3,s=0)
        exp_smooth = np.zeros(sim_smooth.shape)
        exp_smooth[:,0] = sim_smooth[:,0]
        exp_smooth[:,1] = dataF(exp_smooth[:,0])
        ax[0].plot(1000.0*exp_smooth[:,0],exp_smooth[:,1],'.--',color=colors[cidx+1],label='Exp '+T+' (Smoothed)')

        # Make the comparison.
        # Try to handle a case where Abaqus failed early, but we have partial results.
        if max(sdata[:,0])<0.666*max(edata[:,0]):
            errs[T] = 1000.0 - 1000.0*max(sdata[:,0])/max(edata[:,0])
            print '\n********************************************************************'
            print ' Abaqus only reached',max(sdata[:,0]),' (out of '+str(max(edata[:,0]))+')!'
            print '********************************************************************'
        else:
            # errs[T] = np.linalg.norm((exp_smooth[:,1]-sim_smooth[:,1])/max(edata[:,1]))
            errs[T] = 1.0 - CH.rsquared(exp_smooth,sim_smooth)
        cidx = cidx+2

    # Plot the model uniaxial, biaxial, and planar curves.
    if cmd!='vis':
        for t in 'ubp':
            if not t in matdata: continue
            dataF = interp.interp1d(matdata[t][:,0], matdata[t][:,1], kind='nearest', bounds_error=False, fill_value=0.0)
            vals = np.zeros((NP,3))
            vals[:,0] = np.linspace(min(matdata[t][:,0]),max(matdata[t][:,0]),NP)
            vals[:,1] = dataF(vals[:,0])
            vals[:,2] = MU.get_function(model,t)(vals[:,0],*popt)  # splat operator.
            # errs['mat_'+t] = np.linalg.norm((vals[:,1]-vals[:,2])/max(matdata[t][:,1]))
            errs['mat_'+t] = 1.0 - CH.rsquared(vals[:,1],vals[:,2])
        CHP.plot_data(ax[1],model,matdata,popt,[0,4],[0,.25])
        ax[1].set_aspect(np.diff(ax[1].get_xlim())/np.diff(ax[1].get_ylim())) # Square axis.


    # Plot settings.
    if cmd=='mat':
        ax[0].set_xlabel('Engineering Strain')
        ax[0].set_ylabel(r'Nominal Stress $\left({}^N\!/{}_{mm^2}\right)$')
    elif cmd=='act' or cmd=='vis':
        ax[0].set_xlabel('Internal Pressure (kPa)')
        if len(simdata)>1: ax[0].set_ylabel('Displacement (mm) or Force (N)')
        else:
            if 'linU' in simdata or 'bndU' in simdata:   ax[0].set_ylabel('Displacement (mm)')
            elif 'linF' in simdata or 'bndF' in simdata: ax[0].set_ylabel('Force (N)')
    ax[0].grid()
    # Plot with the same axis every time.
    if not hasattr(calc_fit, "xlim"):
        calc_fit.xlim = ax[0].get_xlim()
        calc_fit.ylim = ax[0].get_ylim()
    ax[0].set_xlim(calc_fit.xlim)
    ax[0].set_ylim(calc_fit.ylim)
    ax[0].set_aspect(np.diff(calc_fit.xlim)/np.diff(calc_fit.ylim)) # Square axis.
    # ax[0].set_aspect(abs(xlim[1]-xlim[0])/abs(ylim[1]-ylim[0])) # Square axis.
    pyplot.suptitle('\n'.join(textwrap.wrap(str(popt),100))+'\nitr='+str(calc_fit.iter)+'\nerrs='+str(errs)+'\nerr_sum='+str(sum(errs.values())))
    L = ax[0].legend(loc='best',frameon=False,framealpha=0)
    for legobj in L.legendHandles: legobj.set_linewidth(2.0)
    pyplot.tight_layout()
    pyplot.savefig('results--'+str(calc_fit.iter)+'.png')
    pyplot.savefig('results--latest.png')
    pyplot.close()
    print '\n********************************************************************'
    print ' Calculated sum-of-squares error:',errs,'=',sum(errs.values())
    print '********************************************************************'
    calc_fit.iter = calc_fit.iter + 1
    return sum(errs.values())