Ejemplo n.º 1
0
def norm_spray(test_path, flat_path, dark_path, mask_fld, save_fld):
    if 'TimeRes' in save_fld:
        test_fld = test_path.split('.tif')[0][:-5].split('/')[-1]
        save_fld = create_folder(f'{save_fld}/{test_fld}/')
        mask_fld = save_fld.replace('Norm', 'Mask')

    data = np.array(Image.open(test_path))
    flat = np.array(Image.open(flat_path))
    dark = np.array(Image.open(dark_path))
    data_norm = (data - dark) / (flat - dark)

    # Mask the image
    lcsc_mask = np.array(Image.open(f'{prj_fld}/Images/Spray/LCSC_Mask.tif'))
    data_norm *= (lcsc_mask > 0)

    # Calculate offset
    data_mask = mask_image(test_path, data_norm, 0.7, mask_fld, lcsc_mask)
    data_bg = data_norm * ~(data_mask > 0) * (lcsc_mask > 0)
    data_bg[data_bg == 0] = np.nan
    ofst = np.nanmedian(data_bg)
    data_norm /= ofst

    # Apply median filter to remove spurious pixels
    data_norm = median_filter(data_norm, 3)

    # Scale image
    data_norm *= 5000

    # Save Transmission images
    im = Image.fromarray(data_norm.astype(np.uint16))
    im.save(save_fld + '/' + split(test_path)[1])
Ejemplo n.º 2
0
def saveProj(data, name, folder):
    folder = create_folder(folder)
    montage = np.reshape(data, (data.shape[0], -1))
    im = Image.fromarray(montage)
    im.save('{0}/{1}.tif'.format(folder, name))

    return
Ejemplo n.º 3
0
def main():
    # Get 50% KI in H2O density in g/cm^3, convert to ug/mm^3
    density = density_KIinH2O(50) * 1000

    # Location of the 0.30 gpm AVERAGED input and outputs
    #ij_0p30avg_inp = glob.glob('{0}/TimeAvg_0p30/'
    #                           '0p30/FastMART_500iter_Smooth500iter/'
    #                           'Data/S0*/'.format(inp_fld))
    #ij_0p30avg_out = create_folder('{0}/SprayVol/IJ_0p30gpm_AVG/'
    #                               .format(out_fld))

    # Location of the 0.30 gpm input and outputs
    ij_0p30_inp = glob.glob('{0}/EPL7_30/MakePermanentImgMask/'
                            'FastMART_500iter_Smooth500Iter/'
                            'Data/S0*/'.format(inp_fld))
    ij_0p30_out = create_folder('{0}/SprayVol/IJ_0p30gpm/'.format(out_fld))

    # Location of the 0.45 gpm input and outputs
    #ij_0p45_inp = glob.glob('{0}/Statistics_0p45/'
    #                        '0p45/FastMART_500iter_Smooth500/'
    #                        'Data/S0*/'.format(inp_fld))
    #ij_0p45_out = create_folder('{0}/SprayVol/IJ_0p45gpm/'
    #                            .format(out_fld))

    # Rotations for the volumes (see Jupyter Notebook)
    rot = {'Angle': 13, 'Axes': (2, 0)}

    # Convert the individual volumes
    #convertVTK(ij_0p30avg_inp, rot, ij_0p30avg_out, density)
    convertVTK(ij_0p30_inp, rot, ij_0p30_out, density)
Ejemplo n.º 4
0
def save_plt(dataset, plt_folder, plt_name, zone=None):
    """
    Function that saves the Tecplot dataset/zone into a .plt file.
    This function saves to an individual .plt file. If you want to save a
    series of volumes (such as for each zone), then call this function
    inside a for-loop.

    INPUT VARIABLES
    ---------------
    dataset:        Tecplot dataset.

    plt_folder:     Output folder path where the .plt file will be saved.

    plt_name:       Desired name of the .plt file.

    zone:           OPTIONAL. Specific zone to save (can call by name or
                    index starting at 1). If not specified, will save
                    the entire dataset.
    """
    # Create folder if it doesn't exist
    plt_fld = create_folder(plt_fld)

    # Save the dataset to a PLT file
    tp.data.save_tecplot_plt('{0}/{1}.plt'.format(plt_fld, plt_name),
                             dataset=dataset,
                             zones=zone)
Ejemplo n.º 5
0
def averaged_plots(x, y, ylbl, xlbl, scale, name, scint):
    """
    Creates plots of the averaged variables.
    =============
    --VARIABLES--
    x:              X axis variable.
    y:              Y axis variable.
    ylbl:           Y axis label.
    xlbl:           X axis label.
    scale:          Y scale ('log' or 'linear').
    name:           Save name for the plot.
    scint:          Scintillator being used.
    """
    global prj_fld

    averaged_folder = create_folder(
        '{0}/Figures/Averaged_Figures'.format(prj_fld))

    plt.figure()

    # Water
    plt.plot(x[0], y[0], color='k', linewidth=2.0, label='Water')

    # 1.6% KI
    plt.plot(x[1],
             y[1],
             marker='x',
             markevery=50,
             linewidth=2.0,
             label='1.6% KI')

    # 3.4% KI
    plt.plot(x[2], y[2], linestyle='--', linewidth=2.0, label='3.4% KI')

    # 5.3% KI
    plt.plot(x[3], y[3], linestyle='-.', linewidth=2.0, label='5.3% KI')

    # 8.1% KI
    plt.plot(x[4], y[4], linestyle=':', linewidth=2.0, label='8.1% KI')

    # 10.0% KI
    plt.plot(x[5],
             y[5],
             marker='^',
             markevery=50,
             linewidth=2.0,
             label='10.0% KI')

    # 11.1% KI
    plt.plot(x[6], y[6], linestyle='--', linewidth=2.0, label='11.1% KI')
    plt.legend()
    plt.ylabel(ylbl)
    plt.xlabel(xlbl)
    plt.yscale(scale)
    plt.savefig('{0}/{1}_{2}.png'.format(averaged_folder, scint, name))
Ejemplo n.º 6
0
def saveAnim(fld, renderView, viewType, timeSteps):
    # Save animation
    save_fld = create_folder('{0}/PV_{1}/'.format(fld, viewType))
    SaveAnimation(
                  '{}/vol.png'.format(save_fld),
                  renderView,
                  FrameWindow=[0, timeSteps-1],
                  ImageResolution=[1116, 527],
                  TransparentBackground=1,
                  CompressionLevel='0',
                  SuffixFormat='%04d'
                  )
Ejemplo n.º 7
0
def main():
    prj_fld = '/mnt/r/X-ray Radiography/APS 2019-1/'
    cor_fld = '{0}/Corrected/YAG/Summary/'.format(prj_fld)
    plt_fld = create_folder('{0}/Figures/Cal_Errors/'.format(prj_fld))

    tests = glob.glob('{0}/*.pckl'.format(cor_fld))

    # Container for what will be the summary DataFrame
    d = []

    for test in tests:
        # Use 'Ellipse' as the method (worked best in 2018-1)
        method = 'Ellipse'

        # Retrieve test name
        test_name = test.rsplit('/')[-1].rsplit('.')[0]

        # Retrieve vertical locations
        vert_loc = np.array(get_ypos(test))

        # Retrieve errors
        abEr = get_abs(test, method)
        rmse = get_rmse(test, method)
        mape = get_mape(test, method)
        zeta = get_zeta(test, method)
        mdlq = get_mdlq(test, method)

        # Remove outliers from data
        vert_loc, abEr = reject_outliers(vert_loc, abEr)

        # Build up summary dict
        d.append({
                  'Name': test_name,
                  'RMSE': rmse,
                  'MAPE': mape,
                  'Zeta': zeta,
                  'MdLQ': mdlq
                  })

        # Create absolute error plot
        plt.figure()
        plt.plot(vert_loc, abEr, color='tab:blue', linewidth=2.0)
        plt.xlabel('Vertical Location (px)')
        plt.ylabel('Absolute Error ($\mu$m)')
        plt.title(test_name)
        plt.savefig('{0}/{1}.png'.format(plt_fld, test_name))
        plt.close()

    # Save summary of errors
    summ = pd.DataFrame(d)
    summ.to_csv(prj_fld + '/Corrected/YAG/summary.txt', sep='\t')
Ejemplo n.º 8
0
def main():
    # Get 50% KI in H2O density in g/cm^3, convert to ug/mm^3
    density = density_KIinH2O(50) * 1000

    # Location of the 0.30 gpm input and outputs
    sc_0p20_inp = glob.glob('{0}/New_SC_0p20/'
                            'SC_0p20/FastMART/'
                            'Data/S0*/'.format(inp_fld))
    sc_0p20_out = create_folder('{0}/SprayVol/SC_0p20gpm/'.format(out_fld))

    # Rotations for the volumes (see Jupyter Notebook)
    rot = {'Angle': 13, 'Axes': (2, 0)}

    # Convert the individual volumes
    convertVTK(sc_0p20_inp, rot, sc_0p20_out, density)
Ejemplo n.º 9
0
def conv_spray(test_path, save_fld):
    if 'TimeRes' in save_fld:
        test_fld = test_path.split('.tif')[0][:-5].split('/')[-1]
        save_fld = create_folder(f'{save_fld}/{test_fld}/')

    # Load models from the whitebeam_2019 script
    with open(prj_fld + '/Model/water_model_YAG.pckl', 'rb') as f:
        water_mdl = pickle.load(f)

    with open(prj_fld + '/Model/KI4p8_model_YAG.pckl', 'rb') as f:
        KI4p8_mdl = pickle.load(f)

    models = [water_mdl, KI4p8_mdl]

    # Load corresponding model
    if 'KI' in test_path:
        model = models[1]
    else:
        model = models[0]

    TtoEPL = model[0]

    # Load in normalized image
    data_norm = np.array(Image.open(test_path)).astype(float) / 5000

    # Convert to EPL in cm
    data_epl = np.zeros(np.shape(data_norm), dtype=float)
    for k, _ in enumerate(data_norm):
        data_epl[k, :] = TtoEPL[k](data_norm[k, :])

    # Mask the image
    lcsc_mask = np.array(Image.open(f'{prj_fld}/Images/Spray/LCSC_Mask.tif'))
    data_epl *= (lcsc_mask > 0)

    # Calculate offset
    data_mask = np.array(Image.open(test_path.replace('/Norm/', '/Mask/')))
    data_bg = data_epl * ~(data_mask > 0) * (lcsc_mask > 0)
    data_bg[data_bg == 0] = np.nan
    ofst = np.nanmedian(data_bg)
    data_epl -= ofst

    # Scale image for saving as np.uint16
    data_epl += 1  # for negative values
    data_epl *= 2500

    # Save EPL image
    im = Image.fromarray(data_epl.astype(np.uint16))
    im.save(save_fld + '/' + split(test_path)[1])
Ejemplo n.º 10
0
def saveVol(vol, W, name, folder):
    grid = W.vshape[::-1]
    winX = [W.vg['options']['WindowMinX'], W.vg['options']['WindowMaxX']]
    winY = [W.vg['options']['WindowMinY'], W.vg['options']['WindowMaxY']]
    winZ = [W.vg['options']['WindowMinZ'], W.vg['options']['WindowMaxZ']]
    win = [winX, winY, winZ]

    grid = [np.linspace(*w, g) for (w, g) in zip(win, grid)]
    limits = [[-999, 999]] * 3

    center_x = -0.37
    center_y = 0.9
    center_z = 0.2

    cropX = [np.argmin(np.abs(grid[0] - x)) for x in limits[0]]
    cropY = [np.argmin(np.abs(grid[1] - y)) for y in limits[1]]
    cropZ = [np.argmin(np.abs(grid[2] - z)) for z in limits[2]]

    vol2 = np.array(vol[cropZ[0]:cropZ[1], cropY[0]:cropY[1],
                        cropX[0]:cropX[1]],
                    order='F')

    gridX = grid[0][cropX[0]:cropX[1]]
    gridY = grid[1][cropY[0]:cropY[1]]
    gridZ = grid[2][cropZ[0]:cropZ[1]]

    voxelSize = [
        np.mean(np.diff(gridX)),
        np.mean(np.diff(gridY)),
        np.mean(np.diff(gridZ))
    ]

    originX = (gridX - center_x)[0]
    originY = (gridY - center_y)[0]
    originZ = (gridZ - center_z)[0]

    # Save volume
    folder = create_folder(folder)
    imageToVTK(
        '{0}/{1}'.format(folder, name),
        origin=[originZ, originY, originX],
        spacing=np.flip(voxelSize, axis=0).tolist(),
        pointData={'LVF': (vol2 / density_KIinH2O(50)).astype(np.int16)})

    return
