Example #1
0
def fegrab(el,ns,set_id,wrt_file):
    
    ### FINITE ELEMENT RESPONSES ###
    start = time.time()    
    
    resp = np.zeros([ns,el**3])   
    for sn in xrange(ns):
        filename = "sq%s_%s%s_%s.dat" %(el,ns,set_id,sn+1)        
        resp[sn,...] = rr.res_red(filename,el,sn)
    
    np.save('r_%s%s' %(ns,set_id),resp)  
    
    end = time.time()
    timeE = np.round((end - start),3)    
    msg = 'Load FE results from .dat files for set %s%s: %s seconds' %(ns,set_id,timeE)
    rr.WP(msg,wrt_file)
    
    ## responses in frequency space
    start = time.time()
    
    resp_fft = np.fft.fftn(resp.reshape([ns,el,el,el]), axes = [1,2,3]) 
    del resp
    np.save('r_fft_%s%s' %(ns,set_id),resp_fft)  
    
    end = time.time()
    timeE = np.round((end - start),3)
    msg = 'Convert FE results to frequency space for set %s%s: %s seconds' %(ns,set_id,timeE)
    rr.WP(msg,wrt_file)
def calibration_procedure(el, ns, H, set_id, wrt_file):

    M = np.load('M_%s%s.npy' % (ns, set_id))
    r_fft = np.load('r_fft_%s%s.npy' % (ns, set_id))

    start = time.time()

    specinfc = np.zeros((H, el**3), dtype='complex64')

    # here we perform the calibration
    specinfc[:, 0] = rr.calib(0, M, r_fft, 0, H, el, ns)
    [specinfc[:, 1], p] = rr.calib(1, M, r_fft, 0, H, el, ns)

    # calib_red is simply calib with some default arguments
    calib_red = partial(rr.calib, M=M, r_fft=r_fft, p=p, H=H, el=el, ns=ns)

    specinfc[:, 2:(el**3)] = np.asarray(map(calib_red,
                                            range(2, el**3))).swapaxes(0, 1)

    np.save('specinfc_%s%s' % (ns, set_id), specinfc)

    end = time.time()
    timeE = np.round((end - start), 3)
    msg = 'Calibration: %s seconds' % timeE
    rr.WP(msg, wrt_file)
def msf(el, ns, Hi, H, order, set_id, wrt_file):

    start = time.time()

    # import microstructures
    tmp = np.zeros([Hi, ns, el**3])
    microstructure = sio.loadmat('M_%s%s.mat' % (ns, set_id))['M']
    microstructure = microstructure.swapaxes(0, 1)

    for h in xrange(Hi):
        tmp[h, ...] = (microstructure == h).astype(int)

    del microstructure

    tmp = tmp.swapaxes(0, 1)
    pre_micr = tmp.reshape([ns, Hi, el, el, el])

    del tmp

    np.save('pre_msf_%s%s' % (ns, set_id), pre_micr)

    micr = rr.mf(pre_micr, el, ns, Hi, H, order)
    del pre_micr

    np.save('msf_%s%s' % (ns, set_id), micr)

    end = time.time()
    timeE = np.round((end - start), 3)
    msg = "generate real-space microstructure function: %s seconds" % timeE
    rr.WP(msg, wrt_file)

    # Microstructure functions in frequency space
    start = time.time()

    M = np.fft.fftn(micr, axes=[2, 3, 4])

    del micr
    size = M.nbytes
    np.save('M_%s%s' % (ns, set_id), M)

    end = time.time()
    timeE = np.round((end - start), 3)

    msg = "FFT3 conversion of micr to M_%s%s: %s seconds" % (ns, set_id, timeE)
    rr.WP(msg, wrt_file)
    msg = 'Size of M_%s%s: %s bytes' % (ns, set_id, size)
    rr.WP(msg, wrt_file)
Example #4
0
def fegrab(el, ns, set_id, direc, wrt_file):

    # FINITE ELEMENT RESPONSES
    start = time.time()

    resp = np.zeros([ns, el**3])

    nwd = os.getcwd() + '/' + direc  # for unix
    # nwd = os.getcwd() + '\\' + direc
    os.chdir(nwd)

    for sn in xrange(ns):
        filename = "sq%s_%s%s_%s.dat" % (el, ns, set_id, sn + 1)
        resp[sn, ...] = rr.res_red(filename, el, sn)

    os.chdir('..')

    np.save('r_%s%s' % (ns, set_id), resp)

    end = time.time()
    timeE = np.round((end - start), 3)
    msg = 'Load FE results from .dat files for set %s%s: %s seconds' \
        % (ns, set_id, timeE)
    rr.WP(msg, wrt_file)

    # responses in frequency space
    start = time.time()

    resp_fft = np.fft.fftn(resp.reshape([ns, el, el, el]), axes=[1, 2, 3])
    del resp
    np.save('r_fft_%s%s' % (ns, set_id), resp_fft)

    print "selection of resp_fft"
    print resp_fft[0, 10, 10, 5:10]

    end = time.time()
    timeE = np.round((end - start), 3)
    msg = 'Convert FE results to frequency space for set %s%s: %s seconds' \
        % (ns, set_id, timeE)
    rr.WP(msg, wrt_file)
Example #5
0
def msf(el, ns, H, set_id, wrt_file):

    start = time.time()

    ## import microstructures
    pre_micr = np.zeros([el**3, ns, H])
    microstructure = sio.loadmat('M_%s%s.mat' % (ns, set_id))['M']

    for h in xrange(H):
        pre_micr[..., h] = (microstructure == h).astype(int)

    del microstructure

    micr = np.swapaxes(pre_micr[::-1, ...].reshape([el, el, el, ns, H]), 1, 2)

    del pre_micr

    np.save('msf_%s%s' % (ns, set_id), micr)

    end = time.time()
    timeE = np.round((end - start), 3)
    msg = "generate real-space microstructure function from GSH-coefficients: %s seconds" % timeE
    rr.WP(msg, wrt_file)

    ## Microstructure functions in frequency space
    start = time.time()

    M = np.fft.fftn(micr, axes=[0, 1, 2])
    del micr
    size = M.nbytes
    np.save('M_%s%s' % (ns, set_id), M)

    end = time.time()
    timeE = np.round((end - start), 3)

    msg = "FFT3 conversion of micr to M_%s%s: %s seconds" % (ns, set_id, timeE)
    rr.WP(msg, wrt_file)
    msg = 'Size of M_%s%s: %s bytes' % (ns, set_id, size)
    rr.WP(msg, wrt_file)
