Пример #1
0
def main(felixfiles, location, norm_method, output_filename="averaged"):
    dat_location = location / "EXPORT"
    widget = FELion_Tk(title="Felix Averaged plot", location=location / "OUT")

    fig, canvas = widget.Figure()

    if norm_method == "Relative": ylabel = "Relative Depletion (%)"
    else: ylabel = "Norm. Intensity"

    ax = widget.make_figure_layout(title="Felix Averaged plot",
                                   xaxis="Wavenumber $cm^{-1}$",
                                   yaxis=ylabel,
                                   yscale="linear",
                                   savename="felix_averaged")
    datfiles = [
        dat_location / f"{filename.stem}.dat" for filename in felixfiles
    ]
    avgfile = dat_location / f"{output_filename}.dat"

    wn, inten = read_dat_file(avgfile, norm_method)

    ax.plot(wn, inten, "k.-", label="Averaged", alpha=0.7, zorder=100)

    print(f"felix dat files: {datfiles}\nAveraged file: {avgfile}")
    for felixfile, datfile in zip(felixfiles, datfiles):
        wn, inten = read_dat_file(datfile, norm_method)
        ax.plot(wn, inten, ".", label=f"{felixfile.name}")
    widget.plot_legend = ax.legend()
    widget.mainloop()
Пример #2
0
    def __init__(self, scanfile, tkplot=False):

        self.scanfile = scanfile = pt(scanfile)
        self.location = location = scanfile.parent
        os.chdir(location)

        if tkplot:

            self.widget = FELion_Tk(title=scanfile, location=scanfile.parent)

            self.fig, self.canvas = self.widget.Figure(
                default_save_widget=False)
            self.widget.save_fmt = self.widget.Entries("Entry", "png", 0.1,
                                                       0.05 * 9 + 0.02)
            self.widget.save_btn = self.widget.Buttons("Save", 0.5, 0.05 * 9,
                                                       self.savefig_timescan)
            savename = scanfile.stem
            ax = self.widget.make_figure_layout(
                title=f"Timescan: {scanfile.name}",
                xaxis="Time (ms)",
                yaxis="Counts",
                yscale="linear",
                savename=savename)
            self.widget.lines = {}

        if tkplot:

            time, mean, error = self.read_timescan_file(ax=ax)
            self.widget.lines["SUM"] = ax.errorbar(time,
                                                   mean.sum(axis=0),
                                                   yerr=error.sum(axis=0),
                                                   label="SUM",
                                                   fmt="k.-")
            self.widget.plot_legend = ax.legend()
            self.widget.mainloop()

        else:

            m = {}
            time, mean, error = self.read_timescan_file(tkplot=False, m=m)
            m["SUM"] = {
                "x": list(time),
                "y": list(mean.sum(axis=0)),
                "name": f"SUM",
                "mode": 'lines+markers',
                "line": {
                    "color": "black"
                },
                "error_y": {
                    "type": "data",
                    "array": list(error.sum(axis=0)),
                    "visible": True
                }
            }

            sendData(m)

        self.time, self.mean, self.error = time, mean, error
Пример #3
0
    def InteractivePlots(self):

        widget = FELion_Tk(title=self.felixfile, location=self.location/"OUT")
        self.fig, self.canvas = widget.Figure(dpi=120)
        self.ax = self.fig.add_subplot(111)

        self.line = Line2D(self.xs, self.ys, marker='s', ls='', ms=6, c='b', markeredgecolor='b', animated=True)
        self.ax.add_line(self.line)        
        
        self.inter_xs = np.arange(self.xs[0], self.xs[-1])
        self.funcLine = Line2D([], [], marker='', ls='-', c='b', animated=True)
        self.ax.add_line(self.funcLine)

        self.redraw_f_line()
        self._ind = None

        self.canvas.mpl_connect('draw_event', self.draw_callback)
        self.canvas.mpl_connect('button_press_event', self.button_press_callback)
        self.canvas.mpl_connect('key_press_event', self.key_press_callback)
        self.canvas.mpl_connect('button_release_event', self.button_release_callback)
        self.canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)

        if not self.opo:
            res, b0, trap = var_find(f"{self.location}/DATA/{self.felixfile}")
            label = f"{self.felixfile}: Res:{res}; B0: {b0}ms; trap: {trap}ms"
        else: label = f"{self.felixfile}"

        self.baseline_data = widget.make_figure_layout(ax=self.ax, xdata=self.data[0], ydata=self.data[1], label=label, savename=self.felixfile,
            title=f"Create Baseline", xaxis="Wavenumber (cm-1)", yaxis="Counts", ls='', marker='o', ms=5, markeredgecolor='r', c='r')

        def on_closing():
            def ask(check, change, txt=""):
                if check:
                    yes = askyesno(f"Save corrected as {self.fname}{txt} file?", f"You haven't saved the corrected file\nPress 'Yes' to save the {txt} file and quit OR 'No' to just quit.")
                    if yes: return change()
                    else: return print(f"[{txt}] Changes haven't saved")
                else: return print(f"[{txt}] No changes have made")
            
            ask(self.felix_corrected, self.save_cfelix, ".cfelix")
            ask(self.baseline_corrected, self.SaveBase, ".base")
            widget.destroy()

        widget.protocol("WM_DELETE_WINDOW", on_closing)
        widget.mainloop()