Ejemplo n.º 11
0
def main():
    # Spray type
    sprays = ['SC', 'AeroECN 100psi 10%KI']

    for spray in sprays:
        # Location of spray images
        spry_fld = '{0}/Images/{1}/'.format(prj_fld, spray)

        # Flat and dark image paths
        flat = glob.glob('{0}/Mean/*flat*'.format(spry_fld))[0]
        dark = glob.glob('{0}/Mean/*dark*'.format(spry_fld))[0]

        # Time-averaged images
        tavg_files = glob.glob('{0}/Mean/*.tif'.format(spry_fld))

        # Time-resolved images
        tres_fld = glob.glob('{0}/Raw/*'.format(spry_fld))

        # Remove flat/dark from the folder
        tres_fld = [x for x in tres_fld if 'dark' not in x]
        tres_fld = [x for x in tres_fld if 'flat' not in x]

        tres_files = [glob.glob('{0}/*.tif'.format(x))[500] for x in tres_fld]

        # Run time-averaged normalization
        norm_tavg_fld = create_folder('{0}/Norm/TimeAvg/'.format(spry_fld))
        mask_tavg_fld = create_folder('{0}/Mask/TimeAvg/'.format(spry_fld))
        [
            norm_spray(x, flat, dark, norm_tavg_fld, mask_tavg_fld)
            for x in tavg_files
        ]

        # Run time-resolved normalization
        norm_tres_fld = create_folder('{0}/Norm/TimeRes/'.format(spry_fld))
        mask_tres_fld = create_folder('{0}/Mask/TimeRes/'.format(spry_fld))
        [
            norm_spray(x, flat, dark, norm_tres_fld, mask_tres_fld)
            for x in tres_files
        ]

        # Run time-averaged EPL conversion
        epl_tavg_fld = create_folder('{0}/EPL/TimeAvg/'.format(spry_fld))
        tavg_files = glob.glob('{0}/*.tif'.format(norm_tavg_fld))
        [conv_spray(x, epl_tavg_fld) for x in tavg_files]

        # Run time-resolved EPL conversion
        epl_tres_fld = create_folder('{0}/EPL/TimeRes/'.format(spry_fld))
        tres_files = glob.glob('{0}/*.tif'.format(norm_tres_fld))
        [conv_spray(x, epl_tres_fld) for x in tres_files]
Ejemplo n.º 12
0
def plot_atten(atten1, atten2, name):
    """
    Plots the attenuation coefficients before and after re-shaping.
    =============
    --VARIABLES--
    atten1:     Original attenuation coefficient from nist.mass_atten.
    atten2:     Updated attenuation coefficient from
                spectrum_modeling.xcom_reshape.
    name:       Name of filter.
    """
    atten_fld = create_folder('{0}/Figures/Atten_Coeff'.format(prj_fld))

    plt.figure()
    plt.plot(atten1['Energy'],
             atten1['Attenuation'],
             label='Original',
             linestyle='solid',
             color='k',
             linewidth=2.0,
             zorder=1)
    plt.plot(atten2['Energy'],
             atten2['Attenuation'],
             label='Re-shaped',
             linestyle='dashed',
             color='b',
             linewidth=2.0,
             zorder=2)
    plt.yscale('log')
    plt.legend()
    plt.xlabel('Photon Energy (keV)')
    plt.ylabel('Attenuation Coefficient (cm$^2$/g')
    plt.title('{0}'.format(name))
    plt.savefig('{0}/{1}.png'.format(atten_fld, name))
    plt.close()

    return
Ejemplo n.º 13
0
def main():
    # Location of spray images
    spry_fld = '{0}/Images/Spray/'.format(prj_fld)

    # Flat and dark image paths
    flat = '{0}/Images/Flat/Mean/AVG_Background_NewYAG.tif'.format(prj_fld)
    dark = '{0}/Images/Flat/AVG_dark_current.tif'.format(prj_fld)

    # Time-averaged images
    tavg_files = glob.glob('{0}/Mean/*.tif'.format(spry_fld))

    # Time-resolved images
    tres_fld = glob.glob('{0}/Raw/*'.format(spry_fld))
    tres_files = [
        glob.glob('{0}/*.tif'.format(x))[:100] for x in tres_fld
        if 'NewYAG' in x
    ]

    # Run time-averaged normalization
    mask_fld = create_folder('{0}/Mask/TimeAvg/'.format(spry_fld))
    norm_fld = create_folder('{0}/Norm/TimeAvg/'.format(spry_fld))
    [norm_spray(x, flat, dark, mask_fld, norm_fld) for x in tavg_files]

    # Run time-averaged EPL conversion
    epl_tavg_fld = create_folder('{0}/EPL/TimeAvg/'.format(spry_fld))
    tavg_files = glob.glob('{0}/*.tif'.format(norm_fld))
    [conv_spray(x, epl_tavg_fld) for x in tavg_files]

    # Run time-resolved normalization
    mask_fld = create_folder('{0}/Mask/TimeRes/'.format(spry_fld))
    norm_fld = create_folder('{0}/Norm/TimeRes/'.format(spry_fld))
    [[norm_spray(x, flat, dark, mask_fld, norm_fld) for x in y]
     for y in tres_files]

    # Run time-resolved EPL conversion
    epl_tres_fld = create_folder('{0}/EPL/TimeRes/'.format(spry_fld))
    tres_files = glob.glob('{0}/**/*.tif'.format(norm_fld), recursive=True)

    # Crop (if desired)
    tres_files = np.reshape(tres_files, (-1, 5001))
    tres_files = tres_files[:, :100].flatten().tolist()
    [conv_spray(x, epl_tres_fld) for x in tres_files]
