コード例 #1
0
def mainTest(SpectrogramObject:Spectrogram, startTime:int, stopTime:int, signalJump:int=50, bottomIndex:int=0, topIndex:int=None, vStartInd: int=None):
    widths = [1,3,5,11,21]
    orders = [1,2,10]
    seam = []

    velocities = SpectrogramObject.velocity
    time = SpectrogramObject.time
    for width in widths:
        for order in orders:
            signal, p_table, dp_table, botVel, topVel = seamExtraction(SpectrogramObject, startTime, stopTime, width, signalJump, bottomIndex, topIndex, order)

            plt.plot(velocities[botVel:topVel+1], dp_table[0])
            plt.title("Total Minkowski" + str(order) +" Order Cost diagram with a window size of " +str(width) +" raw")
            plt.xlabel("Starting velocity of the trace (m/s)")
            plt.ylabel("Minimum value of the sum (|p_i - p_{i-1}|^" + str(order) + ") along the path")
            plt.show()

            print("Here is a graph of the signal trace across time")       

            plt.figure(figsize=(10, 6))
            myplot = SpectrogramObject.plot()
            plt.xlim((SpectrogramObject.time[startTime], SpectrogramObject.time[stopTime]))

            myplot.plot(time[startTime: stopTime+1], velocities[signal], 'b-', alpha = 0.4, label="Minimum Cost")
            if vStartInd != None:
                # Compute the signal seam for assuming this is the start point.
                seam = reconstruction(p_table, vStartInd-botVel, botVel)
                myplot.plot(time[startTime: stopTime+1], velocities[seam], 'r--', alpha = 0.4, label="Expected Start Point")
            myplot.title("Velocity as a function of time for the minimum cost seam with Minkowski" + str(order)+ " and a window size of " + str(width) + " raw")
            myplot.legend()
            myplot.show()
コード例 #2
0
def createGallery(digsToLookAt: list = None,
                  colormap="blue-orange-div",
                  fileext="jpeg",
                  transformData=False):
    if type(digsToLookAt) == type(None):
        digsToLookAt = DigFile.inventory(justSegments=True)['file']

    digDir = DigFile.dig_dir()
    imageDir, _ = os.path.split(digDir)
    imageFold = "ImageGallery"
    imageDir = os.path.join(imageDir, imageFold)
    print(digsToLookAt)
    for i in range(len(digsToLookAt)):
        filename = digsToLookAt[i]
        print(filename)
        spec = Spectrogram(os.path.join(digDir, filename))
        pcms, lastAxes = spec.plot(transformData, cmap=colormap)
        fileloc, filename = os.path.split(
            os.path.splitext(os.path.join(imageDir, filename))[0])
        fileloc = os.path.join(fileloc, filename)

        for key in pcms.keys():
            if "complex" in key:
                continue  # There is not a graph with a name that contains complex.
            if not os.path.exists(fileloc):
                os.makedirs(fileloc)

            plt.figure(num=key)  # Get to the appropriate figure.
            plt.savefig(
                os.path.join(fileloc, filename) +
                f' {key} spectrogram.{fileext}')
            plt.clf()
        del spec
コード例 #3
0
def generate_graphs(directory):
    for file in os.listdir(directory):
        print(directory + file)
        if file.endswith(".dig"):
            # Then we have the right file.

            Spectrogram_Object = Spectrogram(directory + file)
            sampleSize = 256
            full_length_spectra = Spectrogram_Object.spectrogram(
                0, Spectrogram_Object.samples, sampleSize)

            colormaps = ["gist_stern", "tab20c", "tab20b", "terrain"]

            for colormap in colormaps:
                Spectrogram_Object.plot(full_length_spectra,
                                        sample_window=sampleSize,
                                        cmap=colormap)