Пример #4
0
    def __init__(self, location, resOnFile=None, resOffFile=None, power=None, nshots=10, massIndex=0, timeStart=1):

        self.location = pt(location)
        self.scanfiles = list(self.location.glob("*.scan"))
        self.resOnFile = resOnFile
        self.resOffFile = resOffFile

        self.power = {"resOn": power[0]/1000, "resOff": power[1]/1000} # mJ to J

        self.nshots = nshots
        self.massIndex = massIndex
        self.timeStart = timeStart

        self.widget = FELion_Tk(title="Depletion Plot", location=self.location)
        self.create_figure()

        self.startPlotting()

        self.widget.mainloop()
Пример #5
0
def massplot(massfiles, tkplot):
    os.chdir(massfiles[0].parent)

    if tkplot:

        if len(massfiles) == 1: savename = massfiles[0].stem
        else: savename = "combined_masspec"
        widget = FELion_Tk(title=f"Mass spectrum: {savename}",
                           location=massfiles[0].parent)
        fig, canvas = widget.Figure()
        ax = widget.make_figure_layout(title="Mass Spectrum",
                                       xaxis="Mass [u]",
                                       yaxis="Counts",
                                       yscale="log",
                                       savename=savename)

    else:
        data = {}
    for massfile in massfiles:

        masses_temp, counts_temp = np.genfromtxt(massfile).T
        res, b0, trap = var_find(massfile)
        label = f"{massfile.stem}: Res:{res}; B0: {b0}ms; trap: {trap}ms"
        if tkplot: ax.plot(masses_temp, counts_temp, label=label)
        else:
            data[massfile.stem] = {
                "x": list(masses_temp),
                "y": list(counts_temp),
                "name": label,
                "mode": "lines",
                "showlegend": True
            }

    if not tkplot:
        print("Done")
        sendData(data)
    else:
        widget.plot_legend = ax.legend()
        widget.mainloop()
        print("Done")
Пример #6
0
def main(filenames, delta, tkplot, gamma=None):
    global widget
    os.chdir(filenames[0].parent)

    if tkplot:
        widget = FELion_Tk(title="THz Scan", location=filenames[0].parent)
        fig, canvas = widget.Figure(default_save_widget=False)
        widget.save_fmt = widget.Entries("Entry", "png", 0.1, 0.05*9+0.02)
        widget.save_btn = widget.Buttons("Save", 0.5, 0.05*9, save_fig)

        if len(filenames) == 1: savename=filenames[0].stem
        else: savename = "averaged_thzScan"
        ax = widget.make_figure_layout(title="THz scan", xaxis="Frequency (GHz)", yaxis="Depletion (%)", savename=savename)

        fit_data = plot_thz(ax=ax, tkplot=True)
        widget.plot_legend = ax.legend(title=f"Intensity: {fit_data.max():.2f} %")
        widget.mainloop()

    else: 
        
        data = plot_thz()
        sendData(data)