Ejemplo n.º 14
0
"""

import pickle
import glob
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from general.calc_statistics import polyfit
from general.misc import create_folder

# Location of APS 2018-1 data
prj_fld = '/mnt/r/X-ray Radiography/APS 2018-1/'

# Save location for the plots
plt_fld = create_folder('{0}/Figures/Jet_Errors/'.format(prj_fld))

# KI %
KIconc = [0, 1.6, 3.4, 5.3, 8.1, 10, 11.1]


def get_xpos(path):
    with open(path, 'rb') as f:
        processed_data = pickle.load(f)

    xpos = np.nanmean(processed_data['Lateral Position'])

    return xpos


def get_per(path, method):
Ejemplo n.º 15
0
def proc_jet(cropped_view, cm_px, save_fld, scint, index, test_name, test_path,
             TtoEPL, EPLtoT, offset_sl_x, offset_sl_y, data_norm, iface):
    # Create folders
    epl_fld = create_folder(save_fld + '/EPL')
    summ_fld = create_folder(save_fld + '/Summary')
    ratio_elps_fld = create_folder(save_fld + '/RatioEllipse')
    ratio_peak_fld = create_folder(save_fld + '/RatioPeak')
    vert_elps_fld = create_folder(save_fld + '/EllipseVertical')
    vert_peak_fld = create_folder(save_fld + '/PeakVertical')
    vert_opt_fld = create_folder(save_fld + '/OpticalVertical')
    ratio_elpsT_fld = create_folder(save_fld + '/RatioEllipseT')
    ratio_peakT_fld = create_folder(save_fld + '/RatioPeakT')
    bnd_fld = create_folder(save_fld + '/Boundaries')
    graph_fld = create_folder(save_fld + '/Graphs/' + test_name)
    width_fld = create_folder(save_fld + '/Widths/' + test_name)
    scans_fld = create_folder(save_fld + '/Scans/')

    # Construct EPL mapping
    data_epl = np.zeros(np.shape(data_norm), dtype=float)
    ofst_epl = np.zeros(np.shape(data_norm)[0], dtype=float)
    for _, k in enumerate(cropped_view):
        data_epl[k, :] = TtoEPL[k](data_norm[k, :])

    # Correct the EPL values
    ofst_epl = np.nanmedian(data_epl[offset_sl_x, offset_sl_y])
    data_epl -= ofst_epl

    left_bound = len(cropped_view) * [np.nan]
    right_bound = len(cropped_view) * [np.nan]
    elps_epl = len(cropped_view) * [np.nan]
    optical_diameter = len(cropped_view) * [np.nan]
    peak_epl = len(cropped_view) * [np.nan]
    axial_position = len(cropped_view) * [np.nan]
    lateral_position = len(cropped_view) * [np.nan]
    fitted_graph = len(cropped_view) * [np.nan]
    epl_graph = len(cropped_view) * [np.nan]
    optical_T = len(cropped_view) * [np.nan]
    peak_T = len(cropped_view) * [np.nan]
    elps_T = len(cropped_view) * [np.nan]

    for z, k in enumerate(cropped_view):
        smoothed = savgol_filter(data_epl[k, :], 5, 3)
        warnings.filterwarnings('ignore')
        peaks, _ = find_peaks(smoothed, width=100)
        warnings.filterwarnings('default')

        if len(peaks) == 1:
            # Offset EPL calculation (row-wise)
            warnings.filterwarnings('ignore')
            [_, _, lpos, rpos] = peak_widths(smoothed, peaks, rel_height=0.85)
            warnings.filterwarnings('default')

            #left_side = data_epl[k, 0:int(round(lpos[0]))-10]
            #right_side = data_epl[k, int(round(rpos[0]))+10:-1]
            #ofst_epl[k] = np.mean([np.nanmedian(left_side),
            #                       np.nanmedian(right_side)])
            #data_epl[k, :] -= ofst_epl[k]
            #if '005' in test_name:
            #    breakpoint()
            #smoothed -= ofst_epl[k]

            # Ellipse fitting
            warnings.filterwarnings('ignore')
            [rel_width, rel_max, lpos, rpos] = peak_widths(smoothed,
                                                           peaks,
                                                           rel_height=0.85)
            warnings.filterwarnings('default')
            rel_width = rel_width[0]
            rel_max = rel_max[0]
            left_bound[z] = lpos[0]
            right_bound[z] = rpos[0]
            ydata = smoothed[int(round(lpos[0])):int(round(rpos[0]))]

            warnings.filterwarnings('ignore')
            ide_data = ideal_ellipse(ydata, rel_width, rel_max, cm_px)
            elps_epl[z] = ide_data[0]
            fitted_graph[z] = ide_data[1]
            epl_graph[z] = ide_data[2]
            warnings.filterwarnings('default')

            optical_diameter[z] = rel_width * cm_px
            axial_position[z] = k
            lateral_position[z] = int(np.mean([lpos[0], rpos[0]]))
            peak_epl[z] = smoothed[peaks[0]]

            # Convert diameters to transmissions
            optical_T[z] = EPLtoT[k](optical_diameter[z])
            peak_T[z] = EPLtoT[k](peak_epl[z])
            elps_T[z] = EPLtoT[k](elps_epl[z])

            # Plot the fitted and EPL graphs
            if z % 15 == 0:
                # Ellipse
                plot_ellipse(epl_graph[z], fitted_graph[z],
                             '{0}/{1}_{2:03d}.png'.format(graph_fld, scint, k))
                plt.close()

                plot_widths(data_epl[k, :], peaks, rel_max, lpos[0], rpos[0],
                            '{0}/{1}_{2:03d}.png'.format(width_fld, scint, k))
                plt.close()

    # Save EPL images
    im = Image.fromarray(data_epl)
    im.save(epl_fld + '/' + test_path.rsplit('/')[-1].replace('Norm', 'EPL'))

    if len(peaks) == 1:
        lat_start = int(round(np.nanmean(lateral_position))) - 20
        lat_end = int(round(np.nanmean(lateral_position))) + 20
        signal = np.nanmean(data_epl[20:325, lat_start:lat_end])
    else:
        signal = 0

    noise = np.nanstd(data_epl[offset_sl_x, offset_sl_y])
    SNR = signal / noise

    # Calculate ratios
    ratio_ellipseT = np.array(elps_T) / np.array(optical_T)
    ratio_peakT = np.array(peak_T) / np.array(optical_T)
    ratio_ellipse = np.array(elps_epl) / np.array(optical_diameter)
    ratio_peak = np.array(peak_epl) / np.array(optical_diameter)

    mean_ratio_ellipseT = np.nanmean(ratio_ellipseT)
    mean_ratio_peakT = np.nanmean(ratio_peakT)
    mean_ratio_ellipse = np.nanmean(ratio_ellipse)
    mean_ratio_peak = np.nanmean(ratio_peak)

    cv_ratio_ellipseT = np.nanstd(ratio_ellipseT) / np.nanmean(ratio_ellipseT)
    cv_ratio_peakT = np.nanstd(ratio_peakT) / np.nanmean(ratio_peakT)
    cv_ratio_ellipse = np.nanstd(ratio_ellipse) / np.nanmean(ratio_ellipse)
    cv_ratio_peak = np.nanstd(ratio_peak) / np.nanmean(ratio_peak)

    with np.errstate(all='ignore'):
        ellipse_errors = [
            rmse(elps_epl, optical_diameter),
            mape(elps_epl, optical_diameter),
            zeta(elps_epl, optical_diameter),
            mdlq(elps_epl, optical_diameter)
        ]
        peak_errors = [
            rmse(peak_epl, optical_diameter),
            mape(peak_epl, optical_diameter),
            zeta(peak_epl, optical_diameter),
            mdlq(peak_epl, optical_diameter)
        ]

    processed_data = {
        'Diameters': [optical_diameter, elps_epl, peak_epl],
        'Transmissions': [optical_T, elps_T, peak_T],
        'Axial Position': axial_position,
        'Lateral Position': lateral_position,
        'Bounds': [left_bound, right_bound],
        'Offset EPL': ofst_epl,
        'SNR': SNR,
        'Ellipse Errors': ellipse_errors,
        'Peak Errors': peak_errors,
        'Transmission Ratios': [ratio_ellipseT, ratio_peakT],
        'EPL Ratios': [ratio_peak, ratio_ellipse],
        'Injector Face': iface
    }

    with open(summ_fld + '/' + scint + '_' + test_name + '.pckl', 'wb') as f:
        pickle.dump(processed_data, f)

    with open('{0}/{1}_{2}_y170.pckl'.format(scans_fld, scint, test_name),
              'wb') as f:
        pickle.dump(
            [data_epl[170, :],
             savgol_filter(data_epl[170, :], 105, 7)], f)

    with open('{0}/{1}_{2}_y60.pckl'.format(scans_fld, scint, test_name),
              'wb') as f:
        pickle.dump([data_epl[60, :],
                     savgol_filter(data_epl[60, :], 105, 7)], f)

    # Boundary plot
    plt.figure()
    plt.imshow(data_epl, vmin=0, vmax=0.50, zorder=1)
    plt.scatter(x=left_bound, y=axial_position, s=1, color='red', zorder=2)
    plt.scatter(x=right_bound, y=axial_position, s=1, color='red', zorder=2)
    plt.scatter(x=lateral_position,
                y=axial_position,
                s=1,
                color='white',
                zorder=2)
    plt.title(test_name)
    plt.savefig('{0}/{1}.png'.format(bnd_fld, test_name))
    plt.close()

    # Vertical ellipse variation
    plt.figure()
    plt.plot(axial_position, np.array(elps_epl) * 10, ' o')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Ellipse Diameter (mm)')
    plt.xlim([0, 480])
    plt.ylim([0.4, 5.0])
    plt.title(test_name)
    plt.savefig('{0}/{1}_{2}.png'.format(vert_elps_fld, scint, test_name))
    plt.close()

    # Vertical peak variation
    plt.figure()
    plt.plot(axial_position, np.array(peak_epl) * 10, ' o')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Peak Diameter (mm)')
    plt.xlim([0, 480])
    plt.ylim([0.4, 5.0])
    plt.title(test_name)
    plt.savefig('{0}/{1}_{2}.png'.format(vert_peak_fld, scint, test_name))
    plt.close()

    # Vertical optical variation
    plt.figure()
    plt.plot(axial_position, np.array(optical_diameter) * 10, ' o')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Optical Diameter (mm)')
    plt.xlim([0, 480])
    plt.ylim([0.4, 5.0])
    plt.title(test_name)
    plt.savefig('{0}/{1}_{2}.png'.format(vert_opt_fld, scint, test_name))
    plt.close()

    # Vertical EPL ratio (ellipse)
    plt.figure()
    plt.plot(axial_position, ratio_ellipse, ' o')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Ellipse/Optical EPL Ratio')
    plt.xlim([0, 480])
    plt.ylim([0.4, 2.1])
    plt.savefig('{0}/{1}_{2}.png'.format(ratio_elps_fld, scint, test_name))
    plt.close()

    # Vertical EPL ratio (peak)
    plt.figure()
    plt.plot(axial_position, ratio_peak, ' o')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Peak/Optical EPL Ratio')
    plt.xlim([0, 480])
    plt.ylim([0.4, 2.1])
    plt.savefig('{0}/{1}_{2}.png'.format(ratio_peak_fld, scint, test_name))
    plt.close()

    # Vertical transmission ratio (ellipse)
    plt.figure()
    plt.plot(axial_position, ratio_ellipseT, ' o')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Ellipse/Optical Transmission Ratio')
    plt.xlim([0, 480])
    plt.ylim([0.8, 2.3])
    plt.title(test_name)
    plt.savefig('{0}/{1}_{2}.png'.format(ratio_elpsT_fld, scint, test_name))
    plt.close()

    # Vertical transmission ratio (peak)
    plt.figure()
    plt.plot(axial_position, ratio_peakT, ' o')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Peak/Optical Transmission Ratio')
    plt.xlim([0, 480])
    plt.ylim([0.8, 2.3])
    plt.title(test_name)
    plt.savefig('{0}/{1}_{2}.png'.format(ratio_peakT_fld, scint, test_name))
    plt.close()
Ejemplo n.º 16
0
def main():
    # Location of APS 2018-1 data
    prj_fld = '/mnt/r/X-ray Radiography/APS 2019-1/'

    # Imaging setup
    # See 'Pixel Size' in Excel workbook
    cm_px = np.loadtxt('{}/cm_px.txt'.format(prj_fld))

    dark_path = prj_fld + '/Images/Flat/AVG_dark_current.tif'
    dark = np.array(Image.open(dark_path))

    flat_path = prj_fld + '/Images/Flat/Mean/AVG_Background_NewYAG.tif'
    flatfield = np.array(Image.open(flat_path))

    matrix_path = prj_fld + '/test_matrix.txt'
    test_matrix = pd.read_csv(matrix_path, sep='\t+', engine='python')

    # Create folder for the Normalized sets
    norm_fld = create_folder('{0}/Processed/Normalized/'.format(prj_fld))

    # Normalize the all of the images and save them
    norm_jets(prj_fld, dark, flatfield, test_matrix, norm_fld)

    # Scintillator used
    scint = 'YAG'

    # Load models from the whitebeam_2019 script
    f = open(prj_fld + '/Model/water_model_' + scint + '.pckl', 'rb')
    water_mdl = pickle.load(f)
    f.close()

    f = open(prj_fld + '/Model/KI4p8_model_' + scint + '.pckl', 'rb')
    KI4p8_mdl = pickle.load(f)
    f.close()

    # Top-level save folder
    save_fld = '{0}/Processed/{1}/'.format(prj_fld, scint)

    KI_conc = [0, 4.8]
    models = [water_mdl, KI4p8_mdl]

    # Look at only the Calibration2 files (NewYAG)
    calib2_files = glob.glob('{0}/Images/Calibration/Mean/'
                             '*Calibration2*'.format(prj_fld))

    # Add KI to the glob
    ki_files = glob.glob('{0}/Images/Calibration/Mean/*KI*'.format(prj_fld))
    calib2_files.append(ki_files[0])

    # Get Calibration2 file names to look up in matrix table
    calib2_names = [
        split(x)[1].rsplit('.')[0].rsplit('AVG_')[1] for x in calib2_files
    ]

    for index, test_name in enumerate(test_matrix['Test']):
        if test_name in calib2_names:
            test_path = norm_fld + '/Norm_' + test_name + '.tif'

            # Load relevant model
            if 'KI' in test_name:
                model = models[1]
            else:
                model = models[0]
            TtoEPL = model[0]
            EPLtoT = model[1]

            # Cropping window
            crop_start = test_matrix['Cropping Start'][index]
            crop_stop = 480
            cropped_view = np.linspace(start=crop_start,
                                       stop=crop_stop,
                                       num=crop_stop - crop_start + 1,
                                       dtype=int)

            # ROI for offset calculations
            roi = test_matrix['ROI'][index]
            sl_x_start = int(roi.rsplit(',')[0].rsplit(':')[0][1:])
            sl_x_end = int(roi.rsplit(',')[0].rsplit(':')[1])
            offset_sl_x = slice(sl_x_start, sl_x_end)

            sl_y_start = int(roi.rsplit(",")[1].rsplit(":")[0])
            sl_y_end = int(roi.rsplit(",")[1].rsplit(":")[1][:-1])
            offset_sl_y = slice(sl_y_start, sl_y_end)

            # Injector face
            iface = test_matrix['Injector Face'][index]

            # Load in normalized images
            data_norm = np.array(Image.open(test_path))

            # Process the jet file
            proc_jet(cropped_view, cm_px, save_fld, scint, index, test_name,
                     test_path, TtoEPL, EPLtoT, offset_sl_x, offset_sl_y,
                     data_norm, iface)
Ejemplo n.º 17
0
"""

import glob
import h5py
import numpy as np

import matplotlib.pyplot as plt
from PIL import Image
from scipy.interpolate import interp1d

from general.calc_statistics import rmse
from general.misc import create_folder

prj_fld = '/mnt/r/X-ray Radiography/APS 2018-1/'
hdf5_fld = '{0}/HDF5'.format(prj_fld)
mb_fld = create_folder('{0}/Monobeam/SC'.format(prj_fld))


def horiz_scan(xx, image_h_x, yy, image_h_y, img, EPL, x, y):
    # Set min/max X locations
    minX = -3.5
    maxX = 3.5

    # Get horizontal scan indices
    h_y = yy[image_h_y]
    h_x1 = xx[image_h_x[0]]
    h_x2 = xx[image_h_x[1]]
    h_xslice = list(range(np.argmin(abs(-5 - x)), np.argmin(abs(5 - x))))

    # APS data
    aps_ind = slice(np.argmin(abs(x - minX)), np.argmin(abs(x - maxX)))
Ejemplo n.º 18
0
def main():
    # Location of APS 2018-1 data
    prj_fld = '/mnt/r/X-ray Radiography/APS 2018-1/'

    # Imaging setup
    # See 'APS White Beam.xlsx -> Pixel Size'
    cm_px = np.loadtxt('{0}/cm_px.txt'.format(prj_fld))

    dark_path = prj_fld + '/Images/Uniform_Jets/Mean/AVG_Jet_dark2.tif'
    dark = np.array(Image.open(dark_path))

    flat_path = prj_fld + '/Images/Uniform_Jets/Mean/AVG_Jet_flat2.tif'
    flatfield = np.array(Image.open(flat_path))

    matrix_path = prj_fld + '/APS White Beam.txt'
    test_matrix = pd.read_csv(matrix_path, sep='\t+', engine='python')

    norm_fld = create_folder('{0}/Processed/Normalized/'.format(prj_fld))

    # Normalize the images and save them
    norm_jets(prj_fld, dark, flatfield, test_matrix, norm_fld)

    # Scintillator
    scintillators = ['LuAG', 'YAG']

    for scint in scintillators:
        # Load models from the whitebeam_2018-1 script
        f = open(prj_fld + '/Model/water_model_' + scint + '.pckl', 'rb')
        water_mdl = pickle.load(f)
        f.close()

        f = open(prj_fld + '/Model/KI1p6_model_' + scint + '.pckl', 'rb')
        KI1p6_mdl = pickle.load(f)
        f.close()

        f = open(prj_fld + '/Model/KI3p4_model_' + scint + '.pckl', 'rb')
        KI3p4_mdl = pickle.load(f)
        f.close()

        f = open(prj_fld + '/Model/KI5p3_model_' + scint + '.pckl', 'rb')
        KI5p3_mdl = pickle.load(f)
        f.close()

        f = open(prj_fld + '/Model/KI8p1_model_' + scint + '.pckl', 'rb')
        KI8p1_mdl = pickle.load(f)
        f.close()

        f = open(prj_fld + '/Model/KI10p0_model_' + scint + '.pckl', 'rb')
        KI10p0_mdl = pickle.load(f)
        f.close()

        f = open(prj_fld + '/Model/KI11p1_model_' + scint + '.pckl', 'rb')
        KI11p1_mdl = pickle.load(f)
        f.close()

        # Top-level save folder
        save_fld = '{0}/Processed/{1}/'.format(prj_fld, scint)

        KI_conc = [0, 1.6, 3.4, 5.3, 8.1, 10, 11.1]
        models = [
            water_mdl, KI1p6_mdl, KI3p4_mdl, KI5p3_mdl, KI8p1_mdl, KI10p0_mdl,
            KI11p1_mdl
        ]

        for index, test_name in enumerate(test_matrix['Test']):
            test_path = norm_fld + '/Norm_' + test_name + '.tif'
            model = models[KI_conc.index(test_matrix['KI %'][index])]
            TtoEPL = model[0]
            EPLtoT = model[1]

            # Offset bounds found in ImageJ, X and Y are flipped!
            sl_x_start = test_matrix['BY'][index]
            sl_x_end = sl_x_start + test_matrix['Height'][index]
            offset_sl_x = slice(sl_x_start, sl_x_end)

            sl_y_start = test_matrix['BX'][index]
            sl_y_end = sl_y_start + test_matrix['Width'][index]
            offset_sl_y = slice(sl_y_start, sl_y_end)

            # Load in normalized images
            data_norm = np.array(Image.open(test_path))

            # Process the jet file
            proc_jet(cm_px, save_fld, scint, index, test_name, test_path,
                     TtoEPL, EPLtoT, offset_sl_x, offset_sl_y, data_norm)