Example #6
0
def results(el, ns, set_id, typ, wrt_file):

    # vector of the indicial forms of the tensor components
    real_comp = '11'

    mks_R = np.load('mksR_%s%s.npy' % (ns, set_id))
    resp = np.load('r_%s%s.npy' % (ns, set_id)).reshape([ns, el, el, el])
    micr = np.load('pre_msf_%s%s.npy' % (ns, set_id))

    maxindx = np.unravel_index(np.argmax(np.abs(resp - mks_R)), resp.shape)
    maxresp = resp[maxindx]
    maxMKS = mks_R[maxindx]
    maxerr = (np.abs(resp - mks_R)[maxindx] / np.mean(resp)) * 100

    print 'indices of max error'
    print maxindx
    print 'reference response at max error'
    print maxresp
    print 'MKS response at max error'
    print maxMKS
    print 'maximum error'
    print maxerr
    print micr[maxindx[0], :, maxindx[1], maxindx[2], maxindx[3]]

    # VISUALIZATION OF MKS VS. FEM

    # pick a slice perpendicular to the x-direction
    slc = maxindx[1]
    sn = maxindx[0]

    # slc = 10
    # sn = 130

    # Plot slices of the response
    plt.figure(num=2, figsize=[16, 8])

    dmin = np.min([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])
    dmax = np.max([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])

    plt.subplot(231)
    ax = plt.imshow(micr[sn, 0, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet')
    plt.colorbar(ax)
    plt.title('phase map, slice %s' % (slc))

    plt.subplot(232)
    ax = plt.imshow(mks_R[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('MKS $\%s_{%s}$ response, slice %s' % (typ, real_comp, slc))

    plt.subplot(233)
    ax = plt.imshow(resp[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('FEM $\%s_{%s}$ response, slice %s' % (typ, real_comp, slc))

    # Plot a histogram representing the frequency of strain levels with
    # separate channels for each phase of each type of response.
    plt.subplot(212)

    # find the min and max of both datasets (in full)
    dmin = np.amin([resp, mks_R])
    dmax = np.amax([resp, mks_R])

    micr0 = micr[:, 0, :, :, :].reshape(ns * el * el * el).astype(int)

    resp_lin = resp.reshape(ns * el * el * el)
    mks_lin = mks_R.reshape(ns * el * el * el)

    tmp = np.nonzero(micr0)
    feb = resp_lin[tmp]
    mks1b = mks_lin[tmp]

    tmp = np.nonzero(micr0 == 0)
    few = resp_lin[tmp]
    mks1w = mks_lin[tmp]

    # select the desired number of bins in the histogram
    bn = 40

    # FEM histogram
    n, bins, patches = plt.hist(feb,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    bincenters = 0.5 * (bins[1:] + bins[:-1])
    febp, = plt.plot(bincenters, n, 'k', linestyle='--', lw=1.5)

    n, bins, patches = plt.hist(few,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    fewp, = plt.plot(bincenters, n, 'k')

    # MKS histogram
    n, bins, patches = plt.hist(mks1b,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    mks1bp, = plt.plot(bincenters, n, 'b', linestyle='--', lw=1.5)

    n, bins, patches = plt.hist(mks1w,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    mks1wp, = plt.plot(bincenters, n, 'b')

    plt.grid(True)

    plt.legend([febp, fewp, mks1bp, mks1wp], [
        "FE - stiff phase", "FE - compliant phase", "MKS - stiff phase",
        "MKS - compliant phase"
    ])

    plt.xlabel("Strain")
    plt.ylabel("Frequency")
    plt.title("Frequency comparison MKS with FE results")

    plt.show()

    # MEAN ABSOLUTE STRAIN ERROR (MASE)
    avgr_fe_tot = 0
    avgr_mks_tot = 0
    max_diff_all = np.zeros(ns)

    for sn in xrange(ns):
        avgr_fe_indv = np.average(resp[sn, ...])
        avgr_mks_indv = np.average(mks_R[sn, ...])

        avgr_fe_tot += avgr_fe_indv
        avgr_mks_tot += avgr_mks_indv
        max_diff_all[sn] = np.amax(abs(resp[sn, ...] - mks_R[sn, ...]))

    avgr_fe = avgr_fe_tot / ns
    avgr_mks = avgr_mks_tot / ns

    # DIFFERENCE MEASURES
    mean_diff_meas = np.mean(abs(resp - mks_R)) / avgr_fe
    mean_max_diff_meas = np.mean(max_diff_all) / avgr_fe
    max_diff_meas_all = np.amax(abs(resp - mks_R)) / avgr_fe

    msg = 'Mean voxel difference over all microstructures'\
        ' (divided by mean von-Mises meas), %s%s: %s%%' \
        % (typ, real_comp, mean_diff_meas*100)
    rr.WP(msg, wrt_file)
    msg = 'Average Maximum voxel difference per microstructure'\
        ' (divided by mean von-Mises meas), %s%s: %s%%' \
        % (typ, real_comp, mean_max_diff_meas*100)
    rr.WP(msg, wrt_file)
    msg = 'Maximum voxel difference in all microstructures '\
        '(divided by mean von-Mises meas), %s%s: %s%%' \
        % (typ, real_comp, max_diff_meas_all*100)
    rr.WP(msg, wrt_file)

    # STANDARD STATISTICS
    msg = 'Average, %s%s, FEM: %s' % (typ, real_comp, avgr_fe)
    rr.WP(msg, wrt_file)
    msg = 'Average, %s%s, MKS: %s' % (typ, real_comp, avgr_mks)
    rr.WP(msg, wrt_file)
    msg = 'Standard deviation, %s%s, FEM: %s' \
        % (typ, real_comp, np.std(resp))
    rr.WP(msg, wrt_file)
    msg = 'Standard deviation, %s%s, MKS: %s' \
        % (typ, real_comp, np.std(mks_R))
    rr.WP(msg, wrt_file)

    resp_min = np.mean(np.amin(resp.reshape([el**3, ns]), axis=0))
    mks_R_min = np.mean(np.amin(mks_R.reshape([el**3, ns]), axis=0))

    resp_max = np.mean(np.amax(resp.reshape([el**3, ns]), axis=0))
    mks_R_max = np.mean(np.amax(mks_R.reshape([el**3, ns]), axis=0))

    msg = 'Mean minimum, %s%s, FEM: %s' % (typ, real_comp, resp_min)
    rr.WP(msg, wrt_file)
    msg = 'Mean minimum, %s%s, MKS: %s' % (typ, real_comp, mks_R_min)
    rr.WP(msg, wrt_file)
    msg = 'Mean maximum, %s%s, FEM: %s' % (typ, real_comp, resp_max)
    rr.WP(msg, wrt_file)
    msg = 'Mean maximum, %s%s, MKS: %s' % (typ, real_comp, mks_R_max)
    rr.WP(msg, wrt_file)
Example #7
0
def fip_calc(el, ns, set_id, wrt_file):

    mks_R = np.load('mksR_%s%s.npy' % (ns, set_id))
    resp = np.load('r_%s%s.npy' % (ns, set_id)).reshape([ns, el, el, el])
    micr = np.load('pre_msf_%s%s.npy' % (ns, set_id))

    # DEFINE RELEVANT PARAMETERS

    typ = 'epsilon'
    real_comp = '11'

    y_0 = 0.1  # phase 0 yield point
    y_1 = 0.125  # phase 1 yield point
    E_0 = 100  # phase 0 Young's Modulus
    E_1 = 100  # phase 1 Young's Modulus

    K = 1000.0  # constant in F-S parameter

    ey_0 = y_0 / E_0  # strain at yield for phase 0
    ey_1 = y_1 / E_1  # strain at yield for phase 1

    # CALCULATE THE PLASTIC AND ELASTIC STRAIN DISTRIBUTIONS

    # FEM results

    # plastic strain phase 0
    ep_0 = micr[:, 0, ...] * resp - ey_0 * micr[:, 0, ...] > 0
    ep_0 = ep_0 * (resp - ey_0 * micr[:, 0, ...])
    ee_0 = micr[:, 0, ...] * resp - ep_0  # elastic strain phase 0

    # plastic strain phase 1
    ep_1 = micr[:, 1, ...] * resp - ey_1 * micr[:, 1, ...] > 0
    ep_1 = ep_1 * (resp - ey_1 * micr[:, 1, ...])
    ee_1 = micr[:, 1, ...] * resp - ep_1  # elastic strain phase 1

    ep_t = ep_0 + ep_1  # plastic strain for both phases
    ee_t = ee_0 + ee_1  # elastic strain for both phases

    # calculate the FIP
    FIP_0 = ep_0 * (micr[:, 0, ...] + K * ((E_0 * ee_0) / y_0))
    FIP_1 = ep_1 * (micr[:, 1, ...] + K * ((E_1 * ee_1) / y_1))
    FIP_t = FIP_0 + FIP_1

    # MKS results

    ep_0_mks = micr[:, 0, ...] * mks_R - ey_0 * micr[:, 0, ...] > 0
    ep_0_mks = ep_0_mks * (mks_R - ey_0 * micr[:, 0, ...])
    ee_0_mks = micr[:, 0, ...] * mks_R - ep_0  # elastic strain phase 0

    # plastic strain phase 1
    ep_1_mks = micr[:, 1, ...] * mks_R - ey_1 * micr[:, 1, ...] > 0
    ep_1_mks = ep_1_mks * (mks_R - ey_1 * micr[:, 1, ...])
    ee_1_mks = micr[:, 1, ...] * mks_R - ep_1  # elastic strain phase 1

    ep_t_mks = ep_0_mks + ep_1_mks  # plastic strain for both phases
    ee_t_mks = ee_0_mks + ee_1_mks  # elastic strain for both phases

    # CALCULATE ERROR IN PLASTIC STRAIN PREDICTION

    avgr_fe_tot = 0
    max_diff_all = np.zeros(ns)

    for sn in xrange(ns):
        avgr_fe_indv = np.average(ep_t[sn, ...])

        avgr_fe_tot += avgr_fe_indv
        max_diff_all[sn] = np.amax(abs(ep_t[sn, ...] - ep_t_mks[sn, ...]))

    avgr_fe = avgr_fe_tot / ns

    # difference measure
    # mean_diff_meas = np.mean(abs(ep_t-ep_t_mks))/avgr_fe
    # mean_max_diff_meas = np.mean(max_diff_all)/avgr_fe
    # max_diff_meas_all = np.amax(abs(ep_t-ep_t_mks))/avgr_fe

    mean_diff_meas = np.mean(abs(ep_t - ep_t_mks)) / 0.000125
    mean_max_diff_meas = np.mean(max_diff_all) / 0.000125
    max_diff_meas_all = np.amax(abs(ep_t - ep_t_mks)) / 0.000125

    msg = 'Mean plastic strain:, %s%%' % avgr_fe
    rr.WP(msg, wrt_file)

    msg = 'Mean voxel difference over all microstructures'\
        ' (normalized by mean strain), %s%sp: %s%%' \
        % (typ, real_comp, mean_diff_meas*100)
    rr.WP(msg, wrt_file)

    msg = 'Average Maximum voxel difference per microstructure'\
        ' (normalized by mean strain), %s%sp: %s%%' \
        % (typ, real_comp, mean_max_diff_meas*100)
    rr.WP(msg, wrt_file)

    msg = 'Maximum voxel difference in all microstructures '\
        '(normalized by mean strain), %s%sp: %s%%' \
        % (typ, real_comp, max_diff_meas_all*100)
    rr.WP(msg, wrt_file)

    # PLOT THE STRAIN FIELDS

    # find indices of max error and use them for plotting
    maxindx = np.unravel_index(np.argmax(np.abs(ep_t - ep_t_mks)), ep_t.shape)
    slc = maxindx[1]
    sn = maxindx[0]

    # choose indices for plotting
    # slc = 10
    # sn = 100

    # Plot slices of the response
    plt.figure(num=3, figsize=[11, 8])

    dmin = np.min([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])
    dmax = np.max([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])

    plt.subplot(221)
    ax = plt.imshow(micr[sn, 0, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet')
    plt.colorbar(ax)
    plt.title('phase map, slice %s' % (slc))

    plt.subplot(222)
    ax = plt.imshow(resp[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('FEM $\%s_{%s}$ response, slice %s' % ('epsilon', '11', slc))

    dmin = np.min([ep_t[sn, slc, :, :], ep_t_mks[sn, slc, :, :]])
    dmax = np.max([ep_t[sn, slc, :, :], ep_t_mks[sn, slc, :, :]])

    plt.subplot(223)
    ax = plt.imshow(ep_t[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('FEM $\%s_{%s}^p$ response, slice %s' % ('epsilon', '11', slc))

    plt.subplot(224)
    ax = plt.imshow(ep_t_mks[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('MKS $\%s_{%s}^p$ response, slice %s' % ('epsilon', '11', slc))

    # plt.show()

    # PLOT PLASTIC STRAIN DISTRIBUTIONS
    # (only plot distributions for soft phase)

    plt.figure(num=4, figsize=[10, 7])

    # find the min and max of both datasets (in full)
    dmin = np.amin([ep_t, ep_t_mks])
    dmax = np.amax([ep_t, ep_t_mks])

    micr0 = micr[:, 0, ...].reshape(ns * el * el * el).astype(int)

    ep_t_lin = ep_t.reshape(ns * el * el * el)
    ep_t_mks_lin = ep_t_mks.reshape(ns * el * el * el)

    tmp = np.nonzero(micr0)
    fe = ep_t_lin[tmp]
    mks = ep_t_mks_lin[tmp]

    # select the desired number of bins in the histogram
    bn = 100

    # FEM histogram
    n, bins, patches = plt.hist(fe,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    bincenters = 0.5 * (bins[1:] + bins[:-1])
    fep, = plt.plot(bincenters, n, 'k', linestyle='-', lw=1.0)

    # MKS histogram
    n, bins, patches = plt.hist(mks,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    mksp, = plt.plot(bincenters, n, 'b', linestyle='-', lw=1.0)

    plt.grid(True)

    plt.legend([fep, mksp], ["FE - compliant phase", "MKS - compliant phase"])

    plt.xlabel("$\%s_{%s}^p$" % ('epsilon', '11'))
    plt.ylabel("Frequency")
    plt.title("$\%s_{%s}^p$ Frequency Histogram, FE vs. MKS," %
              ('epsilon', '11'))

    # plt.show()

    # PLOT VIOLIN PLOT FOR PLASTIC STRAIN BINS

    error = ((ep_t_lin - ep_t_mks_lin) / 0.000125) * 100

    # Plot a histogram representing the frequency of strain levels with
    # separate channels for each phase of each type of response.
    plt.figure(num=5, figsize=[12, 7])

    # select the desired number of bins in the histogram
    bn = 5

    # find the bin locations for the CPFEM response of interest
    n, bins, patches = plt.hist(ep_t_lin,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                color='white')

    print "values per bin: %s" % n

    bincenters = 0.5 * (bins[1:] + bins[:-1])

    error_in_bin_list = []
    bin_labels = []

    for ii in xrange(bn):
        in_bin = (ep_t_lin >= bins[ii]) * (ep_t_lin < bins[ii + 1])
        error_in_bin = error * in_bin
        error_in_bin = error_in_bin[(error_in_bin != 0)]
        error_in_bin_list.append(error_in_bin)

        label_cur = str(np.round(100*bins[ii], 4)) + '% - ' + \
            str(np.round(100*bins[ii + 1], 4)) + '%\n' + \
            str(int(n[ii])) + ' points'
        bin_labels.append(label_cur)

    # plt.figure(num=6, figsize=[12, 5])

    # # select the desired number of bins in the histogram
    # bn_er = 40

    # # find the bin locations for the CPFEM response of interest
    # n, bins, patches = plt.hist(ep_t_lin, bins=bn_er, histtype='step',
    #                             hold=True, color='white')
    # bincenters = 0.5*(bins[1:]+bins[:-1])
    # plt.plot(bincenters, n)
    # plt.axis([401, 607, 0, 70000])

    ax = plt.subplot(111)

    x = np.arange(1, bn + 1)

    ax.violinplot(dataset=error_in_bin_list,
                  showextrema=False,
                  showmedians=False,
                  showmeans=False)

    ax.set_xticks(x)
    ax.set_xticklabels(bin_labels, rotation='vertical')

    plt.xlabel("bin centers, $\%s_{%s}$ MPa - number of samples" %
               (typ, real_comp))
    plt.ylabel("%% error (normalized by mean $\%s_{vm}$)" % typ)
    plt.title("Error Histogram, $\%s_{%s}$" % (typ, real_comp))
    plt.grid(True)
    plt.tight_layout(pad=0.1)
    plt.ylim([1.25 * np.min(error), 1.25 * np.max(error)])

    # x = np.arange(1, bn + 1)

    # fig, ax = plt.subplots(5, figsize=(12, 7))

    # ax.violinplot(dataset=error_in_bin_list, showextrema=False,
    #               showmedians=False, showmeans=False)
    # ax.set_xticks(x)
    # ax.set_xticklabels(bin_labels, rotation='vertical')

    # plt.xlabel("bin centers, $\%s_{%s}$ MPa - number of samples" %
    #            (typ, real_comp))
    # plt.ylabel("%% error (normalized by mean $\%s_{vm}$)" % typ)
    # plt.title("Error Histogram, $\%s_{%s}$" % (typ, real_comp))
    # plt.grid(True)
    # plt.tight_layout(pad=0.1)

    plt.show()
Example #8
0
def results(el, ns, set_id, typ, wrt_file):

    ## vector of the indicial forms of the tensor components
    real_comp = '11'

    mks_R = np.load('mksR_%s%s.npy' % (ns, set_id))
    resp = np.load('r_%s%s.npy' % (ns, set_id)).reshape([ns, el, el, el])

    ### VISUALIZATION OF MKS VS. FEM ###

    ## pick a slice perpendicular to the x-direction
    slc = 10
    sn = 0

    ## Plot slices of the response
    plt.figure(num=2, figsize=[12, 4])

    dmin = np.min([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])
    dmax = np.max([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])

    plt.subplot(121)
    ax = plt.imshow(mks_R[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('MKS $\%s_{%s}$ response, slice %s' % (typ, real_comp, slc))

    plt.subplot(122)
    ax = plt.imshow(resp[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('CPFEM $\%s_{%s}$ response, slice %s' % (typ, real_comp, slc))

    #    plt.subplot(121)
    #    ax = plt.imshow(mks_R[sn,slc,:,:], origin='lower', interpolation='none',
    #        cmap='jet')
    #    plt.colorbar(ax)
    #    plt.title('MKS $\%s_{%s}$ response, slice %s' %(typ,real_comp,slc))
    #
    #    plt.subplot(122)
    #    ax = plt.imshow(resp[sn,slc,:,:], origin='lower', interpolation='none',
    #        cmap='jet')
    #    plt.colorbar(ax)
    #    plt.title('CPFEM $\%s_{%s}$ response, slice %s' %(typ,real_comp,slc))

    #### MEAN ABSOLUTE STRAIN ERROR (MASE) ###
    avgr_fe_tot = 0
    avgr_mks_tot = 0
    max_diff_all = np.zeros(ns)

    for sn in xrange(ns):
        avgr_fe_indv = np.average(resp[sn, ...])
        avgr_mks_indv = np.average(mks_R[sn, ...])

        avgr_fe_tot += avgr_fe_indv
        avgr_mks_tot += avgr_mks_indv
        max_diff_all[sn] = np.amax(abs(resp[sn, ...] - mks_R[sn, ...]))

    avgr_fe = avgr_fe_tot / ns
    avgr_mks = avgr_mks_tot / ns

    ### DIFFERENCE MEASURES ###
    mean_diff_meas = np.mean(abs(resp - mks_R)) / avgr_fe
    mean_max_diff_meas = np.mean(max_diff_all) / avgr_fe
    max_diff_meas_all = np.amax(abs(resp - mks_R)) / avgr_fe

    msg = 'Mean voxel difference over all microstructures (divided by mean von-Mises meas), %s%s: %s%%' % (
        typ, real_comp, mean_diff_meas * 100)
    rr.WP(msg, wrt_file)
    msg = 'Average Maximum voxel difference per microstructure (divided by mean von-Mises meas), %s%s: %s%%' % (
        typ, real_comp, mean_max_diff_meas * 100)
    rr.WP(msg, wrt_file)
    msg = 'Maximum voxel difference in all microstructures (divided by mean von-Mises meas), %s%s: %s%%' % (
        typ, real_comp, max_diff_meas_all * 100)
    rr.WP(msg, wrt_file)

    ### STANDARD STATISTICS ###
    msg = 'Average, %s%s, CPFEM: %s' % (typ, real_comp, avgr_fe)
    rr.WP(msg, wrt_file)
    msg = 'Average, %s%s, MKS: %s' % (typ, real_comp, avgr_mks)
    rr.WP(msg, wrt_file)
    msg = 'Standard deviation, %s%s, CPFEM: %s' % (typ, real_comp,
                                                   np.std(resp))
    rr.WP(msg, wrt_file)
    msg = 'Standard deviation, %s%s, MKS: %s' % (typ, real_comp, np.std(mks_R))
    rr.WP(msg, wrt_file)

    resp_min = np.mean(np.amin(resp.reshape([el**3, ns]), axis=0))
    mks_R_min = np.mean(np.amin(mks_R.reshape([el**3, ns]), axis=0))

    resp_max = np.mean(np.amax(resp.reshape([el**3, ns]), axis=0))
    mks_R_max = np.mean(np.amax(mks_R.reshape([el**3, ns]), axis=0))

    msg = 'Mean minimum, %s%s, CPFEM: %s' % (typ, real_comp, resp_min)
    rr.WP(msg, wrt_file)
    msg = 'Mean minimum, %s%s, MKS: %s' % (typ, real_comp, mks_R_min)
    rr.WP(msg, wrt_file)
    msg = 'Mean maximum, %s%s, CPFEM: %s' % (typ, real_comp, resp_max)
    rr.WP(msg, wrt_file)
    msg = 'Mean maximum, %s%s, MKS: %s' % (typ, real_comp, mks_R_max)
    rr.WP(msg, wrt_file)
def validation_zero_pad(el_cal, el_val, ns_cal, ns_val, H, set_id_cal,
                        set_id_val, wrt_file):

    start = time.time()

    # zero-pad the influence coefficients
    pre_specinfc = np.load('specinfc_%s%s.npy' % (ns_cal, set_id_cal))
    pre_specinfc = np.reshape(pre_specinfc, [H, el_cal, el_cal, el_cal])
    pre_specinfc = np.fft.ifftn(
        pre_specinfc, [el_cal, el_cal, el_cal], [1, 2, 3])

    # h_comp = 0
    # plt.figure(num=1, figsize=[12, 8])
    # dmin = np.amin(pre_specinfc[h_comp, 0, :, :].real)
    # dmax = np.amax(pre_specinfc[h_comp, 0, :, :].real)

    # plt.subplot(221)
    # ax = plt.imshow(pre_specinfc[h_comp, 0, :, :].real, origin='lower',
    #                 interpolation='none',
    #                 cmap='jet', vmin=dmin, vmax=dmax)
    # plt.colorbar(ax)
    # plt.title('original influence coefficients')

    pre_specinfc = np.fft.fftshift(pre_specinfc, axes=[1, 2, 3])

#    edgeHvec = pre_specinfc[0,0,0,:]

    # plt.subplot(222)
    # slc = np.floor(0.5 * el_cal).astype(int)
    # ax = plt.imshow(pre_specinfc[h_comp, slc, :, :].real, origin='lower',
    #                 interpolation='none',
    #                 cmap='jet', vmin=dmin, vmax=dmax)
    # plt.colorbar(ax)
    # plt.title('centered influence coefficients')

    specinfc_pad = np.zeros([H, el_val, el_val, el_val], dtype='complex64')

#    for h in xrange(H):
#        specinfc_pad[:,:,:,h] = edgeHvec[h]

    el_gap = int(0.5 * (el_val - el_cal))
    el_end = el_val - el_gap
    specinfc_pad[:, el_gap:el_end, el_gap:el_end, el_gap:el_end] = pre_specinfc
    del pre_specinfc

    # plt.subplot(223)
    # slc = np.floor(0.5 * el_val).astype(int)
    # ax = plt.imshow(specinfc_pad[h_comp, slc, :, :].real, origin='lower',
    #                 interpolation='none',
    #                 cmap='jet', vmin=dmin, vmax=dmax)
    # plt.colorbar(ax)
    # plt.title('padded/centered influence coefficients')

    specinfc_pad = np.fft.ifftshift(specinfc_pad, axes=[1, 2, 3])

    # plt.subplot(224)
    # ax = plt.imshow(specinfc_pad[h_comp, 0, :, :].real, origin='lower',
    #                 interpolation='none',
    #                 cmap='jet', vmin=dmin, vmax=dmax)
    # plt.colorbar(ax)
    # plt.title('padded influence coefficients')

    specinfc = np.fft.fftn(specinfc_pad, axes=[1, 2, 3])

    # perform the prediction procedure

    M = np.load('M_%s%s.npy' % (ns_val, set_id_val))

    tmp = np.sum(np.conjugate(specinfc) * M, 1)
    mks_R = np.fft.ifftn(tmp, [el_val, el_val, el_val], [1, 2, 3]).real

    np.save('mksR_%s%s' % (ns_val, set_id_val), mks_R)

    end = time.time()
    timeE = np.round((end - start), 3)

    msg = 'validation performed: %s seconds' % timeE
    rr.WP(msg, wrt_file)
def validation_zero_pad(el_cal,el_val,ns_cal,ns_val,H,set_id_cal,set_id_val,wrt_file):

    start = time.time()

    ## zero-pad the influence coefficients    
    pre_specinfc = np.load('specinfc_%s%s.npy' %(ns_cal,set_id_cal)) 
    pre_specinfc = np.reshape(pre_specinfc,[el_cal,el_cal,el_cal,H])
    pre_specinfc = np.fft.ifftn(pre_specinfc,[el_cal,el_cal,el_cal],[0,1,2])
    
    h_comp = 0
    plt.figure(num=1,figsize=[12,8])
    dmin = np.amin(pre_specinfc[0,:,:,h_comp].real)
    dmax = np.amax(pre_specinfc[0,:,:,h_comp].real)
    
    plt.subplot(221)
    ax = plt.imshow(pre_specinfc[0,:,:,h_comp].real, origin='lower', interpolation='none',
        cmap='jet', vmin=dmin, vmax=dmax)
    plt.colorbar(ax)
    plt.title('original influence coefficients')  
    
    pre_specinfc = np.fft.fftshift(pre_specinfc, axes = [0,1,2])    
    
#    edgeHvec = pre_specinfc[0,0,0,:]  

    plt.subplot(222)
    slc = np.floor(0.5*el_cal).astype(int)
    ax = plt.imshow(pre_specinfc[slc,:,:,h_comp].real, origin='lower', interpolation='none',
        cmap='jet', vmin=dmin, vmax=dmax)
    plt.colorbar(ax)
    plt.title('centered influence coefficients')  
    
    specinfc_pad = np.zeros([el_val,el_val,el_val, H],dtype='complex64')

#    for h in xrange(H):    
#        specinfc_pad[:,:,:,h] = edgeHvec[h]

    el_gap = int(0.5*(el_val-el_cal))
    el_end = el_val - el_gap    
    specinfc_pad[el_gap:el_end,el_gap:el_end,el_gap:el_end,:] = pre_specinfc    
    del pre_specinfc

    plt.subplot(223)
    slc = np.floor(0.5*el_val).astype(int)
    ax = plt.imshow(specinfc_pad[slc,:,:,h_comp].real, origin='lower', interpolation='none',
        cmap='jet', vmin=dmin, vmax=dmax)
    plt.colorbar(ax)
    plt.title('padded/centered influence coefficients')  
   
   
    specinfc_pad = np.fft.ifftshift(specinfc_pad, axes = [0,1,2])  
     
    plt.subplot(224)
    ax = plt.imshow(specinfc_pad[0,:,:,h_comp].real, origin='lower', interpolation='none',
        cmap='jet', vmin=dmin, vmax=dmax)
    plt.colorbar(ax)
    plt.title('padded influence coefficients')    
   
    
    
    specinfc = np.fft.fftn(specinfc_pad, axes = [0,1,2])       
    

    ## perform the prediction procedure    
    
    M = np.load('M_%s%s.npy' %(ns_val,set_id_val))
    
    mks_R = np.zeros([el_val,el_val,el_val,ns_val])
    
    
    for sn in xrange(ns_val):
        mks_F = np.sum(np.conjugate(specinfc) * M[:,:,:,sn,:],3)
        mks_R[:,:,:,sn] = np.fft.ifftn(mks_F).real
    
#    print M.shape
#    temp = np.swapaxes(M,0,3)
#    print temp.shape
#    mks_R = np.sum(np.conjugate(specinfc) * temp, 4)
#    print mks_R.shape
#    mks_R = np.swapaxes(mks_R,0,3)
#    print mks_R.shape     
#    mks_R = np.fft.ifftn(mks_R,[el_val,el_val,el_val],[0,1,2]).real
#    print mks_R.shape    
 

    
    np.save('mksR_%s%s' %(ns_val,set_id_val), mks_R)

    end = time.time()
    timeE = np.round((end - start),3)

    msg = 'validation performed: %s seconds' %timeE
    rr.WP(msg,wrt_file)
Example #11
0
def fip_calc(el, ns, set_id, wrt_file):

    mks_R = np.load('mksR_%s%s.npy' % (ns, set_id))
    resp = np.load('r_%s%s.npy' % (ns, set_id)).reshape([ns, el, el, el])
    micr = np.load('pre_msf_%s%s.npy' % (ns, set_id))

    # DEFINE RELEVANT PARAMETERS

    typ = 'epsilon'
    real_comp = '11'

    y_0 = 0.8  # phase 0 yield point
    y_1 = 1.2  # phase 1 yield point
    E_0 = 115  # phase 0 Young's Modulus
    E_1 = 145  # phase 1 Young's Modulus

    ey_0 = y_0 / E_0  # strain at yield for phase 0
    ey_1 = y_1 / E_1  # strain at yield for phase 1

    print ey_0
    print ey_1
    ep_app = 0.9 * 0.5 * (ey_0 + ey_1)
    print ep_app

    # CALCULATE THE PLASTIC AND ELASTIC STRAIN DISTRIBUTIONS

    # FEM results

    # plastic strain phase 0
    ep_0 = micr[:, 0, ...] * resp - ey_0 * micr[:, 0, ...] > 0
    ep_0 = ep_0 * (resp - ey_0 * micr[:, 0, ...])

    # plastic strain phase 1
    ep_1 = micr[:, 1, ...] * resp - ey_1 * micr[:, 1, ...] > 0
    ep_1 = ep_1 * (resp - ey_1 * micr[:, 1, ...])

    ep_t = ep_0 + ep_1  # plastic strain for both phases

    # MKS results

    ep_0_mks = micr[:, 0, ...] * mks_R - ey_0 * micr[:, 0, ...] > 0
    ep_0_mks = ep_0_mks * (mks_R - ey_0 * micr[:, 0, ...])

    # plastic strain phase 1
    ep_1_mks = micr[:, 1, ...] * mks_R - ey_1 * micr[:, 1, ...] > 0
    ep_1_mks = ep_1_mks * (mks_R - ey_1 * micr[:, 1, ...])

    ep_t_mks = ep_0_mks + ep_1_mks  # plastic strain for both phases

    # CALCULATE ERROR IN PLASTIC STRAIN PREDICTION

    avgr_fe_tot = 0
    max_diff_all = np.zeros(ns)

    for sn in xrange(ns):
        avgr_fe_indv = np.average(ep_t[sn, ...])

        avgr_fe_tot += avgr_fe_indv
        max_diff_all[sn] = np.amax(abs(ep_t[sn, ...] - ep_t_mks[sn, ...]))

    avgr_fe = avgr_fe_tot / ns

    # difference measure
    mean_diff_meas = np.mean(abs(ep_t - ep_t_mks)) / ep_app
    mean_max_diff_meas = np.mean(max_diff_all) / ep_app
    max_diff_meas_all = np.amax(abs(ep_t - ep_t_mks)) / ep_app

    msg = 'Mean plastic strain:, %s%%' % avgr_fe
    rr.WP(msg, wrt_file)

    msg = 'Mean voxel difference over all microstructures'\
        ' (normalized by mean strain), %s%sp: %s%%' \
        % (typ, real_comp, mean_diff_meas*100)
    rr.WP(msg, wrt_file)

    msg = 'Average Maximum voxel difference per microstructure'\
        ' (normalized by mean strain), %s%sp: %s%%' \
        % (typ, real_comp, mean_max_diff_meas*100)
    rr.WP(msg, wrt_file)

    msg = 'Maximum voxel difference in all microstructures '\
        '(normalized by mean strain), %s%sp: %s%%' \
        % (typ, real_comp, max_diff_meas_all*100)
    rr.WP(msg, wrt_file)

    # PLOT THE STRAIN FIELDS

    # find indices of max error and use them for plotting
    maxindx = np.unravel_index(np.argmax(np.abs(ep_t - ep_t_mks)), ep_t.shape)
    slc = maxindx[1]
    sn = maxindx[0]

    # choose indices for plotting
    # slc = 10
    # sn = 100

    # Plot slices of the response
    plt.figure(num=3, figsize=[11, 8])

    dmin = np.min([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])
    dmax = np.max([mks_R[sn, slc, :, :], resp[sn, slc, :, :]])

    plt.subplot(221)
    ax = plt.imshow(micr[sn, 0, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet')
    plt.colorbar(ax)
    plt.title('phase map, slice %s' % (slc))

    plt.subplot(222)
    ax = plt.imshow(resp[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('FEM $\%s_{%s}$ response, slice %s' % ('epsilon', '11', slc))

    dmin = np.min([ep_t[sn, slc, :, :], ep_t_mks[sn, slc, :, :]])
    dmax = np.max([ep_t[sn, slc, :, :], ep_t_mks[sn, slc, :, :]])

    plt.subplot(223)
    ax = plt.imshow(ep_t[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('FEM $\%s_{%s}^p$ response, slice %s' % ('epsilon', '11', slc))

    plt.subplot(224)
    ax = plt.imshow(ep_t_mks[sn, slc, :, :],
                    origin='lower',
                    interpolation='none',
                    cmap='jet',
                    vmin=dmin,
                    vmax=dmax)
    plt.colorbar(ax)
    plt.title('MKS $\%s_{%s}^p$ response, slice %s' % ('epsilon', '11', slc))

    # plt.show()

    # PLOT PLASTIC STRAIN DISTRIBUTIONS
    # (only plot distributions for soft phase)

    plt.figure(num=4, figsize=[10, 7])

    # find the min and max of both datasets (in full)
    dmin = np.amin([ep_t, ep_t_mks])
    dmax = np.amax([ep_t, ep_t_mks])

    micr0 = micr[:, 0, ...].reshape(ns * el * el * el).astype(int)

    ep_t_lin = ep_t.reshape(ns * el * el * el)
    ep_t_mks_lin = ep_t_mks.reshape(ns * el * el * el)

    tmp = np.nonzero(micr0)
    fe = ep_t_lin[tmp]
    mks = ep_t_mks_lin[tmp]

    # select the desired number of bins in the histogram
    bn = 100

    # FEM histogram
    n, bins, patches = plt.hist(fe,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    bincenters = 0.5 * (bins[1:] + bins[:-1])
    fep, = plt.plot(bincenters, n, 'k', linestyle='-', lw=1.0)

    # MKS histogram
    n, bins, patches = plt.hist(mks,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    mksp, = plt.plot(bincenters, n, 'b', linestyle='-', lw=1.0)

    plt.grid(True)

    plt.legend([fep, mksp], ["FE - compliant phase", "MKS - compliant phase"])

    plt.xlabel("$\%s_{%s}^p$" % ('epsilon', '11'))
    plt.ylabel("Frequency")
    plt.title("$\%s_{%s}^p$ Frequency Histogram, FE vs. MKS," %
              ('epsilon', '11'))

    # PLOT VIOLIN PLOT FOR PLASTIC STRAIN BINS

    error = ((ep_t_lin - ep_t_mks_lin) / ep_app) * 100

    sort_list = np.argsort(ep_t_lin)

    ep_sort = ep_t_lin[sort_list[np.round(0.999 * len(error)):]]

    err_sort = error[sort_list[np.round(0.999 * len(error)):]]

    # select the desired number of bins in the histogram
    bn = 10

    # number of error values per bin in the violin plot
    num_per_bin = np.floor(len(ep_sort) / bn)

    error_in_bin_list = []
    bin_labels = []

    for ii in xrange(bn):

        if ii != bn - 1:
            error_in_bin = err_sort[ii * num_per_bin:(ii + 1) * num_per_bin -
                                    1]
            ep_in_bin = ep_sort[ii * num_per_bin:(ii + 1) * num_per_bin - 1]
        else:
            error_in_bin = err_sort[ii * num_per_bin:]
            ep_in_bin = ep_sort[ii * num_per_bin:]

        print len(ep_in_bin)

        error_in_bin_list.append(error_in_bin)

        label_cur = str(np.round(100*ep_in_bin[0], 4)) + '% - ' + \
            str(np.round(100*ep_in_bin[-1], 4)) + '%'
        bin_labels.append(label_cur)

    plt.figure(num=5, figsize=[12, 7])

    ax = plt.subplot(111)

    x = np.arange(1, bn + 1)

    ax.violinplot(dataset=error_in_bin_list,
                  showextrema=False,
                  showmedians=False,
                  showmeans=False)

    ax.set_xticks(x)
    ax.set_xticklabels(bin_labels, rotation='vertical')

    plt.xlabel("bin centers, $\%s_{%s}$" % (typ, real_comp))
    plt.ylabel("%% error")
    plt.title("Error Histogram, $\%s_{%s}$" % (typ, real_comp))
    plt.grid(True)
    plt.tight_layout(pad=0.1)
    plt.ylim([1.25 * np.min(err_sort), 1.25 * np.max(err_sort)])

    plt.figure(num=6, figsize=[10, 7])

    # find the min and max of both datasets (in full)

    ep_t_l = ep_t.reshape(ns, el**3) * 100
    ep_t_mks_l = ep_t_mks.reshape(ns, el**3) * 100

    fe = np.max(ep_t_l, 1)
    mks = np.max(ep_t_mks_l, 1)

    dmin = np.amin([fe, mks])
    dmax = np.amax([fe, mks])

    # select the desired number of bins in the histogram
    bn = 25

    # FEM histogram
    n, bins, patches = plt.hist(fe,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    bincenters = 0.5 * (bins[1:] + bins[:-1])
    fep, = plt.plot(bincenters, n, 'b', linestyle='-', lw=1.0)

    # MKS histogram
    n, bins, patches = plt.hist(mks,
                                bins=bn,
                                histtype='step',
                                hold=True,
                                range=(dmin, dmax),
                                color='white')
    mksp, = plt.plot(bincenters, n, 'r', linestyle='-', lw=1.0)

    plt.grid(True)

    plt.legend([fep, mksp], ["FE", "MKS"])

    plt.xlabel("$\%s_{%s}^p$ %%" % ('epsilon', '11'))
    plt.ylabel("Frequency")
    plt.title("Maximum $\%s_{%s}^p$ per MVE, FE vs. MKS," % ('epsilon', '11'))

    plt.show()