Exemple #1
0
def main():

    # Fetch folders for code structure
    folder = folders(folderScripts=os.path.dirname(os.path.realpath(__file__)),
                     folderData="/mnt/f/Desktop/LES_Data")

    # Get Large Eddy Simulation data
    les = getLesData(os.path.join(folder.data, "mov0235_ALL_01-_.nc"))

    # Create plots for each snapshot in time
    for n in range(len(les.t)):
        folderTime = os.path.join(folder.outputs, "timestep_{}".format(n))
        if not os.path.isdir(folderTime):
            os.makedirs(folderTime)

        snapshot = les.data[n]

        # Which layers of the 3D data set do we want to plot?
        imagesIndices = range(0, min(len(snapshot.x), len(snapshot.y)), 10)

        # Plot slices at fixed locations on the y-axis
        for j in imagesIndices:
            layer = snapshot.y[j] * 1e-3
            title = "y = {:.2f}km (id={})".format(layer, j + 1)
            print "XZ layer {} ({})".format(j + 1, title)

            # Plot with only clouds
            plotThermalContour(snapshot.x * 1e-3,
                               snapshot.z * 1e-3,
                               snapshot.ql.field[:, j, :],
                               showMesh=True,
                               id="{}_xz_mesh+cloud".format(j),
                               title=title,
                               xlabel="x (km)",
                               dpi=500,
                               folder=folderTime)

        # Plot slices at fixed locations on the x-axis
        for i in imagesIndices:
            layer = snapshot.x[i] * 1e-3
            title = "x = {:.2f}km (id={})".format(layer, i + 1)
            print "YZ layer {} ({})".format(i + 1, title)

            # Plot with only clouds
            plotThermalContour(snapshot.y * 1e-3,
                               snapshot.z * 1e-3,
                               snapshot.ql.field[:, :, i],
                               showMesh=True,
                               id="{}_yz_mesh+cloud".format(i),
                               title=title,
                               xlabel="y (km)",
                               dpi=500,
                               folder=folderTime)