Ejemplo n.º 19
0
def main():
    prj_fld = '/mnt/r/X-ray Radiography/APS 2019-1/'
    test_conditions = pd.read_csv('{0}/test_conditions.txt'.format(prj_fld),
                                  sep='\t+',
                                  engine='python')
    grouped = test_conditions.groupby(by=['Imaging'])
    tests_keys = list(grouped.groups.keys())[3:]

    hdf5_fld = '{0}/HDF5'.format(prj_fld)

    # Imaging setup
    # See 'Pixel Size' in Excel workbook
    cm_px = np.loadtxt('{}/cm_px.txt'.format(prj_fld))

    # Create offsets file
    open(prj_fld + '/offsets.txt', 'w').close()

    for z in tests_keys:
        indices = [
            i for i, s in enumerate(
                list(grouped.get_group(z)['Y Positions (mm)']))
            if 'to' not in s
        ]
        temp_list = list(grouped.get_group(z)['Scan'])
        EPL = len(indices) * [None]
        wbp = len(indices) * [None]
        yp = len(indices) * [None]
        scan = len(indices) * [None]
        x = len(indices) * [None]
        test = z.rsplit('_')[0]

        # Load in the relevant HDF5 scans
        for n, y in enumerate(indices):
            scan[n] = temp_list[y]
            f = h5py.File('{0}/Scan_{1}.hdf5'.format(hdf5_fld, scan[n]), 'r')
            x[n] = np.array(f['X'])
            BIM = np.array(f['BIM'])
            PIN = np.array(f['PINDiode'])
            extinction_length = np.log(BIM / PIN)
            offset = np.median(extinction_length[0:10])
            extinction_length -= offset

            # Location of injector face in px
            inj_faceY = 19

            wbp[n] = inj_faceY + round(
                float(list(grouped.get_group(z)['Y Positions (mm)'])[y]) /
                (cm_px * 10))
            yp[n] = float(list(grouped.get_group(z)['Y Positions (mm)'])[y])

            # Attenuation coefficient (total w/o coh. scattering - cm^2/g)
            # Convert to mm^2/g for mm, multiply by density in g/mm^3
            if 'KI' not in z:
                # Pure water @ 8 keV
                # <https://physics.nist.gov/PhysRefData/Xcom/html/xcom1.html>
                atten_coeff = (1.006 * 10 * (10 * 10)) * (0.001)
            elif 'KI' in z:
                # 4.8% KI in water @ 8 keV
                # <https://physics.nist.gov/PhysRefData/Xcom/html/xcom1.html>
                atten_coeff = (2.182 * 10 *
                               (10 * 10)) * (density_KIinH2O(4.8) / 1000)

            # Add in air attenuation coefficient
            #atten_coeff *= (9.227*(10*10))*(0.0012929/1000)

            # Calculate EPL and convert to um from mm
            EPL[n] = (extinction_length / atten_coeff) * 1000

            # Append offset value to file
            with open(prj_fld + '/offsets.txt', 'a') as f:
                f.write('{0}\n'.format(offset))

        # Load in corresponding EPL image and convert to um from cm
        img_path = '{0}/Images/Spray/EPL/TimeAvg/AVG_{1}_S001.tif'\
                   .format(prj_fld, z)
        img = np.array(Image.open(img_path))
        img *= 10000

        # Flip image to match MB scan
        img = np.fliplr(img)

        xx = np.linspace(1, 768, 768)
        xx = xx * cm_px * 10  # in mm
        xx = xx - np.mean(xx)

        mb_fld = create_folder('{0}/Monobeam/{1}'.format(prj_fld, z))

        for n, _ in enumerate(indices):
            plt.figure()
            plt.plot(xx[0::5],
                     img[wbp[n], :][0::5],
                     color='b',
                     marker='o',
                     fillstyle='none',
                     label='WB {0}'.format(test))
            plt.plot(x[n],
                     np.mean(EPL[n], axis=1),
                     color='r',
                     marker='s',
                     fillstyle='none',
                     label='MB {0}'.format(scan[n]))
            plt.xlim([-3, 3])
            plt.ylim([-200, 3500])
            plt.xlabel('Horizontal Location (mm)')
            plt.ylabel('EPL ($\mu$m)')
            plt.title('{0} mm Downstream - {1} & {2}'.format(
                yp[n], test, scan[n]))
            plt.legend()
            plt.savefig('{0}/comparison_{1}mm.png'.format(mb_fld, yp[n]))
            plt.close()

        plt.figure()
        plt.imshow(img, vmin=-200, vmax=3500)
        plt.colorbar()
        plt.title('EPL ($\mu$m) Mapping of Spray - {0}'.format(test))
        for n, _ in enumerate(indices):
            plt.plot(np.linspace(1, 768, 768),
                     np.linspace(wbp[n], wbp[n], 768),
                     label='{0}'.format(scan[n]))
        plt.legend()
        plt.savefig('{0}/Spray Image.png'.format(mb_fld))
        plt.close()

        with open('{0}/monobeam_data.pckl'.format(mb_fld), 'wb') as f:
            pickle.dump([EPL, x, scan, wbp, yp], f)
Ejemplo n.º 20
0
def main():
    # Location of APS 2018-1 data
    prj_fld = '/mnt/r/X-ray Radiography/APS 2018-1/'

    # Load XOP spectra
    input_folder = prj_fld + '/Spectra_Inputs'
    input_spectra = xop(input_folder + '/xsurface1.dat')

    # Get energy values
    energy = input_spectra['Energy']

    # Find the angles corresponding to the 2018-1 image vertical pixels
    angles_mrad, flatfield_avg = spectra_angles(
        '{0}/Images/Uniform_Jets/Mean/AVG_'
        'Jet_flat2.tif'.format(prj_fld))

    # Find the index that best approximates middle (angle = 0)
    middle_index = np.argmin(abs(angles_mrad))

    # Create an interpolation object based on angle
    # Passing in an angle in mrad will output an interpolated spectra (w/ XOP as reference)
    spectra_linfit = interp1d(input_spectra['Angle'],
                              input_spectra['Intensity'],
                              axis=0)

    # Create an array containing spectra corresponding to each row of the 2018-1 images
    spectra2D = spectra_linfit(angles_mrad)

    # Middle spectra
    spectra_middle = spectra2D[middle_index, :]

    # Load NIST XCOM attenuation curves
    YAG_atten = mass_atten(['YAG'], xcom=1, col=3, keV=200)
    LuAG_atten = mass_atten(['LuAG'], xcom=1, col=3, keV=200)

    # Reshape XCOM x-axis to match XOP
    YAG_atten = xcom_reshape(YAG_atten, energy)
    LuAG_atten = xcom_reshape(LuAG_atten, energy)

    # Scintillator EPL
    YAG_epl = 0.05  # 500 um
    LuAG_epl = 0.01  # 100 um

    ## Density in g/cm^3
    # Scintillator densities from Crytur <https://www.crytur.cz/materials/yagce/>
    YAG_den = 4.57
    LuAG_den = 6.73

    ## Apply Beer-Lambert Law
    # Find detected scintillator spectrum (along middle) and response curves (no filters)
    LuAG_resp = scint_respfn(spectra_linfit, LuAG_atten, LuAG_den, LuAG_epl)
    YAG_resp = scint_respfn(spectra_linfit, YAG_atten, YAG_den, YAG_epl)

    # Find detected spectra (no filters)
    LuAG_detected_nofilters = np.array([x * LuAG_resp for x in spectra2D])
    YAG_detected_nofilters = np.array([x * YAG_resp for x in spectra2D])

    # Use filters
    LuAG = map(lambda x: filtered_spectra(energy, x, LuAG_resp), spectra2D)
    LuAG = list(LuAG)
    spectra_filtered = np.swapaxes(LuAG, 0, 1)[0]
    LuAG_detected = np.swapaxes(LuAG, 0, 1)[1]

    YAG = map(lambda x: filtered_spectra(energy, x, YAG_resp), spectra2D)
    YAG = list(YAG)
    YAG_detected = np.swapaxes(YAG, 0, 1)[1]

    ## Plot figures
    plot_folder = create_folder(prj_fld + '/Figures/Energy_Spectra')

    # Create vertical integrated power curves
    integrated_xray = np.trapz(spectra2D, energy, axis=1)
    integrated_xray_filtered = np.trapz(spectra_filtered, energy, axis=1)
    integrated_LuAG = np.trapz(LuAG_detected_nofilters, energy, axis=1)
    integrated_YAG = np.trapz(YAG_detected_nofilters, energy, axis=1)
    integrated_LuAG_filtered = np.trapz(LuAG_detected, energy)
    integrated_YAG_filtered = np.trapz(YAG_detected, energy)

    # Integrated plots
    plt.figure()
    plt.plot(integrated_xray, color='black', linewidth=1.5, label='X-ray Beam')
    plt.plot(integrated_xray_filtered,
             color='black',
             linestyle='--',
             linewidth=1.5,
             label='X-ray Beam (filtered)')
    plt.plot(integrated_LuAG,
             color='cornflowerblue',
             linewidth=1.5,
             label='LuAG')
    plt.plot(integrated_LuAG_filtered,
             color='cornflowerblue',
             linestyle='--',
             linewidth=1.5,
             label='LuAG (filtered)')
    plt.plot(integrated_YAG, color='seagreen', linewidth=1.5, label='YAG')
    plt.plot(integrated_YAG_filtered,
             color='seagreen',
             linestyle='--',
             linewidth=1.5,
             label='YAG (filtered)')
    plt.legend()
    plt.savefig(plot_folder + '/integrated_intensity.png')
    plt.close()

    # Integrated and normalized (filtered) plots
    plt.figure()
    plt.plot(integrated_xray_filtered / max(integrated_xray_filtered),
             zorder=1,
             color='black',
             linewidth=1.5,
             label='X-ray Beam (filtered)')
    plt.plot(integrated_LuAG_filtered / max(integrated_LuAG_filtered),
             zorder=2,
             color='cornflowerblue',
             linewidth=1.5,
             label='LuAG (filtered)')
    plt.plot(integrated_YAG_filtered / max(integrated_YAG_filtered),
             zorder=3,
             color='seagreen',
             linewidth=1.5,
             label='YAG (filtered)')
    plt.plot(flatfield_avg / max(flatfield_avg),
             zorder=4,
             color='red',
             linewidth=1.5,
             label='Flat Field')
    plt.legend()
    plt.savefig(plot_folder + '/integrated_norm_intensity.png')
    plt.close()

    # Scintillator response
    plt.figure()
    plt.plot(energy / 1000,
             LuAG_resp,
             linewidth=1.5,
             color='cornflowerblue',
             label='LuAG')
    plt.plot(energy / 1000,
             YAG_resp,
             linewidth=1.5,
             color='seagreen',
             label='YAG')
    plt.legend()
    plt.xlabel('Energy (keV)')
    plt.ylabel('Scintillator Response')
    plt.savefig(plot_folder + '/scintillator_response.png')
    plt.close()

    # Spectra along middle
    plt.figure()
    plt.plot(energy / 1000,
             spectra_middle,
             linewidth=1.5,
             color='black',
             label='Incident')
    plt.plot(energy / 1000,
             spectra_filtered[middle_index, :],
             linewidth=1.5,
             color='black',
             linestyle='--',
             label='Incident (filtered)')
    plt.plot(energy / 1000,
             LuAG_detected_nofilters[middle_index, :],
             linewidth=1.5,
             color='cornflowerblue',
             label='LuAG')
    plt.plot(energy / 1000,
             LuAG_detected[middle_index, :],
             linewidth=1.5,
             color='cornflowerblue',
             linestyle='--',
             label='LuAG (filtered)')
    plt.plot(energy / 1000,
             YAG_detected_nofilters[middle_index, :],
             linewidth=1.5,
             color='seagreen',
             label='YAG')
    plt.plot(energy / 1000,
             YAG_detected[middle_index, :],
             linewidth=1.5,
             color='seagreen',
             linestyle='--',
             label='YAG (filtered)')
    plt.legend()
    plt.xlabel('Energy (keV)')
    plt.ylabel('Intensity')
    plt.savefig(plot_folder + '/middle_spectra.png')
    plt.close()

    # LuAG filtered spectra at various locations
    plt.figure()
    plt.plot(energy / 1000,
             LuAG_detected[middle_index, :],
             linewidth=1.5,
             color='black',
             label='{0}'.format(middle_index))
    plt.plot(energy / 1000,
             LuAG_detected[middle_index + 50, :],
             linewidth=1.5,
             color='blue',
             label='{0}'.format(middle_index + 50))
    plt.plot(energy / 1000,
             LuAG_detected[middle_index - 50, :],
             linewidth=1.5,
             color='blue',
             linestyle='--',
             label='{0}'.format(middle_index - 50))
    plt.plot(energy / 1000,
             LuAG_detected[middle_index + 100, :],
             linewidth=1.5,
             color='red',
             label='{0}'.format(middle_index + 100))
    plt.plot(energy / 1000,
             LuAG_detected[middle_index - 100, :],
             linewidth=1.5,
             color='red',
             linestyle='--',
             label='{0}'.format(middle_index - 100))
    plt.legend()
    plt.title('Filtered')
    plt.xlabel('Energy (keV)')
    plt.ylabel('Intensity')
    plt.savefig(plot_folder + '/LuAG_filtered_spectra.png')
    plt.close()

    # YAG filtered spectra at various locations
    plt.figure()
    plt.plot(energy / 1000,
             YAG_detected[middle_index, :],
             linewidth=1.5,
             color='black',
             label='{0}'.format(middle_index))
    plt.plot(energy / 1000,
             YAG_detected[middle_index + 50, :],
             linewidth=1.5,
             color='blue',
             label='{0}'.format(middle_index + 50))
    plt.plot(energy / 1000,
             YAG_detected[middle_index - 50, :],
             linewidth=1.5,
             color='blue',
             linestyle='--',
             label='{0}'.format(middle_index - 50))
    plt.plot(energy / 1000,
             YAG_detected[middle_index + 100, :],
             linewidth=1.5,
             color='red',
             label='{0}'.format(middle_index + 100))
    plt.plot(energy / 1000,
             YAG_detected[middle_index - 100, :],
             linewidth=1.5,
             color='red',
             linestyle='--',
             label='{0}'.format(middle_index - 100))
    plt.legend()
    plt.title('Filtered')
    plt.xlabel('Energy (keV)')
    plt.ylabel('Intensity')
    plt.savefig(plot_folder + '/YAG_filtered_spectra.png')
    plt.close()

    # X-ray spectra at various locations
    plt.figure()
    plt.plot(energy / 1000,
             spectra2D[middle_index, :],
             linewidth=1.5,
             color='black',
             label='{0}'.format(middle_index))
    plt.plot(energy / 1000,
             spectra2D[middle_index + 50, :],
             linewidth=1.5,
             color='blue',
             label='{0}'.format(middle_index + 50))
    plt.plot(energy / 1000,
             spectra2D[middle_index - 50, :],
             linewidth=1.5,
             color='blue',
             linestyle='--',
             label='{0}'.format(middle_index - 50))
    plt.plot(energy / 1000,
             spectra2D[middle_index + 100, :],
             linewidth=1.5,
             color='red',
             label='{0}'.format(middle_index + 100))
    plt.plot(energy / 1000,
             spectra2D[middle_index - 100, :],
             linewidth=1.5,
             color='red',
             linestyle='--',
             label='{0}'.format(middle_index - 100))
    plt.legend()
    plt.title('Unfiltered')
    plt.xlabel('Energy (keV)')
    plt.ylabel('Intensity')
    plt.savefig(plot_folder + '/xray_spectra.png')
    plt.close()