Пример #7
0
def opoplot(opofiles, tkplot):

    if tkplot:

        widget = FELion_Tk(title="Mass spectrum", location=opofiles[0].parent)

        fig, canvas = widget.Figure()

        if len(opofiles) == 1: savename = opofiles[0].stem
        else: savename = "combined_masspec"
        ax = widget.make_figure_layout(title="Mass Spectrum",
                                       xaxis="Mass [u]",
                                       yaxis="Counts",
                                       yscale="log",
                                       savename=savename)

    else:
        data = {"real": {}, "relative": {}}

    c = 0
    for i, opofile in enumerate(opofiles):
        basefile = opofile.parent / f"{opofile.stem}.obase"
        wn, counts = np.genfromtxt(opofile).T
        baseCal = BaselineCalibrator(basefile)

        baseCounts = baseCal.val(wn)
        ratio = counts / baseCounts
        relative_depletion = (1 - ratio) * 100
        label = f"{opofile.name}"
        if tkplot: ax.plot(wn, counts, label=label)
        else:

            data["real"][opofile.name] = {
                "x": list(wn),
                "y": list(counts),
                "name": label,
                "mode": "lines",
                "showlegend": True,
                "legendgroup": f'group{i}',
                "line": {
                    "color": f"rgb{colors[c]}"
                },
            }

            data["real"][f"{opofile.name}_line"] = {
                "x": list(wn),
                "y": list(baseCounts),
                "mode": "lines",
                "name": f"{opofile.name}_line",
                "marker": {
                    "color": "black"
                },
                "legendgroup": f'group{i}',
                "showlegend": False,
            }

            data["relative"][opofile.name] = {
                "x": list(wn),
                "y": list(relative_depletion),
                "name": label,
                "mode": "lines",
                "showlegend": True,
                "line": {
                    "color": f"rgb{colors[c]}"
                }
            }

            c += 2
            if c >= len(colors): c = 1

    if not tkplot:

        sendData(data)
    else:
        widget.plot_legend = ax.legend()

        widget.mainloop()
Пример #8
0
def fit_all_peaks(filename, norm_method, prominence=None, width=None, height=None, fitall=False, overwrite=False, tkplot=False, fullfiles=None):

    wn, inten = read_dat_file(filename, norm_method)

    if tkplot:
        widget = FELion_Tk(title=f"Fitted: {filename.name}", location=filename.parent.parent / "OUT")
        fig, canvas = widget.Figure()

        if norm_method == "Relative": ylabel = "Relative Depletion (%)"
        else: ylabel =  "Norm. Intensity"
        ax = widget.make_figure_layout(title=f"Experimental fitted Spectrum: {filename.name}", xaxis="Wavenumber $(cm^{-1})$", yaxis=ylabel, yscale="linear", savename=f"{filename.stem}_expfit")
        ax.plot(wn, inten, ".", label=filename.name)

    indices, _ = peak(inten, prominence=prominence, width=width, height=height)

    _["wn_range"] = np.array([wn[_["left_bases"]], wn[_["right_bases"]]]).T

    for item in _:
        _[item] = _[item].tolist()
    wn_ = list(wn[indices])
    inten_ = list(inten[indices])
    
    data = {"data": {}, "extras": _, "annotations":{}}

    if filename.stem == "averaged": line_color = "black"
    else:
        index = fullfiles.index(filename.stem)
        line_color = f"rgb{colors[2*index]}"

    data["data"] = {
        "x":wn_, "y":inten_, "name":"peaks", "mode":"markers",
        "marker":{
            "color":"blue", "symbol": "star-triangle-up", "size": 12
        }
    }

    data["annotations"] = [
            {
            "x": x,
            "y": y,
            "xref": 'x',
            "yref": 'y',
            "text": f'{x:.2f}',
            "showarrow": True,
            "arrowhead": 2,
            "ax": -25,
            "ay": -40,
            "font":{"color":line_color}, "arrowcolor":line_color
            
        }
        for x, y in zip(wn_, inten_)
    ]
    dataToSend = [{"data": data["data"]}, {"extras":data["extras"]}, {"annotations":data["annotations"]}]

    if not fitall: sendData(dataToSend)
    else:

        location = filename.parent.parent
        output_filename = filename.stem

        fit_data = [{"data": data["data"]}, {"extras":data["extras"]}]

        filename = f"{output_filename}.expfit"
        datfile_location = location/"EXPORT"
        expfile = datfile_location/filename

        if overwrite: method = "w"
        else: method = "a"
        annotations = []
        get_data = []

        with open(expfile, method) as f:
            if overwrite: f.write(f"#Frequency\t#Freq_err\t#Sigma\t#Sigma_err\t#FWHM\t#FWHM_err\t#Amplitude\t#Amplitude_err\n")

            for wavelength in _["wn_range"]:

                get_data_temp, uline_freq, usigma, uamplitude, ufwhm, line_color = exp_fit(location, norm_method, wavelength[0], wavelength[1], output_filename, getvalue=True, fullfiles=fullfiles)
                if uline_freq.nominal_value < 0 or ufwhm.nominal_value > 100: continue
                if tkplot:

                    print("Fitting for wavelength range: ", wavelength[0], wavelength[1])
                    ax.plot(get_data_temp["fit"]["x"], get_data_temp["fit"]["y"], "k-", label=get_data_temp["fit"]["name"])
                    xcord, ycord = uline_freq.nominal_value, uamplitude.nominal_value
                    text_frac = 0.01

                    ax.annotate(f'{uline_freq:.2uP}', xy=(xcord, ycord), xycoords='data',
                                xytext=(xcord+xcord*text_frac, ycord+ycord*text_frac), textcoords='data',
                                arrowprops=dict(arrowstyle="->", connectionstyle="arc3")
                    )
                else:
                    annotate = {
                        "x": uline_freq.nominal_value, "y": uamplitude.nominal_value, "xref": 'x', "yref": 'y', "text": f'{uline_freq:.2uP}', "font":{"color":line_color},
                        "arrowcolor":line_color, "showarrow": True, "arrowhead": 2, "ax": -25, "ay": -40
                    }
                    annotations.append(annotate)
                    get_data.append(get_data_temp)
                    f.write(f"{uline_freq.nominal_value:.4f}\t{uline_freq.std_dev:.4f}\t{usigma.nominal_value:.4f}\t{usigma.std_dev:.4f}\t{ufwhm.nominal_value:.4f}\t{ufwhm.std_dev:.4f}\t{uamplitude.nominal_value:.4f}\t{uamplitude.std_dev:.4f}\n")
                
        if tkplot:
            widget.plot_legend = ax.legend()
            widget.mainloop()
            
        else:

            fit_data.append({"annotations":annotations})
            fit_data.append(get_data)
            
            sendData(fit_data)