Exemple #2
0
def lesCloudContours(id="LEM",
                     caseStudy="ARM",
                     indicatorFunction="plume",
                     netcdfFile=None,
                     interval=1,
                     generateGif=False,
                     greyscale=False,
                     plotCloud=False,
                     plotThermals=True,
                     plotVelocity=False,
                     plotAll=False):
    '''
    Plot cross sections of clouds and their underlying structures.
    
    :param id: The simulation source type, set to either "ARM" or "MONC", str.
    :param caseStudy: The name of the case study to be plot, str.
    :param indicatorFunction: The type of structure to overlay onto the cloud, str.
    :param netcdfFile: Specify the netcdf file to open (all files processed if none selected), str.
    :param interval: Gap between layers to be plotted (1 means every layer plotted), int.
    :param generateGif: Compose all generated images into an animation cycling through the layers, bool.
    :param plotCloud: If True generate plot showing only the clouds, bool.
    :param plotThermals: If True generate plot showing cloud and the chosen indicatorFunction, bool.
    :param plotVelocity: If True generate plot showing cloud and the vertical velocity, bool.
    :param plotAll: If True generate plot showing all the features above, bool.
    '''

    # Fetch folders for code structure
    if id == "LEM":
        folder = folders(id=id,
                         folderScripts=os.path.dirname(
                             os.path.realpath(__file__)),
                         folderData="/mnt/f/Desktop/LES_Data")
    elif id == "MONC":
        folder = folders(id=f"{id}_{caseStudy}",
                         folderScripts=os.path.dirname(
                             os.path.realpath(__file__)),
                         folderData=f"/mnt/c/{id}_{caseStudy}")
    else:
        raise ValueError(f"id {id} is not valid. Use LEM or MONC.")

    if netcdfFile:
        files = [os.path.join(folder.data, netcdfFile)]
    else:
        # Find all NetCFD files in
        files = getFilesInFolder(folder.data, extension=".nc")

    for file in files:
        print(f"\nProcessing file: {file}")

        # Get Large Eddy Simulation data
        les = getLesData(file, id=id, indicatorFunction=indicatorFunction)

        # Create plots for each snapshot in time
        for n in range(len(les.t)):
            print("\nProcessing timestep {} (t = {:.2f}hrs,  t = {:.1f}s)".
                  format(n + 1,
                         float(les.t[n]) / 3600., float(les.t[n])))

            folderTime = os.path.join(folder.outputs,
                                      "time_{}".format(int(les.t[n])))
            if not os.path.isdir(folderTime):
                os.makedirs(folderTime)

            snapshot = les.data[n]

            # Which layers of the 3D data set do we want to plot?
            imagesIndices = range(0, min(len(snapshot.x), len(snapshot.y)),
                                  interval)
            '''# Plot slices at fixed locations on the z-axis
            for k in range(0, len(snapshot.z), 10):
                layer = snapshot.z[k]*1e-3
                title = "z = {:.2f}km (id={})".format(layer, k+1)
                print "XY layer {} ({})".format(k+1, title)
                
                plotThermalContour(
                    snapshot.x*1e-3,
                    snapshot.y*1e-3,
                    snapshot.ql.field[k,:,:],
                    id="{}_xy_cloud+updraft".format(k),
                    title=title,
                    xlabel="x (km)",
                    ylabel="y (km)",
                    xlim=[-10.,10.],
                    ylim=[-10.,10.],
                    velocityVectorsOnly = True,
                    folder=folderTime,
                    I2=snapshot.I2.field[k,:,:],
                    u=(snapshot.u.field-0*np.mean(snapshot.u.av))[k,:,:],
                    w=(snapshot.v.field-0*np.mean(snapshot.v.av))[k,:,:]
                )'''

            # Plot slices at fixed locations on the y-axis
            for j in imagesIndices:
                layer = snapshot.y[j] * 1e-3
                title = f"t = {float(les.t[n])/3600:.2f} hours, y = {layer:.2f} km"
                print(f"XZ layer {j+1} ({title})")

                # Plot with only clouds
                if plotCloud:
                    plotThermalContour(snapshot.x * 1e-3,
                                       snapshot.z * 1e-3,
                                       snapshot.ql.field[:, j, :],
                                       id="{}_xz_cloud".format(j),
                                       title=title,
                                       xlabel="x (km)",
                                       folder=folderTime,
                                       greyscale=greyscale)

                # Plot including structure of thermals below clouds
                if plotThermals:
                    plotThermalContour(
                        snapshot.x * 1e-3,
                        snapshot.z * 1e-3,
                        snapshot.ql.field[:, j, :],
                        id="{}_xz_cloud+thermal".format(j),
                        # title=title,
                        xlabel="x (km)",
                        folder=folderTime,
                        I2=snapshot.I2.field[:, j, :],
                        greyscale=greyscale)

                # Plot including regions of positive vertical velocity (updrafts)
                if plotVelocity:
                    plotThermalContour(
                        snapshot.x * 1e-3,
                        snapshot.z * 1e-3,
                        snapshot.ql.field[:, j, :],
                        id="{}_xz_cloud+updraft".format(j),
                        title=title,
                        xlabel="x (km)",
                        folder=folderTime,
                        # u=(snapshot.v.field-snapshot.v.av[:,None,None])[:,j,:],
                        w=snapshot.w.field[:, j, :],
                        greyscale=greyscale)

                # Plot including clouds, structure of thermals and vertical velocity
                if plotAll:
                    plotThermalContour(
                        snapshot.x * 1e-3,
                        snapshot.z * 1e-3,
                        snapshot.ql.field[:, j, :],
                        id="{}_xz_cloud+thermal+updraft".format(j),
                        title=title,
                        xlabel="x (km)",
                        folder=folderTime,
                        I2=snapshot.I2.field[:, j, :],
                        w=snapshot.w.field[:, j, :],
                        greyscale=greyscale)

        # Remove les data to clear memory
        totalTimesteps = len(les.t)
        del les
        del snapshot

        # Create gif animations for generated plots
        if generateGif:
            for n in range(totalTimesteps):
                folderTime = os.path.join(folder.outputs,
                                          "timestep_{}".format(n))
                imageListContourXZ = []

                for k in imagesIndices:
                    print(k)
                    imageListContourXZ = []
                    imageListContourYZ = []

                    imageListContourXZ.append(
                        os.path.join(os.path.join(folderTime, "contourCloud"),
                                     "contour_{}_xz_cloud.png".format(k)))
                    imageListContourXZ.append(
                        os.path.join(
                            os.path.join(folderTime, "contourCloud"),
                            "contour_{}_xz_cloud+thermal.png".format(k)))
                    imageListContourXZ.append(
                        os.path.join(
                            os.path.join(folderTime, "contourCloud"),
                            "contour_{}_xz_cloud+thermal+updraft.png".format(
                                k)))

                    makeGif("contour_{}_xz.gif".format(k),
                            imageListContourXZ,
                            folder=folderTime,
                            delay=200)