Ejemplo n.º 21
0
def main():
    # Coding logic:
    #   X Read in all file names
    #   O Read in KI parameters:
    #       O Read ratio_peakT
    #       O Read ratio_ellipseT

    # Location of APS 2019-1 data
    prj_fld = '/mnt/r/X-ray Radiography/APS 2019-1/'

    # Save location for the plots
    plt_fld = create_folder('{0}/Figures/Cal_Summary/'.format(prj_fld))

    # Test matrix
    test_matrix = pd.read_csv('{0}/test_matrix.txt'.format(prj_fld),
                              sep='\t+',
                              engine='python')

    # Processed data sets location
    proc_fld = '{0}/Processed/YAG/Summary/'.format(prj_fld)

    # Read in all file names
    water_tests = glob.glob(proc_fld + '/*Calibration2*')
    ki_tests = glob.glob(proc_fld + '/*KI*')

    # Read in axial positions
    water_apos = [get_ypos(x) for x in water_tests]
    ki_apos = get_ypos(ki_tests[0])

    # Read in water lateral positions
    posn = np.array([get_xpos(x) for x in water_tests])
    posn[np.abs(250 - posn) <= 11] = int(0)
    posn[np.abs(390 - posn) <= 11] = int(1)
    posn[np.abs(510 - posn) <= 11] = int(2)
    posn = posn.astype(int)

    # Indices corresponding to each of the positions
    ind_left = np.where(posn == 0)[0]
    ind_midl = np.where(posn == 1)[0]
    ind_rght = np.where(posn == 2)[0]

    # Indices of only the top injector face (iface = 16)
    top_ind = np.concatenate((ind_left[-2:], ind_midl[-2:], ind_rght[-2:]))

    # Setup water tags for plots
    lbls = ['Left', 'Middle', 'Right']
    colr = ['lightcoral', 'forestgreen', 'cornflowerblue']
    mrkr = ['s', 'o', '^']

    # Read in transmission ratios
    water_elpsT = np.array([get_ellipseT(x) for x in water_tests])
    ki_elpsT = np.array(get_ellipseT(ki_tests[0]))
    water_peakT = np.array([get_peakT(x) for x in water_tests])
    ki_peakT = np.array(get_peakT(ki_tests[0]))

    # Summarize the CF
    water_elpsCF = np.array([np.nanmedian(x) for x in water_elpsT])
    water_peakCF = np.array([np.nanmedian(x) for x in water_peakT])
    ki_elpsCF = np.nanmedian(ki_elpsT)
    ki_peakCF = np.nanmedian(ki_peakT)

    # Consolidate water CF into only the top injector face (iface = 16)
    water_elpsCF_top = np.median(water_elpsCF[top_ind])
    water_peakCF_top = np.median(water_peakCF[top_ind])

    # Read in Injector Face locations
    iface = np.array([get_iface(x) for x in water_tests])

    # Save the CF
    np.savetxt('{0}/cf_water.txt'.format(proc_fld),
               np.c_[iface, water_elpsCF, water_peakCF],
               delimiter='\t',
               header='IFace\telpsCF\tpeakCF')

    np.savetxt('{0}/cf_summary.txt'.format(proc_fld),
               (water_elpsCF_top, water_peakCF_top, ki_elpsCF, ki_peakCF),
               delimiter='\t',
               header='Water elpsCF\tWater peakCF\tKI elpsCF\tKI peakCF')

    ##########################################################################
    ## PLOTS (O - Planned, X - Completed)
    ##      X--> Vertical EllipseT (combined)
    ##              X--> FIG1: Water
    ##              X--> FIG2: KI
    ##      X--> Vertical EllipseT (left/middle/right subplots)
    ##              X--> FIG3: Water
    ##      X--> Vertical PeakT (combined)
    ##              X--> FIG4: Water
    ##              X--> FIG5: KI
    ##      X--> Vertical PeakT (left/middle/right subplots)
    ##              X--> FIG6: Water
    ##########################################################################

    # FIG1: Water vertical EllipseT
    plt.figure()
    [
        plt.plot(
            water_apos[i],
            water_elpsT[i],
            marker=mrkr[posn[i]],
            markerfacecolor=colr[posn[i]],
            markeredgecolor=colr[posn[i]],
            linestyle='',
        ) for i, _ in enumerate(water_tests)
    ]
    leg_el = [
        Line2D([0], [0],
               color=colr[0],
               marker=mrkr[0],
               linestyle='',
               markeredgecolor=colr[0],
               label=lbls[0]),
        Line2D([0], [0],
               color=colr[1],
               marker=mrkr[1],
               linestyle='',
               markeredgecolor=colr[1],
               label=lbls[1]),
        Line2D([0], [0],
               color=colr[2],
               marker=mrkr[2],
               linestyle='',
               markeredgecolor=colr[2],
               label=lbls[2])
    ]
    plt.legend(handles=leg_el)
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Correction Factor (-)')
    plt.title('Water EllipseT')
    plt.savefig('{0}/water_vert_elpsT.png'.format(plt_fld))

    # FIG2: KI vertical EllipseT
    plt.figure()
    plt.plot(ki_apos, ki_elpsT, marker='o', linestyle='')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Correction Factor (-)')
    plt.title('KI EllipseT')
    plt.savefig('{0}/ki_vert_elpsT.png'.format(plt_fld))
    plt.close()

    # FIG3: Vertical EllipseT (left/middle/right)
    plt.subplots(3, 1, sharex=True, figsize=(15, 15))
    # Water vertical EllipseT (left)
    plt.subplot(311)
    [
        plt.plot(water_apos[i],
                 water_elpsT[i],
                 marker=mrkr[posn[i]],
                 linestyle='',
                 label='{0}'.format(iface[i])) for i in ind_left
    ]
    plt.legend()
    plt.ylabel('Correction Factor (-)')
    plt.title('Water EllipseT Left')
    # Water vertical EllipseT (middle)
    plt.subplot(312)
    [
        plt.plot(water_apos[i],
                 water_elpsT[i],
                 marker=mrkr[posn[i]],
                 linestyle='',
                 label='{0}'.format(iface[i])) for i in ind_midl
    ]
    plt.legend()
    plt.ylabel('Correction Factor (-)')
    plt.title('Water EllipseT Middle')
    # Water vertical EllipseT (right)
    plt.subplot(313)
    [
        plt.plot(water_apos[i],
                 water_elpsT[i],
                 marker=mrkr[posn[i]],
                 linestyle='',
                 label='{0}'.format(iface[i])) for i in ind_rght
    ]
    plt.legend()
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Correction Factor (-)')
    plt.title('Water EllipseT Right')
    plt.savefig('{0}/water_vert_separate_elpsT.png'.format(plt_fld))

    # FIG4: Water vertical PeakT
    plt.figure()
    [
        plt.plot(
            water_apos[i],
            water_peakT[i],
            marker=mrkr[posn[i]],
            markerfacecolor=colr[posn[i]],
            markeredgecolor=colr[posn[i]],
            linestyle='',
        ) for i, _ in enumerate(water_tests)
    ]
    leg_el = [
        Line2D([0], [0],
               color=colr[0],
               marker=mrkr[0],
               linestyle='',
               markeredgecolor=colr[0],
               label=lbls[0]),
        Line2D([0], [0],
               color=colr[1],
               marker=mrkr[1],
               linestyle='',
               markeredgecolor=colr[1],
               label=lbls[1]),
        Line2D([0], [0],
               color=colr[2],
               marker=mrkr[2],
               linestyle='',
               markeredgecolor=colr[2],
               label=lbls[2])
    ]
    plt.legend(handles=leg_el)
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Correction Factor (-)')
    plt.title('Water PeakT')
    plt.savefig('{0}/water_vert_peakT.png'.format(plt_fld))

    # FIG5: KI vertical EllipseT
    plt.figure()
    plt.plot(ki_apos, ki_peakT, marker='o', linestyle='')
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Correction Factor (-)')
    plt.title('KI PeakT')
    plt.savefig('{0}/ki_vert_peakT.png'.format(plt_fld))
    plt.close()

    # FIG6: Vertical PeakT (left/middle/right)
    plt.subplots(3, 1, sharex=True, figsize=(15, 15))
    # Water vertical PeakT (left)
    plt.subplot(311)
    [
        plt.plot(water_apos[i],
                 water_peakT[i],
                 marker=mrkr[posn[i]],
                 linestyle='',
                 label='{0}'.format(iface[i])) for i in ind_left
    ]
    plt.legend()
    plt.ylabel('Correction Factor (-)')
    plt.title('Water PeakT Left')
    # Water vertical PeakT (middle)
    plt.subplot(312)
    [
        plt.plot(water_apos[i],
                 water_peakT[i],
                 marker=mrkr[posn[i]],
                 linestyle='',
                 label='{0}'.format(iface[i])) for i in ind_midl
    ]
    plt.legend()
    plt.ylabel('Correction Factor (-)')
    plt.title('Water PeakT Middle')
    # Water vertical PeakT (right)
    plt.subplot(313)
    [
        plt.plot(water_apos[i],
                 water_peakT[i],
                 marker=mrkr[posn[i]],
                 linestyle='',
                 label='{0}'.format(iface[i])) for i in ind_rght
    ]
    plt.legend()
    plt.xlabel('Axial Position (px)')
    plt.ylabel('Correction Factor (-)')
    plt.title('Water PeakT Right')
    plt.savefig('{0}/water_vert_separate_peakT.png'.format(plt_fld))