Пример #9
0
def exp_theory(theoryfiles,
               location,
               norm_method,
               sigma,
               scale,
               tkplot,
               output_filename="averaged"):

    location = pt(location)

    if tkplot:

        widget = FELion_Tk(title="Exp. Vs Theory",
                           location=theoryfiles[0].parent)
        fig, canvas = widget.Figure()
        if len(theoryfiles) == 1: savename = theoryfiles[0].stem
        else: savename = "Exp vs Theory"

        if norm_method == "Relative": ylabel = "Relative Depletion (%)"
        else: ylabel = "Norm. Intensity"
        ax = widget.make_figure_layout(title="Experimental vs Theory",
                                       xaxis="Wavenumber $(cm^{-1})$",
                                       yaxis=ylabel,
                                       yscale="linear",
                                       savename=savename)

    if location.name is "DATA": datfile_location = location.parent / "EXPORT"
    else: datfile_location = location / "EXPORT"
    avgfile = datfile_location / f"{output_filename}.dat"
    xs, ys = read_dat_file(avgfile, norm_method)

    if tkplot:
        ax.plot(xs, ys, "k-", label="Experiment", alpha=0.9)
    else:
        data = {
            "line_simulation": {},
            "averaged": {
                "x": list(xs),
                "y": list(ys),
                "name": "Exp",
                "mode": "lines",
                "marker": {
                    "color": "black"
                },
            }
        }

    for theoryfile in theoryfiles:

        x, y = np.genfromtxt(theoryfile).T[:2]
        x = x * scale

        norm_factor = ys.max() / y.max()
        y = norm_factor * y

        theory_x, theory_y = [], []
        for wn, inten in zip(x, y):

            size = 1000

            diff = 4 * sigma
            x = np.linspace(wn - diff, wn + diff, size)

            y = gaussian(x, inten, sigma, wn)
            theory_x = np.append(theory_x, x)
            theory_y = np.append(theory_y, y)

        if tkplot: ax.fill(theory_x, theory_y, label=theoryfile.stem)

        else:
            data["line_simulation"][f"{theoryfile.name}"] = {
                "x": list(theory_x),
                "y": list(theory_y),
                "name": f"{theoryfile.stem}",
                "fill": "tozerox"
            }

    if not tkplot: sendData(data)
    else:
        widget.plot_legend = ax.legend()
        widget.mainloop()