Exemple #3
0
def cloudFractionContour(generateGif=False, id="LEM", caseStudy="ARM", indicatorFunction="basic", netcdfFile=None):
    
    
    # Fetch folders for code structure
    if id == "LEM":
        folder = folders(
            id = id,
            folderScripts = os.path.dirname(os.path.realpath(__file__)),
            folderData = "/mnt/f/Desktop/LES_Data"
        )
    elif id == "MONC":
        folder = folders(
            id = f"{id}_{caseStudy}",
            folderScripts = os.path.dirname(os.path.realpath(__file__)),
            folderData = f"/mnt/c/{id}_{caseStudy}"
        )
    else:
        raise ValueError(f"id {id} is not valid.")
    
    if netcdfFile:
        files = [os.path.join(folder.data, netcdfFile)]
    else:
        # Get all available NetCFD files
        files = getFilesInFolder(folder.data, extension=".nc")
    
    times = []
    cloudTops = {}
    cloudBases = {}
    cloudCovers = {}
    cloudCovers1 = {}
    cloudCovers2 = {}
    cloudFractions = {}
    cloudFractions1 = {}
    cloudFractions2 = {}
    cloudFractions1sigma1 = {}
    cloudFractions2sigma2 = {}
    
    for i,file in enumerate(files):
        print(f"\nProcessing 3D file: {file} (file {i+1} of {len(files)})")
        
        # Get Large Eddy Simulation data
        les = getLesData(
            file, 
            id = id,
            indicatorFunction = indicatorFunction
        )
    
        # Create plots for each snapshot in time
        for n in range(len(les.t)):
            print("\nProcessing timestep {} (t = {:.2f}hrs,  t = {:.1f}s)".format(n+1, float(les.t[n])/3600., float(les.t[n])))
            
            time = int(les.t[n])
            folderTime = os.path.join(folder.outputs, f"time_{time}")
            if not os.path.isdir(folderTime):
                os.makedirs(folderTime)
            
            snapshot = les.data[n]
            
            z = snapshot.z
            cloud = snapshot.ql.field > 1e-5
            cloudz = np.max(snapshot.ql.field, axis=snapshot.ql.axisXY) > 1e-5
            cloudFraction = horizontalAverage(cloud, axis=snapshot.ql.axisXY)
            cloudFraction1 = conditionalAverage(cloud, np.invert(snapshot.I2.field), axis=snapshot.ql.axisXY)
            cloudFraction2 = conditionalAverage(cloud, snapshot.I2.field, axis=snapshot.ql.axisXY)
            cloudFraction1sigma1 = cloudFraction1*(1-snapshot.I2.av)
            cloudFraction2sigma2 = cloudFraction2*snapshot.I2.av
            
            times.append(time)
            if not True in cloudz:
                cloudTops[time] = 0.
                cloudBases[time] = 0.
            else:
                cloudTops[time] = np.max(z[cloudz])
                cloudBases[time] = np.min(z[cloudz])
            cloudCovers[time]  = calculateCloudCover(cloud, axis=(snapshot.keys.zi))
            cloudCovers1[time] = calculateCloudCover(cloud * np.invert(snapshot.I2.field), axis=(snapshot.keys.zi))
            cloudCovers2[time] = calculateCloudCover(cloud * snapshot.I2.field, axis=(snapshot.keys.zi))
            cloudFractions[time]  = cloudFraction
            cloudFractions1[time] = cloudFraction1
            cloudFractions2[time] = cloudFraction2
            cloudFractions1sigma1[time] = cloudFraction1sigma1
            cloudFractions2sigma2[time] = cloudFraction2sigma2
            
            print("Cloud cover: {:.3f}".format(cloudCovers[time]))
            print("Cloud base: {:.1f}m".format(cloudBases[time]))
            print("Cloud top: {:.1f}m".format(cloudTops[time]))
            
            '''
            plotCloudFraction(
                snapshot.z,
                cloudFraction,
                id = "all",
                folder = folderTime
            )
            
            plotCloudFraction(
                snapshot.z,
                cloudFraction1,
                id = "1",
                folder = folderTime
            )
            
            plotCloudFraction(
                snapshot.z,
                cloudFraction2,
                id = "2",
                folder = folderTime
            )
            '''
            
            
        del les
        del snapshot
    
    cloudTop = np.zeros_like(times, dtype=float)
    cloudBase = np.zeros_like(times, dtype=float)
    cloudCover = np.zeros_like(times, dtype=float)
    cloudCover1 = np.zeros_like(times, dtype=float)
    cloudCover2 = np.zeros_like(times, dtype=float)
    cloudFraction  = np.zeros((len(cloudFractions[times[0]]),  len(times)))
    cloudFraction1 = np.zeros((len(cloudFractions1[times[0]]), len(times)))
    cloudFraction2 = np.zeros((len(cloudFractions2[times[0]]), len(times)))
    cloudFraction1sigma1 = np.zeros((len(cloudFractions1sigma1[times[0]]), len(times)))
    cloudFraction2sigma2 = np.zeros((len(cloudFractions2sigma2[times[0]]), len(times)))
    
    times = sorted(times)
    for n in range(len(times)):
        time = times[n]
        cloudTop[n]  = cloudTops[time]
        cloudBase[n]  = cloudBases[time]
        cloudCover[n]  = cloudCovers[time]
        cloudCover1[n] = cloudCovers1[time]
        cloudCover2[n] = cloudCovers2[time]
        cloudFraction[:,n] = cloudFractions[time]
        cloudFraction1[:,n] = cloudFractions1[time]
        cloudFraction2[:,n] = cloudFractions2[time]
        cloudFraction1sigma1[:,n] = cloudFractions1sigma1[time]
        cloudFraction2sigma2[:,n] = cloudFractions2sigma2[time]
    
    data = {}
    data["t_cloud_fraction"] = np.array(times)
    data["z_cloud_fraction"] = z
    data["cloud_top"]  = cloudTop
    data["cloud_base"]  = cloudBase
    data["cloud_cover"]  = cloudCover
    data["cloud_cover1"] = cloudCover1
    data["cloud_cover2"] = cloudCover2
    data["cloud_fraction"]  = cloudFraction
    data["cloud_fraction1"] = cloudFraction1
    data["cloud_fraction2"] = cloudFraction2
    data["cloud_fraction1_sigma1"] = cloudFraction1sigma1
    data["cloud_fraction2_sigma2"] = cloudFraction2sigma2
    
    folder = os.path.join(folder.outputs, "cloudContour")
    if not os.path.isdir(folder):
        os.makedirs(folder)
    
    savemat(os.path.join(folder, "cloud_fraction.mat"), data)