Ejemplo n.º 22
0
    ij30video_fld = '{}/0p30gpm_Video/VTK'.format(prj_fld)
    ij45_fld = '{}/0p45gpm/VTK'.format(prj_fld)
    ij45avg_fld = '{}/0p45gpm_AVG/VTK'.format(prj_fld)
    ij45video_fld = '{}/0p45gpm_Video/VTK'.format(prj_fld)

    # VTK files
    ij30 = glob.glob('{}/*.vti'.format(ij30_fld))
    ij30avg = glob.glob('{}/*.vti'.format(ij30avg_fld))
    ij30video = glob.glob('{}/*.vti'.format(ij30video_fld))

    ij45 = glob.glob('{}/*.vti'.format(ij45_fld))
    ij45avg = glob.glob('{}/*.vti'.format(ij45avg_fld))
    ij45video = glob.glob('{}/*.vti'.format(ij45video_fld))

    # Output slice folders
    slice30_fld = create_folder('{}/0p30gpm/Slice/'.format(prj_fld))
    slice30avg_fld = create_folder('{}/0p30gpm_AVG/Slice/'.format(prj_fld))
    slice30vid_fld = create_folder('{}/0p30gpm_Video/Slice/'.format(prj_fld))

    slice45_fld = create_folder('{}/0p45gpm/Slice/'.format(prj_fld))
    slice45avg_fld = create_folder('{}/0p45gpm_AVG/Slice/'.format(prj_fld))
    slice45vid_fld = create_folder('{}/0p45gpm_Video/Slice/'.format(prj_fld))

    # Output surface folders
    surf30_fld = create_folder('{}/0p30gpm/Surface/'.format(prj_fld))
    surf30avg_fld = create_folder('{}/0p30gpm_AVG/Surface/'.format(prj_fld))
    surf30vid_fld = create_folder('{}/0p30gpm_Video/Surface/'.format(prj_fld))

    surf45_fld = create_folder('{}/0p45gpm/Surface/'.format(prj_fld))
    surf45avg_fld = create_folder('{}/0p45gpm_AVG/Surface/'.format(prj_fld))
    surf45vid_fld = create_folder('{}/0p45gpm_Video/Surface/'.format(prj_fld))
Ejemplo n.º 23
0
def main():
    # Location of APS 2018-1 data
    prj_fld = '/mnt/r/X-ray Radiography/APS 2018-1/'

    # Save location for the plots
    plots_folder = create_folder('{0}/Figures/Jet_HorizSumm/'.format(prj_fld))

    # Scintillator
    scintillators = ['LuAG', 'YAG']

    # KI %
    KI_conc = [0, 1.6, 3.4, 5.3, 8, 10, 11.1]

    # Test matrix
    test_matrix = pd.read_csv('{0}/APS White Beam.txt'.format(prj_fld),
                              sep='\t+',
                              engine='python')

    # Crop down the test matrix
    test_matrix = test_matrix[['Test', 'Nozzle Diameter (um)', 'KI %']].copy()

    for scint in scintillators:
        # Processed data sets location
        prc_fld = '{0}/Processed/{1}/Summary/'.format(prj_fld, scint)

        # Groups
        rpkT = 'Ratio Peak T'
        relT = 'Ratio Ellipse T'

        # Horizontal variation
        horiz_matrix = test_matrix[test_matrix['Test'].str.contains(
            'mm')].copy()
        horiz_matrix['X Position'] = [
            get_xpos('{0}/{1}_{2}.pckl'.format(prc_fld, scint, x))
            for x in horiz_matrix['Test']
        ]

        # Sort horiz_matrix by X position, re-index, and drop the outliers
        horiz_matrix.sort_values(by=['X Position'], inplace=True)
        horiz_matrix.reset_index(inplace=True)
        horiz_matrix.drop([0, len(horiz_matrix) - 1], inplace=True)

        # Get horizontal values
        horiz_matrix[relT] = [
            get_mean_elpsT('{0}/{1}_{2}.pckl'.format(prc_fld, scint, x))
            for x in horiz_matrix['Test']
        ]
        horiz_matrix[rpkT] = [
            get_mean_peakT('{0}/{1}_{2}.pckl'.format(prc_fld, scint, x))
            for x in horiz_matrix['Test']
        ]
        breakpoint()
        # Create a fit to the horizontal variation
        xData = horiz_matrix['X Position']
        yData = horiz_matrix[relT]
        yData = savgol_filter(yData, 55, 3)
        XtoCF = CubicSpline(xData, yData)

        # Horizontal plot
        plt.figure()
        plt.plot(horiz_matrix['X Position'],
                 horiz_matrix[rpkT],
                 color='olivedrab',
                 marker='s',
                 label=rpkT)
        plt.plot(xData, XtoCF(xData), color='cornflowerblue', label='Fit')
        plt.plot(horiz_matrix['X Position'],
                 horiz_matrix[relT],
                 fillstyle='none',
                 color='olivedrab',
                 marker='s',
                 label=relT)
        plt.legend()
        plt.title('{0} - Horizontal Variation - 700 um, 10% KI'.format(scint))
        plt.savefig('{0}/{1}_horiz.png'.format(plots_folder, scint))
        plt.close()

        # Save the linear fitted correction factors
        with open('{0}/Processed/{1}/{1}_peakT_cf.txt'.format(prj_fld, scint),
                  'wb') as f:
            np.savetxt(f, peakT_combi_fit['function'](KI_conc))

        with open('{0}/Processed/{1}/{1}_elpsT_cf.txt'.format(prj_fld, scint),
                  'wb') as f:
            np.savetxt(f, elpsT_combi_fit['function'](KI_conc))
Ejemplo n.º 24
0
@author: rahmann
"""

import glob
import h5py
import pickle
import numpy as np

from PIL import Image

from monobeam_aecn import horiz_scan
from general.misc import create_folder

prj_fld = '/mnt/r/X-ray Radiography/APS 2018-1/'
hdf5_fld = '{0}/HDF5'.format(prj_fld)
mb_fld = create_folder('{0}/Monobeam/AeroECN'.format(prj_fld))


def main():
    # See 'Spray Imaging' in Excel workbook
    cm_px = np.loadtxt('{0}/cm_px.txt'.format(prj_fld))

    fly_scan = 'Fly_Scans_208_340'

    # Injector center position on image (in pixels)
    image_inj_x = 390
    image_inj_y = 18

    # Load in fly scan data
    f = h5py.File('{0}/{1}.hdf5'.format(hdf5_fld, fly_scan), 'r')
    x = np.array(f['X'])
Ejemplo n.º 25
0
def saveConvergence(data, name, folder):
    folder = create_folder(folder)
    np.save('{0}/{1}.npy'.format(folder, name), data)

    return
Ejemplo n.º 26
0
"""

import cv2
import glob
import h5py
import numpy as np

import matplotlib.pyplot as plt
from PIL import Image
from skimage.filters import (threshold_otsu, threshold_local)

from general.misc import create_folder

inp_fld = '/mnt/f/X-ray Tomography/3DXray-Tomo/Processed/IJ/'
out_fld = create_folder('/mnt/r/X-ray Tomography/2018_DataSets/'
                        'ImageCalibration/OpenCV/')


def resizeData(path):
    data = np.array(Image.open(path))
    input_size = data.shape[0]
    bin_size = 2
    output_size = input_size // bin_size
    data_reshaped = data.reshape(
        (1, output_size, bin_size, output_size, bin_size)).max(4).max(2)

    return data_reshaped[0]


def makeBlob():
    # Setup SimpleBlobDetector parameters