コード例 #4
0
def mainTest(SpectrogramObject:Spectrogram, startTime:int, stopTime:int, bottomIndex:int=0, topIndex:int=None, vStartInd: int=None,verbose:bool = False):
    widths = [1,3,5,11,21]
    orders = [1,2,10]
    precision = 10
    thetas = np.arange(precision+1)/precision # Get in the range of zero to one inclusive.
    seam = []

    velocities = SpectrogramObject.velocity
    time = SpectrogramObject.time

    signalData = time*1e6

    headers = ["Time ($\mu$s)"]

    basefilePath = "../DocumentationImages/DP/ComplexSpectra/"
    digfileUsed = SpectrogramObject.data.filename
    for width in widths:
        for order in orders:
            for theta in thetas:
                hyperParamNames =  "w " + str(width) + " ord " + str(order) + " Minkowski dist theta " + str(theta).replace(".", "_")
                signal, p_table, dp_table, botVel, topVel = seamExtraction(SpectrogramObject, startTime, stopTime, width, bottomIndex, topIndex, order, theta=theta)

                fname = "DP_Cost_Table time by vel " +hyperParamNames + ".csv"
                filename = basefilePath + fname
                np.savetxt(filename,dp_table,delimiter=",")

                fname = "Parent_Table time by vel " + hyperParamNames + ".csv"
                filename = basefilePath + fname
                np.savetxt(filename,p_table,delimiter=",")

                fig = plt.figure(num=1)
                plt.plot(velocities[botVel:topVel+1], dp_table[0])
                plt.title("Total Minkowski" + str(order) +" Order Cost diagram with a window size of " +str(width) +" PercPhase:" + str(theta))
                plt.xlabel("Starting velocity of the trace (m/s)")
                plt.ylabel("Minimum value of the sum ($\theta$|$\phi_i$ - $\phi_{i-1}$|^" + str(order) + "(1-$\theta$)|$Amp_i$ - $Amp_{i-1}$|^" + str(order) +") along the path")
                # manager = plt.get_current_fig_manager()
                # manager.window.Maximized()
                if verbose:
                    fig.show()
                    print("Here is a graph of the signal trace across time")       
                # fig.show()
                    
                extension = "svg"
                fname = "DP_Start_Cost " + hyperParamNames + extension
                filename = basefilePath + fname
                fig.savefig(filename, bbox_inches = "tight")

                fig2 = plt.figure(num = 2, figsize=(10, 6))
                ax = fig2.add_subplot(1,1,1)
                fig2Axes = fig2.axes[0]

                print(type(fig2Axes))
                print(fig2Axes)
                SpectrogramObject.plot(axes=fig2Axes)
                plt.xlim((SpectrogramObject.time[startTime], SpectrogramObject.time[stopTime]))

                fig2Axes.plot(time[startTime: stopTime+1], velocities[signal], 'b-', alpha = 0.4, label="Minimum Cost")
                if vStartInd != None:
                       # Compute the signal seam for assuming this is the start point.
                    seam = reconstruction(p_table, vStartInd-botVel, botVel)
                    fig2Axes.plot(time[startTime: stopTime+1], velocities[seam], 'r--', alpha = 0.4, label="Expected Start Point")
                fig2Axes.set_title("Velocity as a function of time for the minimum cost seam with Minkowski" + str(order)+ " and a window size of " + str(width) + " raw")
                fig2Axes.legend()

                # manager = plt.get_current_fig_manager()
                # manager.window.showMaximized()
                if verbose:
                    fig2.show()
                fname = "Overlay Spectra " + hyperParamNames + extension
                filename = basefilePath + fname
                plt.savefig(filename, bbox_inches = "tight")

                # Build the reconstruction of every possible starting velocity. Then, save them in a csv file.
                extension = "csv"
                fname = "Velocity Traces " + hyperParamNames + extension
                filename = basefilePath + fname

                for velInd in range(0, topVel-botVel+1):
                    trace = reconstruction(p_table, velInd, botVel)
                    header = "Starting Velocity " + str(velocities[velInd+botVel]) + "(m/s)"
                    headers.append(header) 
                    meaured = velocities[trace]
                    signalData = np.hstack((signalData, meaured))
                signalData = signalData.reshape((topVel-botVel + 2, len(time))).transpose() # I want each column to be a velocity trace.
                # np.savetxt(filename, signalData, delimiter=",")
                df = pd.DataFrame(data=signalData, index=time*1e6, columns=headers)
                df.to_csv(filename)

                print("Completed the documentation for ", hyperParamNames)
コード例 #5
0
            add_row(next(loc), 0.9, 0.8, 0.5)  # to faded yellow
            add_row(next(loc), 0.5, 0, 0.5)
            add_row(next(loc), 0, 0.5, 0)
            add_row(next(loc), 1, 0.75, 0.2)
            add_row(next(loc), 0.2, 0.2, 0.2)
            add_row(next(loc), 0, 0, 0)
        except:
            pass

        add_row(1, 0, 0, 0)
        return cdict

    roids = calculate_centroids()
    bounds = normalize_bounds(roids)
    cdict = build_cdict(bounds)

    from matplotlib.colors import LinearSegmentedColormap
    COLORMAPS[name] = LinearSegmentedColormap(name, cdict)
    return dict(name=name, centroids=roids, cmap=COLORMAPS[name])


if __name__ == '__main__':
    sg = Spectrogram('../dig/CH_4_009.dig')
    roids = make_spectrogram_color_map(sg, 4, "Kitty")

    sg.plot(cmap = roids["cmap"])
    import matplotlib.pyplot as plt
    plt.xlim((0, 50))
    plt.ylim((1500, 5000))
    plt.show()
コード例 #6
0
    width = 50
    for peak_center in peaks:
        low, high = max(0, peak_center -
                        width), min(len(powers) - 1, peak_center + width)
        neighborhoods.append([velocities[low:high], powers[low:high]])
    return neighborhoods


if __name__ == '__main__':
    import os
    os.chdir('../dig')
    sgram = Spectrogram('./CH_4_009/seg00.dig', 0.0, 50.0e-6)


    peaks, uncertainties, peak_heights = baselines_by_squash(sgram)
    velos = []
    times = [x for x in range(0,30)]


    pcms, axes = sgram.plot(min_time=0, min_vel=100, max_vel=10000, cmap='3w_gby')


    # add the peaks to the plot and change the color map range
    pcm = pcms['intensity raw']
    pcm.set_clim(-40, -65)
    for peak in peaks:
        velo_index = sgram._velocity_to_index(peak)
        axes.plot(times, [peak for x in range(0,30)], color='red', linewidth=3, markersize=15)

    plt.show()
コード例 #7
0
                os.makedirs(fileloc)

            plt.figure(num=key)  # Get to the appropriate figure.
            plt.savefig(
                os.path.join(fileloc, filename) +
                f' {key} spectrogram.{fileext}')
            plt.clf()
        del spec


if __name__ == "__main__":
    # process command line args
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--file_name', type=str, default=False)
    args = parser.parse_args()

    #Just set directory here, I can't be bothered
    directory = '/home/lanl/Documents/dig/new/CH_1_009/'

    plt.rcParams["figure.figsize"] = [
        20, 10
    ]  # This is setting the default parameters to "20 by 10" inches by inches.
    # I would prefer if this was set to full screen.

    if args.file_name:
        spec = Spectrogram(directory + args.file_name)
        spec.plot()
        plt.savefig(args.file_name + '.png')
        plt.clf()
        del spec