Exemple #4
0
def lesVerticalProfiles(id="LEM",
                        caseStudy="ARM",
                        indicatorFunction="basic",
                        netcdfFile=None,
                        thetaMean=None):
    '''
    Plot the vertical profiles of various fields in the Large Eddy Simulation (LES) data
    for comparison with Single Column Models (SCMs).
    
    :param id: The simulation source type, set to either "ARM" or "MONC", str.
    :param caseStudy: The name of the case study to be plot, str.
    :param indicatorFunction: The type of structure to overlay onto the cloud, str.
    :param netcdfFile: Specify the netcdf file to open (all files processed if none selected), str.
    :param thetaMean: Specify a background profile to add to the potential temperature, float np.ndarray.
    '''

    # Fetch folders for code structure
    if id == "LEM":
        folder = folders(id=id,
                         folderScripts=os.path.dirname(
                             os.path.realpath(__file__)),
                         folderData="/mnt/f/Desktop/LES_Data")
    elif id == "MONC":
        folder = folders(id=f"{id}_{caseStudy}",
                         folderScripts=os.path.dirname(
                             os.path.realpath(__file__)),
                         folderData=f"/mnt/c/{id}_{caseStudy}")

        thetaMean = get1dProfiles(folder.data1d, key="theta_mean")
    else:
        raise ValueError(f"id {id} is not valid.")

    if netcdfFile:
        files = [os.path.join(folder.data, netcdfFile)]
    else:
        # Get all available NetCFD files
        files = getFilesInFolder(folder.data, extension=".nc")

    for i, file in enumerate(files):
        print(f"\nProcessing 3D file: {file} (file {i+1} of {len(files)})")

        # Get Large Eddy Simulation data
        les = getLesData(file,
                         id=id,
                         indicatorFunction=indicatorFunction,
                         thetaMeanProfiles=thetaMean)

        # Create plots for each snapshot in time
        for n in range(len(les.t)):
            print("\nProcessing timestep {} (t = {:.2f}hrs,  t = {:.1f}s)".
                  format(n + 1,
                         float(les.t[n]) / 3600., float(les.t[n])))

            folderTime = os.path.join(folder.outputs,
                                      "time_{}".format(int(les.t[n])))
            if not os.path.isdir(folderTime):
                os.makedirs(folderTime)

            snapshot = les.data[n]

            # Volume fraction of fluid 2
            plotVolumeFraction(snapshot.z,
                               snapshot.I2,
                               folder=folderTime,
                               id=indicatorFunction)

            # Mean profiles
            plotVerticalProfile(snapshot.z,
                                snapshot.u,
                                title="Horizontal velocity",
                                xlabel="u (m/s)",
                                folder=folderTime,
                                id=indicatorFunction,
                                plotZero=True)

            plotVerticalProfile(snapshot.z,
                                snapshot.v,
                                title="Horizontal velocity",
                                xlabel="v (m/s)",
                                folder=folderTime,
                                id=indicatorFunction,
                                plotZero=True)

            plotVerticalProfile(snapshot.z,
                                snapshot.w,
                                title="Vertical velocity",
                                xlabel="w (m/s)",
                                folder=folderTime,
                                id=indicatorFunction,
                                plotZero=True)

            plotVerticalProfile(snapshot.z,
                                snapshot.th,
                                title="Potential temperature",
                                xlabel="$\\theta$ (K)",
                                folder=folderTime,
                                id=indicatorFunction)

            plotVerticalProfile(snapshot.z,
                                snapshot.thv,
                                title="Virtual potential temperature",
                                xlabel="$\\theta_v$ (K)",
                                folder=folderTime,
                                id=indicatorFunction)

            plotVerticalProfile(snapshot.z,
                                snapshot.b,
                                title="Buoyancy",
                                xlabel="b (m s$^2$)",
                                folder=folderTime,
                                id=indicatorFunction)

            plotVerticalProfile(snapshot.z,
                                snapshot.q,
                                title="Water vapour",
                                xlabel="$q_t$ (kg/kg)",
                                folder=folderTime,
                                id=indicatorFunction)

            plotVerticalProfile(snapshot.z,
                                snapshot.qv,
                                title="Water vapour",
                                xlabel="$q_v$ (kg/kg)",
                                folder=folderTime,
                                id=indicatorFunction)

            plotVerticalProfile(snapshot.z,
                                snapshot.ql,
                                title="Liquid water",
                                xlabel="$q_l$ (kg/kg)",
                                folder=folderTime,
                                id=indicatorFunction)

            plotVerticalProfile(snapshot.z,
                                snapshot.qr,
                                title="Radioactive tracer",
                                xlabel="$q_r$ (kg/kg)",
                                folder=folderTime,
                                id=indicatorFunction)

            # Variances
            plotVerticalVariances(snapshot.z,
                                  snapshot.u,
                                  title="Horizontal velocity variance",
                                  xlabel="$\\overline{u'u'}$ (m$^2$/s$^2$)",
                                  folder=folderTime,
                                  id=indicatorFunction)
            plotVerticalVariances(snapshot.z,
                                  snapshot.v,
                                  title="Horizontal velocity variance",
                                  xlabel="$\\overline{v'v'}$ (m$^2$/s$^2$)",
                                  folder=folderTime,
                                  id=indicatorFunction)
            plotVerticalVariances(snapshot.z,
                                  snapshot.w,
                                  title="Horizontal velocity variance",
                                  xlabel="$\\overline{w'w'}$ (m$^2$/s$^2$)",
                                  folder=folderTime,
                                  id=indicatorFunction)
            plotVerticalVariances(
                snapshot.z,
                snapshot.th,
                title="Potential temperature variance",
                xlabel="$\\overline{\\theta'\\theta'}$ (K$^2$)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalVariances(
                snapshot.z,
                snapshot.thv,
                title="Virtual potential temperature variance",
                xlabel="$\\overline{\\theta_v'\\theta_v'}$ (K$^2$)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalVariances(snapshot.z,
                                  snapshot.b,
                                  title="Buoyancy variance",
                                  xlabel="$\\overline{b'b'}$ (m$^2$/s$^4$)",
                                  folder=folderTime,
                                  id=indicatorFunction)
            plotVerticalVariances(snapshot.z,
                                  snapshot.q,
                                  title="Total moisture variance",
                                  xlabel="$\\overline{q'q'}$",
                                  folder=folderTime,
                                  id=indicatorFunction)
            plotVerticalVariances(snapshot.z,
                                  snapshot.qv,
                                  title="Water vapour variance",
                                  xlabel="$\\overline{q_v'q_v'}$",
                                  folder=folderTime,
                                  id=indicatorFunction)
            plotVerticalVariances(snapshot.z,
                                  snapshot.ql,
                                  title="Liquid water variance",
                                  xlabel="$\\overline{q_l'q_l'}$",
                                  folder=folderTime,
                                  id=indicatorFunction)

            # Vertical fluxes
            plotVerticalFluxes(
                snapshot.z,
                snapshot.u,
                title="Horizontal velocity fluxes",
                xlabel="$\\sigma_i \\overline{w'u'}$ (m$^2$/s$^2$)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalFluxes(
                snapshot.z,
                snapshot.v,
                title="Horizontal velocity fluxes",
                xlabel="$\\sigma_i \\overline{w'v'}$ (m$^2$/s$^2$)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalFluxes(
                snapshot.z,
                snapshot.th,
                title="Potential temperature fluxes",
                xlabel="$\\sigma_i \\overline{w'\\theta'}$ (K m/s)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalFluxes(
                snapshot.z,
                snapshot.thv,
                title="Virtual potential temperature fluxes",
                xlabel="$\\sigma_i \\overline{w'\\theta_v'}$ (K m/s)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalFluxes(
                snapshot.z,
                snapshot.b,
                title="Buoyancy fluxes",
                xlabel="$\\sigma_i \\overline{w'b'}$ (m$^2$/s$^3$)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalFluxes(
                snapshot.z,
                snapshot.q,
                title="Total moisture fluxes",
                xlabel="$\\sigma_i \\overline{w'q'}$ (kg/kg m/s)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalFluxes(
                snapshot.z,
                snapshot.qv,
                title="Water vapour fluxes",
                xlabel="$\\sigma_i \\overline{w'q_v'}$ (kg/kg m/s)",
                folder=folderTime,
                id=indicatorFunction)
            plotVerticalFluxes(
                snapshot.z,
                snapshot.ql,
                title="Liquid water fluxes",
                xlabel="$\\sigma_i \\overline{w'q_l'}$ (kg/kg m/s)",
                folder=folderTime,
                id=indicatorFunction)