Ejemplo n.º 27
0
def main():
    # Location of APS 2018-1 data
    prj_fld = '/mnt/r/X-ray Radiography/APS 2018-1/'

    # Save location for the plots
    plots_folder = create_folder(
        '{0}/Figures/Jet_EPL_Summary/'.format(prj_fld))

    # Scintillator
    scintillators = ['LuAG', 'YAG']

    # KI %
    KI_conc = [0, 1.6, 3.4, 5.3, 8.1, 10, 11.1]

    # Test matrix
    test_matrix = pd.read_csv('{0}/APS White Beam.txt'.format(prj_fld),
                              sep='\t+',
                              engine='python')

    # Crop down the test matrix
    test_matrix = test_matrix[['Test', 'Nozzle Diameter (um)', 'KI %']].copy()

    for scint in scintillators:
        # Processed data sets location
        prc_fld = '{0}/Processed/{1}/Summary/'.format(prj_fld, scint)

        # Vertical variation
        vert_mat = test_matrix[~test_matrix['Test'].str.contains('mm')].copy()

        # Groups
        grp1 = 'Nozzle Diameter (um)'
        grp2 = 'KI %'
        rpk = 'Ratio Peak'
        rel = 'Ratio Ellipse'

        # Get vertical values
        vert_mat[rel] = [
                         get_elps('{0}/{1}_{2}.pckl'\
                                  .format(prc_fld, scint, x))
                         for x in vert_mat['Test']
                         ]
        vert_mat[rpk] = [
                         get_peak('{0}/{1}_{2}.pckl'\
                                  .format(prc_fld, scint, x))
                         for x in vert_mat['Test']
                         ]
        vert_peak_grp = vert_mat.groupby([grp1, grp2])\
                                .apply(lambda x: np.mean(x[rpk], axis=0))
        vert_elps_grp = vert_mat.groupby([grp1, grp2])\
                                .apply(lambda x: np.mean(x[rel], axis=0))
        axial_loc = np.linspace(start=20,
                                stop=325,
                                num=325 - 20 + 1,
                                dtype=int)

        linecolors = [
            'dimgray', 'firebrick', 'goldenrod', 'mediumseagreen', 'steelblue',
            'mediumpurple', 'hotpink'
        ]
        linelabels = ['0%', '1.6%', '3.4%', '4.8%', '8%', '10%', '11.1%']

        warnings.filterwarnings('ignore')
        # Vertical peak plot
        fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
        fig.set_size_inches(12, 6)
        for i, x in enumerate(linecolors):
            ax1.plot(axial_loc[2:-1],
                     vert_peak_grp[700, KI_conc[i]][2:-1],
                     color=x,
                     linewidth=2.0)
            ax2.plot(axial_loc[2:-1],
                     vert_peak_grp[2000, KI_conc[i]][2:-1],
                     color=x,
                     linewidth=2.0)
        ax1.title.set_text(r'700 $\mu$m')
        ax2.title.set_text(r'2000 $\mu$m')
        ax1.set_xlabel('Axial Position (px)')
        ax2.set_xlabel('Axial Position (px)')
        ax1.set_ylabel('Correction Factor (-)')
        fig.suptitle('Vertical Variation - Ratio Peak')
        fig.legend(ax1,
                   labels=linelabels,
                   loc='center right',
                   borderaxespad=0.1,
                   title=grp2)
        plt.subplots_adjust(wspace=0.05, top=0.90)
        plt.savefig('{0}/{1}_vert_peak.png'.format(plots_folder, scint))
        plt.close()

        # Vertical elps plot
        fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
        fig.set_size_inches(12, 6)
        for i, x in enumerate(linecolors):
            ax1.plot(axial_loc[2:-1],
                     vert_elps_grp[700, KI_conc[i]][2:-1],
                     linewidth=2.0)
            ax2.plot(axial_loc[2:-1],
                     vert_elps_grp[2000, KI_conc[i]][2:-1],
                     linewidth=2.0)
        ax1.title.set_text(r'700 $\mu$m')
        ax2.title.set_text(r'2000 $\mu$m')
        ax1.set_xlabel('Axial Position (px)')
        ax2.set_xlabel('Axial Position (px)')
        ax1.set_ylabel('Correction Factor (-)')
        fig.suptitle('Vertical Variation - Ratio Ellipse')
        fig.legend(ax1,
                   labels=linelabels,
                   loc='center right',
                   borderaxespad=0.1,
                   title=grp2)
        plt.subplots_adjust(wspace=0.05, top=0.90)
        plt.savefig('{0}/{1}_vert_elps.png'.format(plots_folder, scint))
        warnings.filterwarnings('default')

        ######################################################################

        # Horizontal variation
        horiz_matrix = test_matrix[test_matrix['Test'].str\
                                                      .contains('mm')]\
                                                      .copy()
        horiz_matrix['X Position'] = [
                                      get_xpos('{0}/{1}_{2}.pckl'\
                                               .format(prc_fld, scint, x))
                                      for x in horiz_matrix['Test']
                                      ]

        # Sort horiz_matrix by X position, re-index, and drop the outliers
        horiz_matrix.sort_values(by=['X Position'], inplace=True)
        horiz_matrix.reset_index(inplace=True)
        horiz_matrix.drop([0, len(horiz_matrix) - 1], inplace=True)

        # Get horizontal values
        horiz_matrix[rel] = [
                             get_mean_elps('{0}/{1}_{2}.pckl'\
                                           .format(prc_fld, scint, x))
                             for x in horiz_matrix['Test']
                             ]
        horiz_matrix[rpk] = [
                             get_mean_peak('{0}/{1}_{2}.pckl'\
                                           .format(prc_fld, scint, x))
                             for x in horiz_matrix['Test']
                             ]

        # Normalize the horiz values to remove KI% dependency
        horiz_matrix[rel] /= max(horiz_matrix[rel])
        horiz_matrix[rpk] /= max(horiz_matrix[rpk])

        # Fit a quadratic to the horizontal values
        rel_quad = np.poly1d(
            np.polyfit(x=horiz_matrix['X Position'],
                       y=horiz_matrix[rel],
                       deg=2))

        rpk_quad = np.poly1d(
            np.polyfit(x=horiz_matrix['X Position'],
                       y=horiz_matrix[rpk],
                       deg=2))

        # Horizontal plot
        plt.figure()
        plt.plot(horiz_matrix['X Position'],
                 horiz_matrix[rpk],
                 color='olivedrab',
                 marker='s',
                 label=rpk)
        plt.plot(horiz_matrix['X Position'],
                 rpk_quad(horiz_matrix['X Position']),
                 color='black',
                 marker='s',
                 linestyle='dashed',
                 alpha=0.5,
                 label='Peak Fit')
        plt.legend()
        plt.title('{0} - Horizontal Variation - 700 um, 10% KI'.format(scint))
        plt.savefig('{0}/{1}_horiz_peak.png'.format(plots_folder, scint))
        plt.close()

        plt.figure()
        plt.plot(horiz_matrix['X Position'],
                 horiz_matrix[rel],
                 fillstyle='none',
                 color='olivedrab',
                 marker='s',
                 label=rel)
        plt.plot(horiz_matrix['X Position'],
                 rel_quad(horiz_matrix['X Position']),
                 fillstyle='none',
                 color='black',
                 marker='s',
                 linestyle='dashed',
                 alpha=0.5,
                 label='Ellipse Fit')
        plt.legend()
        plt.title('{0} - Horizontal Variation - 700 um, 10% KI'.format(scint))
        plt.savefig('{0}/{1}_horiz_elps.png'.format(plots_folder, scint))
        plt.close()

        ######################################################################

        # Mean vertical variation
        mean_matrix = test_matrix[~test_matrix['Test'].str\
                                                      .contains('mm')]\
                                                      .copy()

        # Get mean vertical values
        mean_matrix[rel] = [
                            get_mean_elps('{0}/{1}_{2}.pckl'\
                                          .format(prc_fld, scint, x))
                            for x in mean_matrix['Test']
                            ]
        mean_matrix[rpk] = [
                            get_mean_peak('{0}/{1}_{2}.pckl'\
                                          .format(prc_fld, scint, x))
                            for x in mean_matrix['Test']
                            ]

        # Calculate the mean values as needed
        pivot_mean_peak = mean_matrix.pivot_table(values=rpk,
                                                  index=[grp2],
                                                  columns=[grp1],
                                                  aggfunc=np.nanmean)
        pivot_mean_elps = mean_matrix.pivot_table(values=rel,
                                                  index=[grp2],
                                                  columns=[grp1],
                                                  aggfunc=np.nanmean)
        # Create arrays from the pivot tables
        # Could plot directly from the pivot table but I didn't want to delve
        # too deep into that
        mean_peak_700 = pivot_mean_peak[700]
        peak_700_fit = polyfit(KI_conc, mean_peak_700, 1)
        peak_700_fit_r2 = peak_700_fit['determination']
        peak_700_fit_lbl = 'y$_{700}$ = ' + '{0:0.3f}x + {1:0.3f};'\
                              'R$^2$ {2:0.0f}%'\
                              .format(
                                      peak_700_fit['polynomial'][0],
                                      peak_700_fit['polynomial'][1],
                                      100*peak_700_fit_r2
                                      )

        mean_peak_2000 = pivot_mean_peak[2000]
        peak_2000_fit = polyfit(KI_conc, mean_peak_2000, 1)
        peak_2000_fit_r2 = peak_2000_fit['determination']
        peak_2000_fit_lbl = 'y$_{2000}$ = ' + '{0:0.3f}x + {1:0.3f};'\
                               'R$^2$ {2:0.0f}%'\
                               .format(
                                       peak_2000_fit['polynomial'][0],
                                       peak_2000_fit['polynomial'][1],
                                       100*peak_2000_fit_r2
                                       )

        mean_elps_700 = pivot_mean_elps[700]
        elps_700_fit = polyfit(KI_conc, mean_elps_700, 1)
        elps_700_fit_r2 = elps_700_fit['determination']
        elps_700_fit_lbl = 'y$_{700}$ = ' + '{0:0.3f}x + {1:0.3f};'\
                              'R$^2$ {2:0.0f}%'\
                              .format(
                                      elps_700_fit['polynomial'][0],
                                      elps_700_fit['polynomial'][1],
                                      100*elps_700_fit_r2
                                      )

        mean_elps_2000 = pivot_mean_elps[2000]
        elps_2000_fit = polyfit(KI_conc, mean_elps_2000, 1)
        elps_2000_fit_r2 = elps_2000_fit['determination']
        elps_2000_fit_lbl = 'y$_{2000}$ = ' + '{0:0.3f}x + {1:0.3f};'\
                               'R$^2$ {2:0.0f}%'\
                               .format(
                                       elps_2000_fit['polynomial'][0],
                                       elps_2000_fit['polynomial'][1],
                                       100*elps_2000_fit_r2
                                       )

        # Peak plot (markers filled)
        plt.figure()
        plt.plot(KI_conc,
                 mean_peak_700,
                 color='olivedrab',
                 marker='s',
                 label='700 um')
        plt.plot(KI_conc,
                 peak_700_fit['function'](KI_conc),
                 color='teal',
                 label=peak_700_fit_lbl)
        plt.plot(KI_conc,
                 mean_peak_2000,
                 color='indianred',
                 marker='^',
                 label='2000 um')
        plt.plot(KI_conc,
                 peak_2000_fit['function'](KI_conc),
                 color='darkorange',
                 label=peak_2000_fit_lbl)
        plt.legend()
        plt.title('{0} - Ratio Peak'.format(scint))
        plt.xlabel('KI (%)')
        plt.ylabel('Correction Factor (-)')
        plt.savefig('{0}/{1}_mean_peak.png'.format(plots_folder, scint))
        plt.close()

        # Ellipse plot (markers not filled)
        plt.figure()
        plt.plot(KI_conc,
                 mean_elps_700,
                 fillstyle='none',
                 color='olivedrab',
                 marker='s',
                 label='700 um')
        plt.plot(KI_conc,
                 elps_700_fit['function'](KI_conc),
                 color='teal',
                 label=elps_700_fit_lbl)
        plt.plot(KI_conc,
                 mean_elps_2000,
                 fillstyle='none',
                 color='indianred',
                 marker='^',
                 label='2000 um')
        plt.plot(KI_conc,
                 elps_2000_fit['function'](KI_conc),
                 color='darkorange',
                 label=elps_2000_fit_lbl)
        plt.legend()
        plt.title('{0} - Ratio Ellipse'.format(scint))
        plt.xlabel('KI (%)')
        plt.ylabel('Correction Factor (-)')
        plt.savefig('{0}/{1}_mean_elps.png'.format(plots_folder, scint))
        plt.close()

        ######################################################################

        mean_peak_combi = np.mean([mean_peak_700, mean_peak_2000], axis=0)
        peak_combi_fit = polyfit(KI_conc, mean_peak_combi, 1)
        peak_combi_fit_r2 = peak_combi_fit['determination']
        peak_combi_fit_lbl = 'y = {0:0.3f}x + {1:0.3f};'\
                                 'R$^2$ {2:0.0f}%'\
                                 .format(peak_combi_fit['polynomial'][0],
                                         peak_combi_fit['polynomial'][1],
                                         100*peak_combi_fit_r2
                                         )

        mean_elps_combi = np.mean([mean_elps_700, mean_elps_2000], axis=0)
        elps_combi_fit = polyfit(KI_conc, mean_elps_combi, 1)
        elps_combi_fit_r2 = elps_combi_fit['determination']
        elps_combi_fit_lbl = 'y = {0:0.3f}x + {1:0.3f}; R$^2$ {2:0.0f}%'\
                                 .format(
                                         elps_combi_fit['polynomial'][0],
                                         elps_combi_fit['polynomial'][1],
                                         100*elps_combi_fit_r2
                                         )

        # Save the linear fitted correction factors
        with open('{0}/Processed/{1}/{1}_peak_cf.txt'\
                  .format(prj_fld, scint), 'wb') as f:
            np.savetxt(f, peak_combi_fit['function'](KI_conc))

        with open('{0}/Processed/{1}/{1}_elps_cf.txt'\
                  .format(prj_fld, scint), 'wb') as f:
            np.savetxt(f, elps_combi_fit['function'](KI_conc))

        # Map out the correction factor horizontally over an image array
        cf_fld = create_folder('{0}/Processed/{1}/CF_Map/'.format(
            prj_fld, scint))
        image_x = np.linspace(0, 767, 768)
        for KI in KI_conc:
            KIstr = str(KI).replace('.', 'p')

            # Create CF based on elps
            elps_mat = np.ones((352, 768)) * elps_combi_fit['function'](KI)
            elps_mat *= rel_quad(image_x)
            elps_im = Image.fromarray(elps_mat)
            elps_im.save('{0}/elps_{1}.tif'.format(cf_fld, KIstr))

            # Create CF based on peak
            peak_mat = np.ones((352, 768)) * peak_combi_fit['function'](KI)
            peak_mat *= rpk_quad(image_x)
            peak_im = Image.fromarray(peak_mat)
            peak_im.save('{0}/peak_{1}.tif'.format(cf_fld, KIstr))

        plt.figure()
        plt.plot(KI_conc,
                 mean_peak_combi,
                 color='lightcoral',
                 marker='s',
                 linestyle='',
                 label=rpk,
                 zorder=2)
        plt.plot(KI_conc,
                 peak_combi_fit['function'](KI_conc),
                 linestyle='-',
                 color='maroon',
                 label=peak_combi_fit_lbl,
                 zorder=1)
        plt.plot(KI_conc,
                 mean_elps_combi,
                 color='cornflowerblue',
                 marker='^',
                 linestyle='',
                 label=rel,
                 zorder=2)
        plt.plot(KI_conc,
                 elps_combi_fit['function'](KI_conc),
                 linestyle='-',
                 color='mediumblue',
                 label=elps_combi_fit_lbl,
                 zorder=1)
        plt.title('{0} - Combined'.format(scint))
        plt.legend()
        plt.xlabel('KI (%)')
        plt.ylabel('Correction Factor (-)')
        plt.savefig('{0}/{1}_combi.png'.format(plots_folder, scint))
        plt.close()