Exemple #5
0
def main():

    # Fetch folders for code structure
    folder = folders(folderScripts=os.path.dirname(os.path.realpath(__file__)),
                     folderData="/mnt/f/Desktop/LES_Data")

    # Get Large Eddy Simulation data
    les = getLesData(os.path.join(folder.data, "mov0235_ALL_01-_.nc"))
    # les = getLesData(os.path.join(folder.data, "mov0235_ALL_01-_.nc"), indicatorFunction="basic")

    # Create plots for each snapshot in time
    for n in range(len(les.t)):
        folderTime = os.path.join(folder.outputs, "timestep_{}".format(n))
        if not os.path.isdir(folderTime):
            os.makedirs(folderTime)

        snapshot = les.data[n]

        # Create plots for each layer in the vertical
        for k in range(len(snapshot.z)):
            layer = snapshot.z[k] * 1e-3
            title = "z = {:.2f}km (id={})".format(layer, k + 1)
            print "Layer {} ({:.3f}km)".format(k + 1, layer)

            # Histogram for vertical velocity, w
            plotLayerHistogram(snapshot.w,
                               snapshot.I2,
                               layer,
                               k,
                               title=title,
                               folder=os.path.join(folderTime,
                                                   snapshot.w.name))

            # Histogram for potential temperature, theta
            plotLayerHistogram(snapshot.theta,
                               snapshot.I2,
                               layer,
                               k,
                               title=title,
                               folder=os.path.join(folderTime,
                                                   snapshot.theta.name))

            # Histogram for water vapour, qv
            plotLayerHistogram(snapshot.qv,
                               snapshot.I2,
                               layer,
                               k,
                               title=title,
                               folder=os.path.join(folderTime,
                                                   snapshot.qv.name))

            # Histogram for liquid water, ql
            plotLayerHistogram(snapshot.ql,
                               snapshot.I2,
                               layer,
                               k,
                               title=title,
                               folder=os.path.join(folderTime,
                                                   snapshot.ql.name))

    # Remove les data to clear memory
    totalTimesteps = len(les.t)
    totalImages = min(len(snapshot.z), 150)
    del les
    del snapshot

    # Create gif animations for generated plots
    for n in range(totalTimesteps):
        folderTime = os.path.join(folder.outputs, "timestep_{}".format(n))
        imageListW = []
        imageListTheta = []
        imageListQv = []
        imageListQl = []

        for k in range(totalImages):
            imageListW.append(
                os.path.join(os.path.join(folderTime, "w"),
                             "histogram_w_{}.png".format(k + 1)))
            imageListTheta.append(
                os.path.join(os.path.join(folderTime, "theta"),
                             "histogram_theta_{}.png".format(k + 1)))
            imageListQv.append(
                os.path.join(os.path.join(folderTime, "qv"),
                             "histogram_qv_{}.png".format(k + 1)))
            imageListQl.append(
                os.path.join(os.path.join(folderTime, "ql"),
                             "histogram_ql_{}.png".format(k + 1)))

        makeGif("histogram_w.gif", imageListW, folder=folderTime, delay=8)
        makeGif("histogram_theta.gif",
                imageListTheta,
                folder=folderTime,
                delay=8)
        makeGif("histogram_qv.gif", imageListQv, folder=folderTime, delay=8)
        makeGif("histogram_ql.gif", imageListQl, folder=folderTime, delay=8)