Ejemplo n.º 28
0
        #for spray, spray_fld in zip([ij30], [ij30_fld]):
        n += 1
        for i in range(201):
            #for i in range(1):
            # Import surface
            #bpy.ops.import_mesh.ply(filepath=spray[i])
            filepath = '{0}/Surface/vol{1:04d}.ply'.format(spray_fld, i)
            bpy.ops.import_mesh.ply(filepath=filepath)

            # Surface name
            surf_name = spray[i].split('\\')[-1].split('.')[0]

            # Translate and rotate spray
            D.objects[surf_name].rotation_euler = Euler(sprayRot, 'XYZ')
            D.objects[surf_name].location = sprayLoc[n]

            # Set material
            D.objects[surf_name].active_material = D.materials.get('water')

            # Output path
            outFld = create_folder('{}/ISO Blender/'.format(spray_fld))
            outPath = '{0}/{1}.png'.format(outFld, surf_name)
            C.scene.render.filepath = outPath

            # Render and save
            bpy.ops.render.render(write_still=True, use_viewport=True)

            # Clear object
            obj_del = bpy.data.objects[surf_name]
            D.objects.remove(obj_del, do_unlink=True)
Ejemplo n.º 29
0
def spray_model(spray_epl, energy, model, scint, I0, wfct):
    """
    Applies the spray to the filtered X-ray spectra.
    =============
    --VARIABLES--
    spray_epl:  Spray path lengths to iterate through.
    energy:     Energy values from XOP.
    model:      Model type (water/KI%).
    scint:      Scintillator name (LuAG/YAG).
    I0:         Detected flat field spectra.
    wfct:       Weighting function for T calculation.
    """
    global prj_fld
    global inp_fld

    # Spray densities
    if model == 'water':
        ki_perc = 0
        spray_den = 1.0
    elif model == 'KI1p6':
        ki_perc = 1.6
        spray_den = density_KIinH2O(ki_perc)
    elif model == 'KI3p4':
        ki_perc = 3.4
        spray_den = density_KIinH2O(ki_perc)
    elif model == 'KI5p3':
        ki_perc = 5.3
        spray_den = density_KIinH2O(ki_perc)
    elif model == 'KI8p1':
        ki_perc = 8.1
        spray_den = density_KIinH2O(ki_perc)
    elif model == 'KI10p0':
        ki_perc = 10.0
        spray_den = density_KIinH2O(ki_perc)
    elif model == 'KI11p1':
        ki_perc = 11.1
        spray_den = density_KIinH2O(ki_perc)

    # Spray composition
    molec = ['H2O', 'KI']
    comp = [100 - ki_perc, ki_perc]

    # Spray attenuation
    liq_atten1 = mass_atten(molec=molec, comp=comp, xcom=xcom, keV=200)
    liq_atten2 = xcom_reshape(liq_atten1, energy)
    plot_atten(liq_atten1, liq_atten2, model)

    # Detected spray spectra I
    I = [
        bl_unk(incident=incident,
               attenuation=liq_atten2['Attenuation'],
               density=spray_den,
               epl=spray_epl) for incident in I0
    ]

    # Swap the axes of I so that it's EPL (len(spray_epl)) x Row (352) x
    #   Intensity (1991)
    I = np.swapaxes(I, 0, 1)

    method = 1
    # Method 1: Ratio of areas
    if method == 1:
        Transmission = np.trapz(y=I, x=energy) / np.trapz(y=I0, x=energy)
    # Method 2: Weighted sum
    elif method == 2:
        Transmission = [np.sum((x / I0) * wfct, axis=1) for x in I]
    # Method 3: Average value
    elif method == 3:
        Transmission = np.mean(I / I0, axis=2)

    # Swap axes so that it's Row x EPL
    Transmission = np.swapaxes(Transmission, 0, 1)

    # Cubic spline fitting of Transmission and spray_epl curves
    #   Needs to be reversed b/c of monotonically increasing
    #   restriction on 'x', however this doesn't change the interp call.
    # Function that takes in I/I0 and outputs expected EPL (cm)
    TtoEPL = [
        CubicSpline(vertical_pix[::-1], spray_epl[::-1])
        for vertical_pix in Transmission
    ]

    # Function that takes in EPL (cm) value and outputs expected I/I0
    EPLtoT = [
        CubicSpline(spray_epl, vertical_pix) for vertical_pix in Transmission
    ]

    # Save model
    mdl_fld = create_folder('{0}/Model/'.format(prj_fld))

    with open('{0}/{1}_model_{2}.pckl'.format(mdl_fld, model, scint),
              'wb') as f:
        pickle.dump([TtoEPL, EPLtoT, spray_epl, Transmission], f)

    # Calculate average attenuation and transmission
    atten_avg = np.nanmean([-np.log(x) / spray_epl for x in Transmission],
                           axis=0)
    trans_avg = np.nanmean(Transmission, axis=0)

    return atten_avg, trans_avg
Ejemplo n.º 30
0
def convertVTK(ij_inp, rot, ij_out, density):
    """
    Converts individual IJ volumes.

    VARIABLES
    ---------
    ij_inp:     Input folder containing each of the LaVision DaVis volumes.
    rot:        Rotation dict to correct the volumes (see Jupyter notebook).
    ij_out:     Location to save the VTK files.
    density:    Density of the liquid to use for conversion to LVF.
                Use density=1 for no correction for the mixing cases.
    """
    # Create folders as needed
    create_folder('{0}/VTK'.format(ij_out))
    create_folder('{0}/PIM'.format(ij_out))
    create_folder('{0}/Slice-4'.format(ij_out))
    create_folder('{0}/SliceIJ'.format(ij_out))
    create_folder('{0}/Slice+4'.format(ij_out))
    create_folder('{0}/Slice+8'.format(ij_out))

    # Get total number of volumes and initialize the impingement point var
    ijPtn4_den = np.zeros((len(ij_inp), 1))
    ijPt0_den = np.zeros((len(ij_inp), 1))
    ijPt4_den = np.zeros((len(ij_inp), 1))
    ijPt8_den = np.zeros((len(ij_inp), 1))

    for i, inp in enumerate(ij_inp):
        # Load in the density volume
        # Only load in the X/Y/Z values on the first volume (always the same)
        if i == 0:
            volume, x_mm, y_mm, z_mm = load_davis(inp)

            # Flip the Y values
            y_mm = y_mm[::-1]

            # Get the location of the impingement point in mm space
            X, Y, Z = np.meshgrid(x_mm, y_mm, z_mm, indexing='ij')

            # Rotate the X, Y, Z meshgrids
            X = rotate(X, rot['Angle'], axes=rot['Axes'], reshape=False)
            Y = rotate(Y, rot['Angle'], axes=rot['Axes'], reshape=False)
            Z = rotate(Z, rot['Angle'], axes=rot['Axes'], reshape=False)

            # Center point in voxels
            center_X = 90
            center_Y = 129
            center_Z = 195

            # Impingement point in voxel coordinates (found from the rotated
            # projection images)
            ij_X = X[center_X, center_Y, center_Z]
            ij_Y = Y[center_X, center_Y, center_Z]
            ij_Z = Z[center_X, center_Y, center_Z]

            # Center the x, y, z vectors
            x_mm -= ij_X
            y_mm -= ij_Y
            z_mm -= ij_Z

            # Crop down the volume (see Jupyter notebook)
            x1 = np.argmin(np.abs(x_mm - -4.7))
            x2 = np.argmin(np.abs(x_mm - 4.7))
            y1 = np.argmin(np.abs(y_mm - -5))
            y2 = np.argmin(np.abs(y_mm - 14))
            z1 = np.argmin(np.abs(z_mm - -10))
            z2 = np.argmin(np.abs(z_mm - 10))

            # Get the origin (defines corner of the grid)
            origin = [x_mm[x1], y_mm[y1], z_mm[z1]]

            # Cropping
            x_mm = x_mm[x1:x2]
            y_mm = y_mm[y1:y2]
            z_mm = z_mm[z1:z2]

            # Save the volume extents
            np.save('{0}/VTK/x_mm.npy'.format(ij_out),
                    x_mm,
                    allow_pickle=False)
            np.save('{0}/VTK/y_mm.npy'.format(ij_out),
                    y_mm,
                    allow_pickle=False)
            np.save('{0}/VTK/z_mm.npy'.format(ij_out),
                    z_mm,
                    allow_pickle=False)

            # Get the APS locations
            ind0X = np.argmin(np.abs(x_mm - 0))
            ind0Z = np.argmin(np.abs(z_mm - 0))
            indn4Y = np.argmin(np.abs(y_mm - -4))
            ind0Y = np.argmin(np.abs(y_mm - 0))
            ind4Y = np.argmin(np.abs(y_mm - 4))
            ind8Y = np.argmin(np.abs(y_mm - 8))

        else:
            volume, _, _, _ = load_davis(inp)

        # Rotate the volume
        volume = rotate(volume, rot['Angle'], axes=rot['Axes'], reshape=False)

        # Mask out invalid values
        volume[volume < 0] = 0

        # Calculate optical depth for the mixing cases
        # Volumes were inverted (1 - buffer) in DaVis
        if density == 1:
            volume = -np.log(1 - volume)

        # Get voxel size
        dx = np.abs(x_mm[1] - x_mm[0])
        dy = np.abs(y_mm[1] - y_mm[0])
        dz = np.abs(z_mm[1] - z_mm[0])
        voxelSize = (dx, dy, dz)

        # Cropping
        volume = volume[x1:x2, y1:y2, z1:z2].astype('float32')

        # Calculate the PIM as a function of y
        # Convert volume to density, then project onto all XZ planes
        PIM = np.sum(volume / dx, axis=(0, 2)) * dx**2

        # Save the PIM trace
        np.save('{0}/PIM/{1:04d}'.format(ij_out, i), PIM, allow_pickle=False)

        # Get the intensity value at the impingement point (as density)
        ijPtn4_den[i] = volume[ind0X, indn4Y, ind0Z] / dx
        ijPt0_den[i] = volume[ind0X, ind0Y, ind0Z] / dx
        ijPt4_den[i] = volume[ind0X, ind4Y, ind0Z] / dx
        ijPt8_den[i] = volume[ind0X, ind8Y, ind0Z] / dx

        # Extract the slices as solution density
        slicen4 = volume[:, indn4Y, :].astype('float32') / dx
        slice0 = volume[:, ind0Y, :].astype('float32') / dx
        slice4 = volume[:, ind4Y, :].astype('float32') / dx
        slice8 = volume[:, ind8Y, :].astype('float32') / dx

        # Save slices as numpy files
        np.save('{0}/Slice-4/{1:04d}'.format(ij_out, i),
                slicen4,
                allow_pickle=False)
        np.save('{0}/SliceIJ/{1:04d}'.format(ij_out, i),
                slice0,
                allow_pickle=False)
        np.save('{0}/Slice+4/{1:04d}'.format(ij_out, i),
                slice4,
                allow_pickle=False)
        np.save('{0}/Slice+8/{1:04d}'.format(ij_out, i),
                slice8,
                allow_pickle=False)

        # Bin volumes down and smooth
        #volume = zoom(volume, (0.5, 0.5, 0.5))
        volume = gaussian_filter(volume, 1)

        # Convert density to liquid volume fraction (LVF)
        LVF = volume / density
        breakpoint()

        # Convert files to VTK format (make sure to normalize by grid size!)
        imageToVTK(
            '{0}/VTK/{1:04d}'.format(ij_out, i),
            origin=origin,
            spacing=voxelSize,
            pointData={'LVF': LVF / dx},
        )

    # Create a time series file
    seriesVTK(ij_out)

    # Save the impingement point values as density and LVF
    np.save('{0}/ijPtn4_den'.format(ij_out), ijPtn4_den)
    np.save('{0}/ijPtn4_LVF'.format(ij_out), ijPtn4_den / density)

    np.save('{0}/ijPt0_den'.format(ij_out), ijPt0_den)
    np.save('{0}/ijPt0_LVF'.format(ij_out), ijPt0_den / density)

    np.save('{0}/ijPt4_den'.format(ij_out), ijPt4_den)
    np.save('{0}/ijPt4_LVF'.format(ij_out), ijPt4_den / density)

    np.save('{0}/ijPt8_den'.format(ij_out), ijPt8_den)
    np.save('{0}/ijPt8_LVF'.format(ij_out), ijPt8_den / density)