def main():

    # Fetch folders for code structure
    folder = folders(folderScripts=os.path.dirname(os.path.realpath(__file__)),
                     folderData="/mnt/f/Desktop/LES_Data")

    # Get Large Eddy Simulation data and Single Column Model data
    les = getLesData(os.path.join(folder.data, "mov0235_ALL_01-_.nc"))
    scm = getScmData(os.path.join(folder.data, "SCM_results.mat"))

    # Create plots for each snapshot in time
    for n in range(len(les.t)):
        folderTime = os.path.join(folder.outputs, "timestep_{}".format(n))
        if not os.path.isdir(folderTime):
            os.makedirs(folderTime)

        snapshot = les.data[n]

        # Create plots for each layer in the vertical
        for k in range(len(snapshot.z)):
            layer = snapshot.z[k] * 1e-3
            title = "z = {:.2f}km (id={})".format(layer, k + 1)
            print "Layer {} ({:.3f}km)".format(k + 1, layer)

            scmGaussian = {}
            scmGaussian["sigma1"] = interpolateFromArray(
                scm["SCM_zw"][0], snapshot.z[k], scm["SCM_sigma1w"][:, 2])
            scmGaussian["sigma2"] = interpolateFromArray(
                scm["SCM_zw"][0], snapshot.z[k], scm["SCM_sigma2w"][:, 2])
            scmGaussian["w1"] = interpolateFromArray(scm["SCM_zw"][0],
                                                     snapshot.z[k],
                                                     scm["SCM_w_1"][:, 2])
            scmGaussian["w2"] = interpolateFromArray(scm["SCM_zw"][0],
                                                     snapshot.z[k],
                                                     scm["SCM_w_2"][:, 2])
            scmGaussian["wVar1"] = interpolateFromArray(
                scm["SCM_zw"][0], snapshot.z[k], scm["SCM_ww1"][:, 2])
            scmGaussian["wVar2"] = interpolateFromArray(
                scm["SCM_zw"][0], snapshot.z[k], scm["SCM_ww2"][:, 2])

            # Histogram for vertical velocity, w
            plotHistogramWithGaussian(snapshot.w,
                                      snapshot.I2,
                                      layer,
                                      k,
                                      title=title,
                                      folder=os.path.join(
                                          folderTime, snapshot.w.name),
                                      scmGaussian=scmGaussian)

            # Histogram for water vapour, qv
            # plotHistogramWithGaussian(
            # snapshot.qv,
            # snapshot.I2,
            # layer,
            # k,
            # title=title,
            # folder=os.path.join(folderTime, snapshot.qv.name)
            # )

            # Histogram for liquid water, ql
            # plotHistogramWithGaussian(
            # snapshot.ql,
            # snapshot.I2,
            # layer,
            # k,
            # title=title,
            # folder=os.path.join(folderTime, snapshot.ql.name)
            # )

    # Remove les data to clear memory
    totalTimesteps = len(les.t)
    totalImages = min(len(snapshot.z), 150)
    del les
    del snapshot