Example #1
0
    def __init__(self, master):
        global fileName
        global daqInterval

        self.master = master
        master.title('MEC Power Supply Monitoring')
        master.geometry('1000x850+200+200')

        # ------------------------------------------------------------------------
        # Displaying the filename
        # ------------------------------------------------------------------------
        # Graphical definition of label
        self.filenameVariable = Tkinter.StringVar()  #variable to call label
        self.filenameLabel = Tkinter.Label(master,
                                           textvariable=self.filenameVariable,
                                           anchor="w",
                                           fg="black")
        self.filenameVariable.set(
            u"Datalogging file:")  # default value in display
        self.filenameLabel.pack()
        self.filenameLabel.place(x=10, y=0, width=100, height=25)

        self.filenamedisplayVariable = Tkinter.StringVar(
        )  # variable to call label
        global vsetfileName
        vsetfileName = self.filenamedisplayVariable
        self.filenamedisplayLabel = Tkinter.Label(
            master,
            textvariable=self.filenamedisplayVariable,
            anchor="center",
            fg="black",
            bg="ivory")
        self.filenamedisplayVariable.set(fileName)  #default value in display
        self.filenamedisplayLabel.pack()
        self.filenamedisplayLabel.place(x=110, y=0, width=100, height=25)

        # ------------------------------------------------------------------------
        # BUTTONS Definitions
        # ------------------------------------------------------------------------

        # Graphic definition of SETTINGS button
        self.settingsButton = Tkinter.Button(
            master,
            text="SETTINGS",
            command=self.Settings,
            anchor="center",
            fg="black")  # Button uses the settings function
        self.settingsButton.pack()
        self.settingsButton.place(x=85, y=100, width=80, height=25)

        # Graphic definition of START button
        self.startButton = Tkinter.Button(
            master,
            text="START",
            command=self.Start,
            anchor="center",
            fg="black")  # Button uses the Start function
        self.startButton.pack()
        self.startButton.place(x=85, y=125, width=80, height=25)

        # Graphical definition of STOP button
        self.stopButton = Tkinter.Button(
            master, text="STOP",
            command=self.Stop)  # Button uses the Stop function
        self.stopButton.pack()
        self.stopButton.place(x=85, y=150, width=80, height=25)

        # ------------------------------------------------------------------------
        # Displaying PS1 status (ON/OFF) on master
        # ------------------------------------------------------------------------
        # Graphical definition of PS1 ON/OFF label
        self.onoffPS1Variable = Tkinter.StringVar()  # variable to call label
        if runPS1 == 'False':
            self.onoffPS1Variable.set(u"PS1: OFF")
        else:
            self.onoffPS1Variable.set(u"PS1: ON")

        self.onoffPS1Label = Tkinter.Label(master,
                                           textvariable=self.onoffPS1Variable,
                                           anchor="center",
                                           fg="black")
        self.onoffPS1Label.pack()
        self.onoffPS1Label.place(x=10, y=75, width=80, height=25)

        # ------------------------------------------------------------------------
        # Displaying PS1 voltage
        # ------------------------------------------------------------------------
        # Graphical definition of label
        self.ps1voltageVariable = Tkinter.StringVar()  #variable to call label
        self.ps1voltageLabel = Tkinter.Label(
            master,
            textvariable=self.ps1voltageVariable,
            anchor="w",
            fg="black")
        self.ps1voltageVariable.set(
            u"PS1 Voltage:")  # default value in display
        self.ps1voltageLabel.pack()
        self.ps1voltageLabel.place(x=10, y=25, width=80, height=25)

        self.ps1VdisplayVariable = Tkinter.StringVar(
        )  # variable to call label
        global vsetPS1
        vsetPS1 = self.ps1VdisplayVariable
        self.ps1VdisplayLabel = Tkinter.Label(
            master,
            textvariable=self.ps1VdisplayVariable,
            anchor="e",
            fg="black",
            bg="ivory")
        self.ps1VdisplayVariable.set(
            str(ps1Voltage))  #default value in display
        self.ps1VdisplayLabel.pack()
        self.ps1VdisplayLabel.place(x=90, y=25, width=30, height=25)

        # ------------------------------------------------------------------------
        # Displaying PS1 current
        # ------------------------------------------------------------------------
        # Graphical definition of label
        self.ps1currentVariable = Tkinter.StringVar()  #variable to call label
        self.ps1currentLabel = Tkinter.Label(
            master,
            textvariable=self.ps1currentVariable,
            anchor="w",
            fg="black")
        self.ps1currentVariable.set(
            u"PS1 Current:")  # default value in display
        self.ps1currentLabel.pack()
        self.ps1currentLabel.place(x=10, y=50, width=80, height=25)

        self.ps1IdisplayVariable = Tkinter.StringVar(
        )  # variable to call label
        global isetPS1
        time.sleep(1)
        isetPS1 = self.ps1IdisplayVariable
        self.ps1IdisplayLabel = Tkinter.Label(
            master,
            textvariable=self.ps1IdisplayVariable,
            anchor="e",
            fg="black",
            bg="ivory")
        self.ps1IdisplayVariable.set(
            str(ps1currentActual))  #default value in display
        self.ps1IdisplayLabel.pack()
        self.ps1IdisplayLabel.place(x=90, y=50, width=30, height=25)

        # ------------------------------------------------------------------------
        # Displaying PS2 status (ON/OFF) on master
        # ------------------------------------------------------------------------
        # Graphical definition of PS2 ON/OFF label
        self.onoffPS2Variable = Tkinter.StringVar()  # variable to call label
        self.onoffPS2Label = Tkinter.Label(master,
                                           textvariable=self.onoffPS2Variable,
                                           anchor="center",
                                           fg="black")
        if runPS2 == 'False':
            self.onoffPS2Variable.set(u"PS2: OFF")
        else:
            self.onoffPS2Variable.set(u"PS2: ON")
        self.onoffPS2Label.pack()
        self.onoffPS2Label.place(x=135, y=75, width=80, height=25)

        # ------------------------------------------------------------------------
        # Displaying PS2 voltage
        # ------------------------------------------------------------------------
        # Graphical definition of label
        self.ps2voltageVariable = Tkinter.StringVar()  #variable to call label
        self.ps2voltageLabel = Tkinter.Label(
            master,
            textvariable=self.ps2voltageVariable,
            anchor="w",
            fg="black")
        self.ps2voltageVariable.set(
            u"PS2 Voltage:")  # default value in display
        self.ps2voltageLabel.pack()
        self.ps2voltageLabel.place(x=135, y=25, width=80, height=25)

        self.ps2displayVariable = Tkinter.StringVar()  # variable to call label
        global vsetPS2
        vsetPS2 = self.ps2displayVariable
        self.ps2displayLabel = Tkinter.Label(
            master,
            textvariable=self.ps2displayVariable,
            anchor="e",
            fg="black",
            bg="ivory")
        self.ps2displayVariable.set(str(ps2Voltage))  #default value in display
        self.ps2displayLabel.pack()
        self.ps2displayLabel.place(x=215, y=25, width=30, height=25)

        # ------------------------------------------------------------------------
        # Displaying PS2 current
        # ------------------------------------------------------------------------
        # Graphical definition of label
        self.ps2currentVariable = Tkinter.StringVar()  #variable to call label
        self.ps2currentLabel = Tkinter.Label(
            master,
            textvariable=self.ps2currentVariable,
            anchor="w",
            fg="black")
        self.ps2currentVariable.set(
            u"PS2 Current:")  # default value in display
        self.ps2currentLabel.pack()
        self.ps2currentLabel.place(x=135, y=50, width=80, height=25)

        self.ps2IdisplayVariable = Tkinter.StringVar(
        )  # variable to call label
        global isetPS2
        time.sleep(1)
        isetPS2 = self.ps2IdisplayVariable
        self.ps2IdisplayLabel = Tkinter.Label(
            master,
            textvariable=self.ps2IdisplayVariable,
            anchor="e",
            fg="black",
            bg="ivory")
        self.ps2IdisplayVariable.set(
            str(ps2currentActual))  #default value in display
        self.ps2IdisplayLabel.pack()
        self.ps2IdisplayLabel.place(x=215, y=50, width=30, height=25)

        # ------------------------------------------------------------------------
        # Displaying last data acquisition
        # ------------------------------------------------------------------------
        # Graphical definition of label
        self.lastdAcqVariable = Tkinter.StringVar()  #variable to call label
        self.lastdAcqLabel = Tkinter.Label(master,
                                           textvariable=self.lastdAcqVariable,
                                           anchor="w",
                                           fg="black")
        self.lastdAcqVariable.set(u"Last datalog:")  # default value in display
        self.lastdAcqLabel.pack()
        self.lastdAcqLabel.place(x=0, y=185, width=80, height=25)

        self.lastdAcqdisplayVariable = Tkinter.StringVar(
        )  # variable to call label
        global lastdAcq
        time.sleep(1)
        lastdAcq = self.lastdAcqdisplayVariable
        self.lastdAcqdisplayLabel = Tkinter.Label(
            master,
            textvariable=self.lastdAcqdisplayVariable,
            anchor="w",
            fg="black",
            bg="ivory")
        self.lastdAcqdisplayVariable.set(str(' '))  #default value in display
        self.lastdAcqdisplayLabel.pack()
        self.lastdAcqdisplayLabel.place(x=80, y=185, width=160, height=25)

        # ------------------------------------------------------------------------
        # Displaying Timer
        # ------------------------------------------------------------------------
        # Graphical definition of label
        self.timerVariable = Tkinter.StringVar()  #variable to call label
        self.timerLabel = Tkinter.Label(master,
                                        textvariable=self.timerVariable,
                                        anchor="w",
                                        fg="black")
        self.timerVariable.set(
            u"Time before next datalog:")  # default value in display
        self.timerLabel.pack()
        self.timerLabel.place(x=0, y=210, width=150, height=25)

        self.timerdisplayVariable = Tkinter.StringVar(
        )  # variable to call label
        global timer
        time.sleep(1)
        timer = self.timerdisplayVariable
        self.timerdisplayLabel = Tkinter.Label(
            master,
            textvariable=self.timerdisplayVariable,
            anchor="e",
            fg="black",
            bg="ivory")
        self.timerdisplayVariable.set(str(' '))  #default value in display
        self.timerdisplayLabel.pack()
        self.timerdisplayLabel.place(x=190, y=210, width=50, height=25)

        # ------------------------------------------------------------------------
        # Displaying Graphic trends for PSx currents
        # ------------------------------------------------------------------------
        self.graph1display = Tkinter.StringVar()  #variable to call label
        self.graph2display = Tkinter.StringVar()  #variable to call label
        global graph1display
        global graph2display
        graph1display = self.graph1display
        graph2display = self.graph2display
        graph1displaylabel = Tkinter.Label(
            master,
            textvariable=self.graph1display,
            anchor="center",
            fg="white",
            bg="black"
        )  #putting a label behind the labels. Labels display text
        graph2displaylabel = Tkinter.Label(
            master,
            textvariable=self.graph2display,
            anchor="center",
            fg="white",
            bg="black"
        )  #putting a label behind the labels. Labels display text
        self.graph1display.set(u"PS1 Current")  #default value in display
        self.graph2display.set(u"PS1 Current")  #default value in display
        graph1displaylabel.pack()
        graph2displaylabel.pack()
        # graph1displaylabel.grid(column=0,row=7,columnspan=3,sticky='NESW') #label position
        graph1displaylabel.place(x=0, y=300)
        graph2displaylabel.place(x=400, y=300)

        global f1
        global f2
        global var1
        global var2
        f1 = Figure(figsize=(4, 4), dpi=100)
        f2 = Figure(figsize=(4, 4), dpi=100)
        var1 = f1.add_subplot(111)
        var2 = f2.add_subplot(111)
        var1.set_title('PS1 Current')
        var2.set_title('PS2 Current')
        var1.set_xlabel('t [h]')
        var2.set_xlabel('t [h]')
        var1.set_ylabel('I [mA]')
        var2.set_ylabel('I [mA]')
        var1.set_xlim((0, 24))
        var2.set_xlim((0, 24))
        var1.set_ylim((0, 500))
        var2.set_ylim((0, 500))
        var1.plot([], [])
        var2.plot([], [])
        canvas1 = FigureCanvasTkAgg(f1, master)
        canvas2 = FigureCanvasTkAgg(f2, master)
        canvas1.show()
        canvas2.show()
        # canvas.get_tk_widget().grid(column=0,row=7,columnspan=3,sticky='NESW') #graph position
        canvas1.get_tk_widget().place(x=0, y=250)  #graph position
        canvas2.get_tk_widget().place(x=400, y=250)  #graph position
        toolbar1frame = Frame(master)  #New frame to bypass the pack limitation
        toolbar2frame = Frame(master)  #New frame to bypass the pack limitation
        # toolbar1frame.grid(column=0,row=12,columnspan=4,sticky='NESW')
        toolbar1frame.place(x=0, y=700)
        toolbar2frame.place(x=400, y=700)
        toolbar1 = NavigationToolbar2TkAgg(canvas1, toolbar1frame)
        toolbar2 = NavigationToolbar2TkAgg(canvas2, toolbar2frame)
        toolbar1.update()
        toolbar2.update()

        master.grid_columnconfigure(
            0, weight=1)  #configure column 0 to resize with a weight of 1
        master.resizable(
            True, False
        )  #a constraints allowing resizeable along horizontally(column)
        #(true) and not vertically(rows)--false)
        master.update()
        master.geometry(
            master.geometry())  #prevents the window from resizing all the time
Example #2
0
fig, ax = plt.subplots()
ax.grid(True)
ax.set_title("ADRC")
ax.set_xlabel("Time")
ax.set_ylabel("Temperature/PWM")
ax.axis([0, 1000, 0, MaxYaxisValue])

line1 = ax.plot(xAchse, yAchse, "-r", label="Temperature")
#line2=ax.plot(xAchse,yAchse, "-b", label="Watt")
line3 = ax.plot(xAchse, yAchse, "-y", label="PWM")
legend(loc='upper left')

canvas = FigureCanvasTkAgg(fig, master=windows)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

toolbar = NavigationToolbar2TkAgg(canvas, windows)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

CPUTemperature = []

TemperatureData = []
WattDatas = []
PWMDatas = []

response = {}

Start = True

UpdateFlag = False
mutex = threading.Lock()
Example #3
0
    def createPlot(self, specMat, param_str, paramValues):

        s = len(self.U)
        spectra = []

        plot = Figure(figsize=(5, 4),
                      dpi=100,
                      facecolor='whitesmoke',
                      edgecolor=None)

        spectrumplot = plot.add_subplot(211)
        spectrumplot.set_title('$\mathrm{Spectrum}$')
        for A in specMat:
            spectrum = []
            for i in range(len(self.MU)):
                for j in range(len(A[0][i])):
                    spectrum.append(A[0][i][j])
            spectra.append(spectrum)

        spectrumplot.set_xlabel('$\mathrm{Re }\lambda$')
        spectrumplot.set_ylabel('$\mathrm{Im }\lambda$')

        efcnplot = plot.add_subplot(212)
        efcnplot.set_xlabel('$x$')
        efcnplot.set_ylabel('$y(x)$')

        lastind = 0

        xs = real(spectra[0])
        ys = imag(spectra[0])

        def efcnchange(ax):
            print 'called'
            #Get the range for the new area
            xstart, ystart, xdelta, ydelta = ax.viewLim.bounds
            xend = xstart + xdelta
            yend = ystart + ydelta

            x = arange(xstart, xend, .01)
            self.plotEigenfunction(efcnplot, plot, specMat[0], x)

        # Connect for changing the view limits
        # retain a reference to avoid garbage collection
        efcnplot.autoscale(enable=True, axis='both', tight=True)
        cid = efcnplot.callbacks.connect('xlim_changed', efcnchange)
        #efcnplot.callbacks.connect('ylim_changed', efcnchange)

        plotWindow = FigureCanvasTkAgg(plot, master=self)
        self.plotSpectrum(specMat, 0, spectrumplot, efcnplot, plotWindow)

        plotWindow.show()

        toolbar = NavigationToolbar2TkAgg(plotWindow, self)
        toolbar.pack(side=TOP, padx=10, pady=10)

        plotWindow.get_tk_widget().pack(side=LEFT,
                                        fill=BOTH,
                                        expand=True,
                                        padx=10,
                                        pady=10)

        return [spectrumplot, plot, efcnplot, plotWindow]
Example #4
0
    def __init__(self, parent):

        self.parent = parent

        self.FFTwin = Tk.Toplevel(self.parent.tks)
        self.FFTwin.title("UV space")

        menubar = Tk.Menu(self.FFTwin)
        menubar.add_command(label="Quit", command=self.quit)
        self.FFTwin.config(menu=menubar)

        self.figUV1 = pl.figure(figsize=(10, 4))

        self.UVPSF = self.figUV1.add_subplot(131, aspect='equal')

        self.UVOBS = self.figUV1.add_subplot(132,
                                             sharex=self.UVPSF,
                                             sharey=self.UVPSF,
                                             aspect='equal')
        pl.setp(self.UVOBS.get_yticklabels(), visible=False)

        self.UVSOURCE = self.figUV1.add_subplot(133,
                                                sharex=self.UVPSF,
                                                sharey=self.UVPSF,
                                                aspect='equal')
        pl.setp(self.UVSOURCE.get_yticklabels(), visible=False)

        self.figUV1.subplots_adjust(left=0.1,
                                    right=0.98,
                                    top=0.90,
                                    bottom=0.15,
                                    wspace=0.02,
                                    hspace=0.15)

        self.UVfmt = '%.2e Jy'
        self.PSFfmt = '%.2e'

        self.PSFText = self.UVPSF.text(0.05,
                                       0.87,
                                       self.PSFfmt % (0.0),
                                       transform=self.UVPSF.transAxes,
                                       bbox=dict(facecolor='white', alpha=0.7))

        self.UVSOURCEText = self.UVSOURCE.text(
            0.05,
            0.87,
            self.UVfmt % (0.0),
            transform=self.UVSOURCE.transAxes,
            bbox=dict(facecolor='white', alpha=0.7))

        self.UVOBSText = self.UVOBS.text(0.05,
                                         0.87,
                                         self.UVfmt % (0.0),
                                         transform=self.UVOBS.transAxes,
                                         bbox=dict(facecolor='white',
                                                   alpha=0.7))

        self.frames = {}
        self.frames['FigUV'] = Tk.Frame(self.FFTwin)
        self.frames['BFr'] = Tk.Frame(self.FFTwin)

        self.canvasUV1 = FigureCanvasTkAgg(self.figUV1,
                                           master=self.frames['FigUV'])

        self.canvasUV1.show()
        self.frames['FigUV'].pack(side=Tk.TOP)
        self.frames['BFr'].pack(side=Tk.TOP)

        self.buttons = {}
        self.buttons['reload'] = Tk.Button(self.frames['BFr'],
                                           text="Reload",
                                           command=self._FFTRead)
        self.buttons['reload'].pack()

        self.canvasUV1.mpl_connect('pick_event', self._onUVPick)
        self.canvasUV1.get_tk_widget().pack(side=Tk.LEFT)
        toolbar_frame = Tk.Frame(self.FFTwin)
        __toolbar = NavigationToolbar2TkAgg(self.canvasUV1, toolbar_frame)
        toolbar_frame.pack(side=Tk.LEFT)

        self._FFTRead()
Example #5
0
def run_app():

    # #########
    # create and initialise the window
    # #########

    root = Tk()
    root2 = Tk()

    initialise_window(root, 'Transit simulator', [], [root, root2], False)
    initialise_window(root2, 'Transit simulator', [root2], [], False)

    # get variables from log and set as tk variables those to be modified

    catalogue = plc.oec_catalogue()

    planet_search = StringVar(value='HD 209458 b')
    planet = StringVar(value='HD 209458 b')
    metallicity = DoubleVar(value=0.0)
    temperature = DoubleVar(value=0.0)
    logg = DoubleVar(value=0.0)
    phot_filter = IntVar(value=7)
    period = DoubleVar(value=0.0)
    rp_over_rs = DoubleVar(value=0.0)
    sma_over_rs = DoubleVar(value=0.0)
    inclination = DoubleVar(value=0.0)
    eccentricity = DoubleVar(value=0.0)
    periastron = DoubleVar(value=0.0)
    ascending_node = DoubleVar(value=0.0)

    # set progress variables, useful for updating the window

    update_planet = BooleanVar(root, value=True)
    update_planet_list = BooleanVar(root, value=True)
    open_root2 = BooleanVar(root, value=False)

    # create the plot in the additional window

    figure = matplotlib.figure.Figure()
    figure.patch.set_facecolor('white')
    ax1 = figure.add_subplot(122)
    ax2 = figure.add_subplot(221)
    ax3 = figure.add_subplot(223)
    canvas = FigureCanvasTkAgg(figure, root2)
    canvas.get_tk_widget().pack()
    NavigationToolbar2TkAgg(canvas, root2)

    # create widgets

    metallicity_label = Label(root, text='Stellar metallicity (dex)')
    metallicity_entry = Scale(root,
                              from_=-5,
                              to=1,
                              resolution=0.5,
                              variable=metallicity,
                              orient=HORIZONTAL)
    metallicity_entry.set(metallicity.get())

    temperature_label = Label(root, text='Stellar temperature (K)')
    temperature_entry = Scale(root,
                              from_=3500,
                              to=7000,
                              resolution=250,
                              variable=temperature,
                              orient=HORIZONTAL)

    logg_label = Label(root, text='Stellar surface gravity (cm/s^2, log)')
    logg_entry = Scale(root,
                       from_=0.0,
                       to=5.0,
                       resolution=0.5,
                       variable=logg,
                       orient=HORIZONTAL)

    available_filters = ['U', 'B', 'V', 'R', 'I', 'J', 'H', 'K']
    phot_filter_label = Label(root, text='Filter')
    phot_filter_label_2 = Label(root,
                                text=available_filters[phot_filter.get()])
    phot_filter_entry = Scale(root,
                              from_=0,
                              to=len(available_filters) - 1,
                              resolution=1,
                              variable=phot_filter,
                              showvalue=False,
                              orient=HORIZONTAL)

    period_label = Label(root, text='Period (days)')
    period_entry = Entry(root, textvariable=period, validate='key')
    period_entry['validatecommand'] = (
        period_entry.register(test_float_positive_input), '%P', '%d')

    rp_over_rs_label = Label(root, text='Rp/Rs')
    rp_over_rs_entry = Scale(root,
                             from_=0,
                             to=0.15,
                             resolution=0.005,
                             variable=rp_over_rs,
                             orient=HORIZONTAL)

    sma_over_rs_label = Label(root, text='a/Rs')
    sma_over_rs_entry = Scale(root,
                              from_=1,
                              to=20,
                              resolution=0.1,
                              variable=sma_over_rs,
                              orient=HORIZONTAL)

    inclination_label = Label(root, text='Inclination (deg)')
    inclination_entry = Scale(root,
                              from_=70,
                              to=90,
                              resolution=0.1,
                              variable=inclination,
                              orient=HORIZONTAL)

    eccentricity_label = Label(root, text='Eccentricity')
    eccentricity_entry = Scale(root,
                               from_=0,
                               to=1,
                               resolution=0.01,
                               variable=eccentricity,
                               orient=HORIZONTAL)

    periastron_label = Label(root, text='Periastron (deg)')
    periastron_entry = Scale(root,
                             from_=0,
                             to=360,
                             resolution=1,
                             variable=periastron,
                             orient=HORIZONTAL)

    ascending_node_label = Label(root, text='Ascending node (deg)')
    ascending_node_entry = Scale(root,
                                 from_=0,
                                 to=360,
                                 resolution=1,
                                 variable=ascending_node,
                                 orient=HORIZONTAL)

    planet_label = Label(root, text='     Planet     ')
    planet_search_entry = Entry(root, textvariable=planet_search)
    combostyle = ttk.Style()
    combostyle.theme_create('combostyle',
                            parent='alt',
                            settings={
                                'TCombobox': {
                                    'configure': {
                                        'selectbackground': 'white',
                                        'fieldbackground': 'white',
                                        'background': 'white'
                                    }
                                }
                            })
    combostyle.theme_use('combostyle')
    planet_entry = ttk.Combobox(root, textvariable=planet, state='readonly')

    search_planet_button = Button(root, text='SEARCH')

    plot_button = Button(root, text='PLOT')

    exit_transit_simulator_button = Button(root, text='EXIT')

    # define the function that updates the window

    def update_window(*event):

        if not event:
            pass

        if update_planet_list.get():

            if isinstance(catalogue.searchPlanet(planet_search.get()), list):
                test_sample = []
                for test_planet in catalogue.searchPlanet(planet_search.get()):
                    if test_planet.isTransiting:
                        test_sample.append(test_planet)
                planet_entry['values'] = tuple(
                    [ppp.name for ppp in test_sample])
            elif catalogue.searchPlanet(planet_search.get()):
                planet_entry['values'] = tuple(
                    [catalogue.searchPlanet(planet_search.get()).name])
            else:
                planet_entry['values'] = tuple([])

            if len(planet_entry['values']) == 1:
                planet.set(planet_entry['values'][0])
                update_planet.set(True)
            else:
                planet.set('Choose Planet')

            update_planet_list.set(False)

        if update_planet.get():

            parameters = plc.find_oec_parameters(planet.get(),
                                                 catalogue=catalogue)
            logg.set(parameters[1])
            temperature.set(parameters[2])
            metallicity.set(parameters[3])
            rp_over_rs.set(parameters[4])
            period.set(parameters[6])
            sma_over_rs.set(parameters[7])
            eccentricity.set(parameters[8])
            inclination.set(parameters[9])
            periastron.set(parameters[10])
            ascending_node.set(0.0)

            update_planet.set(False)

        phot_filter_label_2.configure(
            text=available_filters[phot_filter.get()])

        planet_entry.selection_clear()

        plot_transit = True

        for input_entry in [
                phot_filter_entry, metallicity_entry, temperature_entry,
                logg_entry, period_entry, rp_over_rs_entry, sma_over_rs_entry,
                inclination_entry, eccentricity_entry, periastron_entry
        ]:

            if len(str(input_entry.get())) == 0:
                plot_transit = False

        if plot_transit:

            if period.get() == 0 or rp_over_rs.get() == 0 or sma_over_rs.get(
            ) == 0:
                plot_transit = False

        if plot_transit:

            try:
                limb_darkening_coefficients = plc.clablimb(
                    'claret', logg.get(), temperature.get(), metallicity.get(),
                    available_filters[phot_filter.get()])

                time_array = np.arange(100 - period.get() / 4,
                                       100 + period.get() / 4,
                                       30. / 24. / 60. / 60.)

                position = plc.exoplanet_orbit(period.get(), sma_over_rs.get(),
                                               eccentricity.get(),
                                               inclination.get(),
                                               periastron.get(), 100,
                                               time_array)

                time_array = time_array[np.where((np.abs(position[1]) < 1.5)
                                                 & (position[0] > 0))]

                position = plc.exoplanet_orbit(period.get(),
                                               sma_over_rs.get(),
                                               eccentricity.get(),
                                               inclination.get(),
                                               periastron.get(),
                                               100,
                                               time_array,
                                               ww=ascending_node.get())

                transit_light_curve = plc.transit('claret',
                                                  limb_darkening_coefficients,
                                                  rp_over_rs.get(),
                                                  period.get(),
                                                  sma_over_rs.get(),
                                                  eccentricity.get(),
                                                  inclination.get(),
                                                  periastron.get(), 100,
                                                  time_array)

                a1, a2, a3, a4 = limb_darkening_coefficients
                star_r = np.arange(0, 1, 0.01)
                star_m = np.sqrt(1 - star_r * star_r)
                star_i = (1.0 - a1 * (1.0 - star_m**0.5) - a2 *
                          (1.0 - star_m) - a3 * (1.0 - star_m**1.5) - a4 *
                          (1.0 - star_m**2))

                cmap = matplotlib.cm.get_cmap('rainbow')
                color = cmap(1 - (temperature.get() - 3500) / (9000 - 3500))

                ax2.cla()
                ax2.set_aspect('equal')
                ax2.tick_params(axis='both',
                                which='both',
                                bottom='off',
                                left='off',
                                top='off',
                                right='off',
                                labelbottom='off',
                                labelleft='off')
                star_circle = matplotlib.patches.Circle((0, 0),
                                                        1,
                                                        color=color,
                                                        fc=color)
                planet_circle = matplotlib.patches.Circle(
                    (position[1][len(position[1]) // 2],
                     position[2][len(position[2]) // 2]),
                    rp_over_rs.get(),
                    color='k',
                    fc='k')
                ax2.add_patch(star_circle)
                ax2.add_patch(planet_circle)
                ax2.plot(position[1], position[2], c='k')
                ax2.set_xlim(-1.5, 1.5)
                ax2.set_ylim(-1.5, 1.5)

                ax3.cla()
                ax3.set_aspect(3.0)
                ax3.set_yticks([0, 0.5, 1.0])
                ax3.set_xticks([-1.0, 0, 1.0])
                ax3.plot(star_r, star_i, c=color)
                ax3.plot(-star_r, star_i, c=color)
                ax3.set_xlim(-1.5, 1.5)
                ax3.set_ylim(0.1, 1.1)
                ax3.set_ylabel('I / I0')
                ax3.set_xlabel('r / Rs')

                ax1.cla()
                ax1.plot((time_array - 100) * 24.0 * 60.0,
                         1000 * transit_light_curve,
                         c='k')
                ylim_1 = int(min(transit_light_curve) * 200)
                ax1.set_ylim(1000 * ylim_1 / 200.0, 1001)
                ax1.tick_params(left='off',
                                right='on',
                                labelleft='off',
                                labelright='on')
                ax1.set_ylabel('F / F0 (ppt)')
                ax1.set_xlabel('t - T0 (min)')

            except IndexError:

                ax1.cla()
                ax2.cla()
                ax3.cla()

        canvas.draw()

    update_window()

    # define actions for the different buttons, including calls to the function that updates the window

    def choose_planet(entry):

        if not entry:
            return 0

        update_planet.set(True)
        update_window()

    def search_planet():

        update_planet_list.set(True)
        update_window()

    def plot():

        open_root2.set(True)
        update_window()

        root2.deiconify()

    def exit_transit_simulator():
        root.destroy()
        root2.destroy()

    # connect actions to widgets

    planet_entry.bind('<<ComboboxSelected>>', choose_planet)
    phot_filter_entry.bind("<ButtonRelease-1>", update_window)
    metallicity_entry.bind("<ButtonRelease-1>", update_window)
    temperature_entry.bind("<ButtonRelease-1>", update_window)
    logg_entry.bind("<ButtonRelease-1>", update_window)
    period_entry.bind(sequence='<KeyRelease>', func=update_window)
    rp_over_rs_entry.bind("<ButtonRelease-1>", update_window)
    sma_over_rs_entry.bind("<ButtonRelease-1>", update_window)
    inclination_entry.bind("<ButtonRelease-1>", update_window)
    eccentricity_entry.bind("<ButtonRelease-1>", update_window)
    periastron_entry.bind("<ButtonRelease-1>", update_window)
    ascending_node_entry.bind("<ButtonRelease-1>", update_window)

    search_planet_button['command'] = search_planet
    plot_button['command'] = plot
    exit_transit_simulator_button['command'] = exit_transit_simulator

    # setup window

    setup_window(root, [
        [],
        [[phot_filter_label_2, 3]],
        [[phot_filter_label, 2], [phot_filter_entry, 3]],
        [[metallicity_label, 2], [metallicity_entry, 3]],
        [[temperature_label, 2], [temperature_entry, 3]],
        [[logg_label, 2], [logg_entry, 3]],
        [[planet_label, 1]],
        [[planet_search_entry, 1], [period_label, 2], [period_entry, 3]],
        [[search_planet_button, 1]],
        [[planet_entry, 1], [rp_over_rs_label, 2], [rp_over_rs_entry, 3]],
        [[sma_over_rs_label, 2], [sma_over_rs_entry, 3]],
        [[inclination_label, 2], [inclination_entry, 3]],
        [[plot_button, 1], [eccentricity_label, 2], [eccentricity_entry, 3]],
        [[exit_transit_simulator_button, 1], [periastron_label, 2],
         [periastron_entry, 3]],
        [[ascending_node_label, 2], [ascending_node_entry, 3]],
        [],
    ])

    # finalise and show  window

    finalise_window(root, 1)
    finalise_window(root2, 3)
    root.mainloop()
Example #6
0
def serine(self):
    cn_min = [0, 0, 40]
    cn_max = [-45, 40, 10]

    bnh_min = [-45, 40, 10]
    bnh_max = [-50, 40, -50]

    cc1_min = [0, 0, 40]
    cc1_max = [45, -40, 10]

    bco_min = [45, -40, 10]
    bco_max = [60, -40, -50]

    ch1_min = [0, 0, 40]
    ch1_max = [-10, 10, 70]

    cc2_min = [0, 0, 40]
    cc2_max = [10, -10, 70]

    ch2_min = [10, -10, 70]
    ch2_max = [5, -5, 90]

    ch3_min = [10, -10, 70]
    ch3_max = [20, -20, 90]

    co2_min = [10, -10, 70]
    co2_max = [40, -40, 70]
    oh_min = [40, -40, 70]
    oh_max = [60, -50, 50]

    fig = Figure(figsize=(10, 6), dpi=100, facecolor='black')
    canvas = FigureCanvasTkAgg(fig, self)
    canvas.draw()
    ax = fig.add_subplot(111, projection="3d")
    ax.set_axis_bgcolor("black")

    cn = ax.plot([cn_max[0], cn_min[0]], [cn_max[1], cn_min[1]],
                 [cn_max[2], cn_min[2]],
                 linewidth=5,
                 color=cn_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    bnh = ax.plot([bnh_max[0], bnh_min[0]], [bnh_max[1], bnh_min[1]],
                  [bnh_max[2], bnh_min[2]],
                  linewidth=5,
                  color=nh_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    ccl = ax.plot([cc1_max[0], cc1_min[0]], [cc1_max[1], cc1_min[1]],
                  [cc1_max[2], cc1_min[2]],
                  linewidth=5,
                  color=cc_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    bco = ax.plot([bco_max[0], bco_min[0]], [bco_max[1], bco_min[1]],
                  [bco_max[2], bco_min[2]],
                  linewidth=5,
                  color=co_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    ch1 = ax.plot([ch1_max[0], ch1_min[0]], [ch1_max[1], ch1_min[1]],
                  [ch1_max[2], ch1_min[2]],
                  linewidth=5,
                  color=ch_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    cc2 = ax.plot([cc2_max[0], cc2_min[0]], [cc2_max[1], cc2_min[1]],
                  [cc2_max[2], cc2_min[2]],
                  linewidth=5,
                  color=cc_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    ch2 = ax.plot([ch2_max[0], ch2_min[0]], [ch2_max[1], ch2_min[1]],
                  [ch2_max[2], ch2_min[2]],
                  linewidth=5,
                  color=ch_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    ch3 = ax.plot([ch3_max[0], ch3_min[0]], [ch3_max[1], ch3_min[1]],
                  [ch3_max[2], ch3_min[2]],
                  linewidth=5,
                  color=ch_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    co2 = ax.plot([co2_max[0], co2_min[0]], [co2_max[1], co2_min[1]],
                  [co2_max[2], co2_min[2]],
                  linewidth=5,
                  color=co_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    oh = ax.plot([oh_max[0], oh_min[0]], [oh_max[1], oh_min[1]],
                 [oh_max[2], oh_min[2]],
                 linewidth=5,
                 color=oh_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    tch = plt.Rectangle((0, 0), 1, 1, fc=ch_color)
    toh = plt.Rectangle((0, 0), 1, 1, fc=oh_color)
    tcn = plt.Rectangle((0, 0), 1, 1, fc=cn_color)
    tcc = plt.Rectangle((0, 0), 1, 1, fc=cc_color)
    tbco = plt.Rectangle((0, 0), 1, 1, fc=co_color)
    tbnh = plt.Rectangle((0, 0), 1, 1, fc=nh_color)

    ax.legend([tch, tcn, tcc, tbco, tbnh, toh],
              ['ch', 'cn', 'cc', 'co', 'nh', 'oh'])

    ax.axis("off")
    toolbarFrame = Frame(self)
    toolbarFrame.grid(row=6, column=7)
    toolbar = NavigationToolbar2TkAgg(canvas, toolbarFrame)
    canvas.get_tk_widget().grid(row=4, column=7)
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.configure(background='white')
        w, h = self.winfo_screenwidth(), self.winfo_screenheight()
        xunit = w / 1000
        yunit = h / 1000

        label = tk.Label(self,
                         text="PID Controller\nand\nMonitering\n\nGROUP 5",
                         font=LARGE_FONT,
                         background='white')
        label.place(x=xunit * 20, y=yunit * 20)

        self.KpLabel = tk.Label(self, text="Kp:", background='white')
        self.KpLabel.place(x=xunit * 10, y=yunit * 325)
        self.KiLabel = tk.Label(self, text="Ki:", background='white')
        self.KiLabel.place(x=xunit * 10, y=yunit * 375)
        self.KdLabel = tk.Label(self, text="Kd:", background='white')
        self.KdLabel.place(x=xunit * 10, y=yunit * 425)
        self.Setpoint = tk.Label(self, text="Sp:", background='white')
        self.Setpoint.place(x=xunit * 10, y=yunit * 475)

        CurrentKp = tk.Label(self, text="Current Kp:", background='white')
        CurrentKp.place(x=xunit * 10, y=yunit * 625)
        self.CurrentKp = tk.Label(self,
                                  text=str(PID_datahouse.Kp),
                                  background='white')
        self.CurrentKp.place(x=xunit * 85, y=yunit * 625)

        CurrentKi = tk.Label(self, text="Current Ki:", background='white')
        CurrentKi.place(x=xunit * 10, y=yunit * 675)
        self.CurrentKi = tk.Label(self,
                                  text=str(PID_datahouse.Ki),
                                  background='white')
        self.CurrentKi.place(x=xunit * 85, y=yunit * 675)

        CurrentKd = tk.Label(self, text="Current Kd:", background='white')
        CurrentKd.place(x=xunit * 10, y=yunit * 725)
        self.CurrentKd = tk.Label(self,
                                  text=str(PID_datahouse.Kd),
                                  background='white')
        self.CurrentKd.place(x=xunit * 85, y=yunit * 725)

        CurrentSetpoint = tk.Label(self,
                                   text="Current Setpoint: ",
                                   background='white')
        CurrentSetpoint.place(x=xunit * 10, y=yunit * 775)
        self.CurrentSetpoint = tk.Label(self,
                                        text=str(PID_datahouse.Sp),
                                        background='white')
        self.CurrentSetpoint.place(x=xunit * 85, y=yunit * 775)

        self.KpEntry = ttk.Entry(self)
        self.KpEntry.place(x=xunit * 30, y=yunit * 325)
        self.KiEntry = ttk.Entry(self)
        self.KiEntry.place(x=xunit * 30, y=yunit * 375)
        self.KdEntry = ttk.Entry(self)
        self.KdEntry.place(x=xunit * 30, y=yunit * 425)
        self.SpEntry = ttk.Entry(self)
        self.SpEntry.place(x=xunit * 30, y=yunit * 475)

        button1 = ttk.Button(self,
                             text='Connect',
                             command=lambda: self.connectingFunc())
        button1.place(x=xunit * 30, y=yunit * 200)

        button2 = ttk.Button(self,
                             text='Disconnect',
                             command=lambda: self.disconnectingFunc())
        button2.place(x=xunit * 30, y=yunit * 250)

        button3 = ttk.Button(self,
                             text='Update',
                             command=lambda: self.updateFromEntry())
        button3.place(x=xunit * 30, y=yunit * 525)

        button3 = ttk.Button(self,
                             text='Quit',
                             command=lambda: self.quitFunc(controller))
        button3.place(x=xunit * 30, y=yunit * 875)

        self.ErrorValue = tk.Label(self,
                                   text="No Error",
                                   background='Green',
                                   width=15,
                                   anchor='w')
        self.ErrorValue.place(x=xunit * 100, y=yunit * 526)

        self.ErrorConnect = tk.Label(self,
                                     text="Not Connected",
                                     background='red',
                                     width=15,
                                     anchor='w')
        self.ErrorConnect.place(x=xunit * 100, y=yunit * 200)

        canvas = FigureCanvasTkAgg(PID_datahouse.graph, self)
        canvas.show()

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.place(x=xunit * 250, y=00)
Example #8
0
def Main(argv):

    line_number = 0

    usage = "Usage: %prog FILENAME [options]"
    parser = OptionParser(usage=usage)
    parser.add_option("-s",
                      "--start",
                      action="store",
                      type="int",
                      dest="start",
                      default=0,
                      help="Start time of analysis in ms")
    parser.add_option("-e",
                      "--end",
                      action="store",
                      type="int",
                      dest="end",
                      default=1000000000,
                      help="End time of analysis in ms")
    parser.add_option("-c", "--core", action="store", type="int", dest="num_of_cores", default=0,
        help="Number of cores, default is 0, i.e. tool automatically tries to " \
      "identify num of cores, can fail if 1 core stays in Idle")
    parser.add_option("",
                      "--norun",
                      action="store_false",
                      dest="running_threads_plot",
                      default=True,
                      help="Disable graph displaying running threads")
    parser.add_option("",
                      "--nocoreload",
                      action="store_false",
                      dest="load_per_core_plot",
                      default=True,
                      help="Disable graph displaying CPU load per core")
    parser.add_option("",
                      "--noirq",
                      action="store_false",
                      dest="irq_plot",
                      default=True,
                      help="Disable graph displaying IRQs")
    parser.add_option(
        "-t",
        "--timeslice",
        action="store",
        type="int",
        dest="timeslice",
        default=150,
        help="Timeslice in ms for CPU load per core plot, default 150")
    parser.add_option("",
                      "--tsref",
                      action="store",
                      type="str",
                      dest="timestamp_file",
                      default="",
                      help="Use timestamp alignment file")
    parser.add_option("",
                      "--mhz",
                      action="store_true",
                      dest="cpu_mhz",
                      default=False,
                      help="CPU load per core in MHz")

    (options, args) = parser.parse_args()

    if len(args) != 1:
        print "Usage: type python <program>.py -h"
        return

    filterMaster.timestamp_start_b = int(options.start)
    filterMaster.timestamp_end_b = int(options.end)

    if str(options.timestamp_file):
        if timestamp_ref_module:
            ref_ts.set_file(str(options.timestamp_file))
        else:
            print "\'timestamp_ref\' module not found: \'--tsref\' discarded"

    filterMaster_ts.timestamp_start_b = int(options.start)
    filterMaster_ts.timestamp_end_b = int(options.end)
    filterMaster_ts.timeslice_ms = options.timeslice
    filterMaster_ts.num_of_cores = options.num_of_cores
    filterMaster_ts.mhz = options.cpu_mhz

    irqTrace.timestamp_start_b = int(options.start)
    irqTrace.timestamp_end_b = int(options.end)

    # CPU load detailed diagram
    ###########################

    file = open(args[0], 'r')
    string = file.readline()

    # search for regexp
    while (string):
        line_number += 1
        filterMaster.filter_line(string, line_number)
        string = file.readline()
    file.close()

    # CPU load per core
    ###################

    if options.load_per_core_plot:
        file = open(args[0], 'r')
        line_number = 0
        string = file.readline()

        # search num of cores
        if (filterMaster_ts.num_of_cores == 0):
            while (string):
                filterMaster_ts.filter_line_pre(string, line_number)
                string = file.readline()

        file.close()

        # search for regexp
        file = open(args[0], 'r')
        line_number = 0
        string = file.readline()

        while (string):
            line_number += 1
            filterMaster_ts.filter_line(string, line_number)
            string = file.readline()

        file.close()

    # IRQ diagram
    #############

    if options.irq_plot:
        file = open(args[0], 'r')
        string = file.readline()

        # search for regexp
        while (string):
            line_number += 1
            irqTrace.filter_line(string, line_number)
            string = file.readline()
        file.close()

    # Display
    #########

    #Update label size for Y axis for all charts
    matplotlib.rc('ytick', labelsize=10)

    bottom_margin = 0.05
    margin = 0.03
    first_graph = None

    #############################################################
    # Window 1: MPU Thread/IRQ execution                        #
    #############################################################
    win1_num_plot = []
    if options.running_threads_plot:
        win1_num_plot.append(2)
    if options.irq_plot:
        win1_num_plot.append(1)

    current_vert = 1 - margin
    current_plot = 0

    if len(win1_num_plot) > 0:
        left_margin = 0.2
        win1_vert_size = ((1 - bottom_margin - len(win1_num_plot) * margin) /
                          sum(win1_num_plot))

        fig1 = P.figure()

        if options.running_threads_plot:
            current_vert -= win1_vert_size * win1_num_plot[current_plot]
            gr = P.axes([
                left_margin, current_vert, 1 - (margin + left_margin),
                win1_vert_size * win1_num_plot[current_plot]
            ])
            current_vert -= margin
            current_plot += 1
            if (first_graph == None):
                first_graph = gr
            filterMaster.draw()

        if options.irq_plot:
            current_vert -= win1_vert_size * win1_num_plot[current_plot]
            gr = P.axes([
                left_margin, current_vert, 1 - (margin + left_margin),
                win1_vert_size * win1_num_plot[current_plot]
            ],
                        sharex=first_graph)
            current_vert -= margin
            current_plot += 1
            if (first_graph == None):
                first_graph = gr
            irqTrace.draw()

        P.xlabel('time (ms)')

        root1 = Tk.Tk()
        root1.title(string="MPU Thread/IRQ execution (" + args[0] + ")")
        canvas1 = FigureCanvasTkAgg(fig1, master=root1)
        canvas1.show()
        canvas1.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        toolbar1 = NavigationToolbar2TkAgg(canvas1, root1)
        toolbar1.update()
        canvas1._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

    #############################################################
    # Window 2: MPU load                                        #
    #############################################################
    win2_num_plot = []
    cpu_label_margin = 0.05

    if options.load_per_core_plot:
        win2_num_plot.append(1)

    current_vert = 1 - margin
    current_plot = 0

    if len(win2_num_plot) > 0:
        left_margin = 0.2
        win2_vert_size = ((1 - bottom_margin - len(win2_num_plot) * margin) /
                          sum(win2_num_plot))
        fig2 = P.figure()

        if options.load_per_core_plot:
            current_vert -= win2_vert_size * win2_num_plot[current_plot]
            gr = P.axes([
                left_margin, current_vert, 1 - (margin + left_margin),
                (win2_vert_size - cpu_label_margin) *
                win2_num_plot[current_plot]
            ],
                        sharex=first_graph)
            current_vert -= margin
            current_plot += 1
            if (first_graph == None):
                first_graph = gr
            filterMaster_ts.draw()

            P.xlabel('time (ms)')

        if len(win1_num_plot) > 0:
            root2 = Tk.Toplevel(root1)
        else:
            root2 = Tk.Tk()

        root2.title(string="MPU load (" + args[0] + ")")
        canvas2 = FigureCanvasTkAgg(fig2, master=root2)
        canvas2.show()
        canvas2.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        toolbar2 = NavigationToolbar2TkAgg(canvas2, root2)
        toolbar2.update()
        canvas2._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

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

    if len(win1_num_plot) > 0:
        root = root1
    else:
        root = root2

    def _quit():
        root.quit()  # stops mainloop
        root.destroy()  # this is necessary on Windows to prevent
        # Fatal Python Error: PyEval_RestoreThread: NULL tstate

    root.protocol("WM_DELETE_WINDOW", _quit)
    root.mainloop()
Example #9
0
    def __init__(self):
        '''Create the user interface and initialize it
        '''
        self.root = Tk()
        #self.root.geometry("+100+0")
        # Set window title from command-line argument, which is saved in self.subarray_name
        self.root.wm_title('Delay Widget')

        self.menu = Menu(self.root)

        filemenu = Menu(self.menu, tearoff=0)
        self.menu.add_cascade(label='File', menu=filemenu)

        filemenu.add_command(label='Open npz File...', command=self.Opennpz)
        filemenu.add_command(label='Save Delays to ACC', command=self.Save)
        filemenu.add_command(label='Save LoRX Delays to ACC',
                             command=self.SaveLoRX)

        self.root.config(menu=self.menu)

        fmain = Frame(self.root)
        fmain.pack()
        line1 = Frame(fmain)
        line1.pack()
        Label(line1, text='Ant 14 Y-X Delay',
              font="Helvetica 14").pack(side=LEFT, expand=1)
        self.dla14var = StringVar()
        self.dla14 = Entry(line1,
                           textvariable=self.dla14var,
                           font="Helvetica 14",
                           width=5)
        self.dla14var.set('0.0')
        self.dla14.bind("<Return>", self.fetch)
        self.dla14.pack(side=LEFT)
        dla14updown = Frame(line1)
        dla14updown.pack(side=LEFT)
        self.dla14upbtn = Button(dla14updown,
                                 text=u'\u25B2',
                                 command=self.up14dla,
                                 borderwidth=0,
                                 pady=0)
        self.dla14upbtn.pack(padx=1, pady=0)
        self.dla14dnbtn = Button(dla14updown,
                                 text=u'\u25BC',
                                 command=self.down14dla,
                                 borderwidth=0,
                                 pady=0)
        self.dla14dnbtn.pack(padx=1, pady=0)

        line2 = Frame(fmain)
        line2.pack()
        fleft = Frame(line2)
        fleft.pack(side=LEFT)
        leftant = Frame(fleft)
        leftant.pack(side=TOP)
        Label(leftant, text='Ant', font="Helvetica 14").pack(side=LEFT)
        self.antvar = StringVar()
        self.ant = Entry(leftant,
                         textvariable=self.antvar,
                         font="Helvetica 14",
                         width=3)
        self.antvar.set('1')
        #self.ant.bind("<Return>", self.fetch)
        self.ant.pack(side=LEFT)
        #antbtns = Frame(leftant)
        #antbtns.pack()
        antupdown = Frame(leftant)
        antupdown.pack()
        self.antupbtn = Button(antupdown,
                               text=u'\u25B2',
                               command=self.up,
                               borderwidth=0,
                               pady=0)
        self.antupbtn.pack(padx=1, pady=0)
        self.antdnbtn = Button(antupdown,
                               text=u'\u25BC',
                               command=self.down,
                               borderwidth=0,
                               pady=0)
        self.antdnbtn.pack(padx=1, pady=0)

        leftdla = Frame(fleft)
        leftdla.pack()
        Label(leftdla, text='X Delay', font="Helvetica 14").pack(side=LEFT)
        self.delays = np.zeros(13, np.float)
        self.dlavar = StringVar()
        self.dla = Entry(leftdla,
                         textvariable=self.dlavar,
                         font="Helvetica 14",
                         width=5)
        self.dlavar.set(str(self.delays[0]))
        self.dla.bind("<Return>", self.fetch)
        self.dla.pack(side=LEFT)
        #dlabtns = Frame(leftdla)
        dlaupdown = Frame(leftdla)
        dlaupdown.pack()
        self.dlaupbtn = Button(dlaupdown,
                               text=u'\u25B2',
                               command=self.updla,
                               borderwidth=0,
                               pady=0)
        self.dlaupbtn.pack(padx=1, pady=0)
        self.dladnbtn = Button(dlaupdown,
                               text=u'\u25BC',
                               command=self.downdla,
                               borderwidth=0,
                               pady=0)
        self.dladnbtn.pack(padx=1, pady=0)

        leftxydla = Frame(fleft)
        leftxydla.pack()
        Label(leftxydla, text='Y-X Delay', font="Helvetica 14").pack(side=LEFT)
        self.xydelays = np.zeros(13, np.float)
        self.xydlavar = StringVar()
        self.xydla = Entry(leftxydla,
                           textvariable=self.xydlavar,
                           font="Helvetica 14",
                           width=5)
        self.xydlavar.set(str(self.xydelays[0]))
        self.xydla.bind("<Return>", self.fetch)
        self.xydla.pack(side=LEFT)
        #dlabtns = Frame(leftdla)
        xydlaupdown = Frame(leftxydla)
        xydlaupdown.pack()
        self.xydlaupbtn = Button(xydlaupdown,
                                 text=u'\u25B2',
                                 command=self.xyupdla,
                                 borderwidth=0,
                                 pady=0)
        self.xydlaupbtn.pack(padx=1, pady=0)
        self.xydladnbtn = Button(xydlaupdown,
                                 text=u'\u25BC',
                                 command=self.xydowndla,
                                 borderwidth=0,
                                 pady=0)
        self.xydladnbtn.pack(padx=1, pady=0)

        fright = Frame(line2)
        fright.pack()

        self.fig = plt.figure(1)
        self.ax = []
        for i in range(4):
            self.ax.append(self.fig.add_subplot(220 + i + 1))
            self.ax[i].grid()
        self.canvas = FigureCanvasTkAgg(self.fig, fright)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, expand=1)
        toolbar1 = NavigationToolbar2TkAgg(self.canvas, fright)
        toolbar1.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        savebtn = Button(fmain, text='Show', command=self.show)
        savebtn.pack(side=LEFT, padx=3, pady=3)
        quitbtn = Button(fmain, text='Exit', command=self.root.quit)
        quitbtn.pack(side=LEFT, padx=3, pady=3)
        self.label1 = Label(fmain, text='', font='Courier 10')
        self.label1.pack()
        self.label2 = Label(fmain, text='', font='Courier 10')
        self.label2.pack()
        self.label3 = Label(fmain, text='', font='Courier 10')
        self.label3.pack()

        # Some test data to play with
        self.data_source = 'Simulation'
        self.fghz = np.array([3.4, 3.5, 3.6, 4.4, 4.6, 4.8])
        self.pol = np.array([0, 2, 3, 1])
        nf = len(self.fghz)
        taux = np.random.randn(13)
        tauy = taux + np.random.randn(13) * 0.1
        taux14 = 0.3
        tauy14 = -1.1
        df = np.random.randn(13, 4, nf) * 0.1
        self.ph = np.zeros((13, 4, nf), float)
        for k, fghz in enumerate(self.fghz):
            self.ph[:, 0,
                    k] = 2 * np.pi * fghz * (taux14 - taux) + df[:, 0, k]  # XX
            self.ph[:, 1,
                    k] = 2 * np.pi * fghz * (tauy14 - tauy) + df[:, 1, k]  # YY
            self.ph[:, 2,
                    k] = 2 * np.pi * fghz * (tauy14 - taux) + df[:, 2, k]  # XY
            self.ph[:, 3,
                    k] = 2 * np.pi * fghz * (taux14 - tauy) + df[:, 3, k]  # YX
        self.doplot(ant=1)
Example #10
0
    def __init__(self, root):
        self.images = []
        self.axes = []
        self.filename = ''
        self.sequenz = Daten()
        self.serialState = ''
        self.decstart = 0
        self.decend = 1500
        #GUI
        self.config = ConfigParser.RawConfigParser()
        self.configfile = 'LogikAnalyse.cfg'
        self.defaultDir = "Daten"
        try:
            self.loadConfig()
        except:
            print 'Kein Configfile gefunden, nehme Anfangswerte'
            #initial defaults
            self.pulseMin = 300
            self.samples = 1500
            self.comPortSelect = 'COM9'
            self.messTyp = 'pulse'

        self.root = root
        self.root.title('Logik Analyse')
        self.root.protocol("WM_DELETE_WINDOW", self.exit_)

        self.fig = matplotlib.figure.Figure()
        self.axes = self.fig.add_subplot(1, 1, 1)

        figframe = Tk.Frame(root)
        figframe.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        canvas = FigureCanvasTkAgg(self.fig, master=figframe)
        toolbar = NavigationToolbar2TkAgg(canvas, figframe)
        toolbar.pack(side=Tk.TOP, fill=Tk.BOTH)  # expand=1)
        self.modify_toolbar()

        self.scaleY()
        self.add_menu()

        configframe = Tk.Frame(root)
        configframe.pack(side=Tk.BOTTOM, fill=Tk.BOTH, expand=1)

        self.samplesSpinboxVal = Tk.StringVar()
        self.samplesSpinboxVal.set(str(self.samples))
        self.samplesSpinboxLabel = Tk.Label(configframe,
                                            text='Samples').pack(side=Tk.LEFT,
                                                                 anchor=Tk.E)
        self.samplesSpinbox = Tk.Spinbox(configframe,
                                         from_=500,
                                         to=5000,
                                         increment=500,
                                         width=5,
                                         textvariable=self.samplesSpinboxVal)
        self.samplesSpinbox.pack(side=Tk.LEFT)
        self.pulseMinSpinboxVal = Tk.StringVar()
        self.pulseMinSpinboxVal.set(str(self.pulseMin))
        self.pulseMinSpinboxLabel = Tk.Label(
            configframe, text='pulseMin').pack(side=Tk.LEFT, anchor=Tk.E)
        self.pulseMinSpinbox = Tk.Spinbox(configframe,
                                          from_=100,
                                          to=500,
                                          increment=50,
                                          width=5,
                                          textvariable=self.pulseMinSpinboxVal)
        self.pulseMinSpinbox.pack(side=Tk.LEFT)
        self.comPortSpinboxVal = Tk.StringVar()
        self.comPortSpinboxVal.set(str(self.comPortSelect))
        #print self.comPortSpinboxVal.get()
        self.comPorts = tuple(serial_ports())
        self.comPortSpinboxLabel = Tk.Label(configframe,
                                            text='Port').pack(side=Tk.LEFT,
                                                              anchor=Tk.E)
        self.comPortSpinbox = Tk.Spinbox(configframe,
                                         command=self.switchconnectSer(),
                                         values=self.comPorts,
                                         textvariable=self.comPortSpinboxVal,
                                         width=14)
        self.comPortSpinbox.pack(side=Tk.LEFT)
        self.messTypRadioVal = Tk.StringVar()
        self.messTypRadioVal.set(self.messTyp)
        self.messTypDtRadio = Tk.Radiobutton(configframe,
                                             text='dt',
                                             padx=0,
                                             variable=self.messTypRadioVal,
                                             value='dt')
        self.messTypDtRadio.pack(side=Tk.LEFT, anchor=Tk.W)
        self.messTypPulseRadio = Tk.Radiobutton(configframe,
                                                text='Pulse',
                                                padx=0,
                                                variable=self.messTypRadioVal,
                                                value='pulse')
        self.messTypPulseRadio.pack(side=Tk.LEFT, anchor=Tk.W)

        canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        self.root.bind('<Control-y>', lambda e: self.scaleY())
        self.root.bind('<Control-m>', lambda e: self.aufnahme())

        # implement the default mpl key bindings
        def on_key_event(event):
            #if (event.key=='y'):
            #    self.scaleY()
            key_press_handler(event, canvas, toolbar)

        self.tmp_cid1 = canvas.mpl_connect('key_press_event', on_key_event)

        def on_button_event(event):
            self.scaleY()

        self.tmp_cid2 = canvas.mpl_connect('button_release_event',
                                           on_button_event)
Example #11
0
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        self._bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        self._fgcolor = '#000000'  # X11 color: 'black'
        self._compcolor = '#d9d9d9'  # X11 color: 'gray85'
        self._ana1color = '#d9d9d9'  # X11 color: 'gray85'
        self._ana2color = '#d9d9d9'  # X11 color: 'gray85'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.', background=self._bgcolor)
        self.style.configure('.', foreground=self._fgcolor)
        self.style.map('.',
                       background=[('selected', self._compcolor),
                                   ('active', self._ana2color)])

        #init options and load .config file
        self.config = options.defaultConfig()
        options.loadConfig(self.config)

        top.geometry("1026x675+477+155")
        top.title("Pygrid")
        top.configure(highlightcolor="black")

        self.TSizegrip1 = ttk.Sizegrip(top)
        self.TSizegrip1.place(anchor=SE, relx=1.0, rely=1.0)

        self.Frame1 = Frame(top)
        self.Frame1.place(relx=0.0, rely=0.06, relheight=0.94, relwidth=0.78)
        self.Frame1.configure(relief=GROOVE, borderwidth="2", width=805)

        self.figure = Figure(dpi=50)
        self.Canvas1 = FigureCanvasTkAgg(self.figure, master=self.Frame1)
        self.Canvas1.get_tk_widget().pack(side=TOP, fill="both", expand=1)

        self.ax = self.figure.add_axes([.05, .05, .80, .9])
        self.ax.axis([
            float(self.config['gen']['dlonmin']),
            float(self.config['gen']['dlonmax']),
            float(self.config['gen']['dlatmin']),
            float(self.config['gen']['dlatmax'])
        ])
        self.cax = self.figure.add_axes([.05 + .8 + 0.025, .05, .025, .9])
        self.cax.set_visible(False)
        self.toolbar = NavigationToolbar2TkAgg(self.Canvas1, self.Frame1)
        self.menubar = Menu(top, bg=self._bgcolor, fg=self._fgcolor)
        top.configure(menu=self.menubar)

        def add_cascade(r, m, t):
            r.add_cascade(menu=m,
                          activebackground="#d9d9d9",
                          activeforeground="#000000",
                          background="#d9d9d9",
                          foreground="#000000",
                          label=t)

        def add_command(r, c, t):
            r.add_command(activebackground="#d8d8d8",
                          activeforeground="#000000",
                          background="#d9d9d9",
                          command=c,
                          foreground="#000000",
                          label=t)

        self.file = Menu(top, tearoff=0)
        add_cascade(self.menubar, self.file, "File")
        add_command(self.file, pygrid_support.TODO, "New")
        self.file.add_separator(background="#d9d9d9")
        add_command(self.file, pygrid_support.TODO, "Exit")

        self.save = Menu(top, tearoff=0)
        add_cascade(self.menubar, self.save, "Save")
        add_command(self.save, pygrid_support.save_segfile, "Save segfile")
        add_command(self.save, pygrid_support.save_neifile, "Save neifile")
        add_command(self.save, pygrid_support.save_nodfile, "Save nodfile")
        add_command(self.save, pygrid_support.save_nod2polyfile,
                    "Save nod2poly file")
        add_command(self.save, pygrid_support.save_llzfile, "Save llzfile")
        add_command(self.save, pygrid_support.save_markerfile,
                    "Save markerfile")

        self.load = Menu(top, tearoff=0)
        add_cascade(self.menubar, self.load, "Load")
        add_command(self.load, pygrid_support.load_coastline, "Load coastline")
        add_command(self.load, pygrid_support.load_segfile, "Load segfile")
        add_command(self.load, pygrid_support.load_neifile, "Load neifile")
        add_command(self.load, pygrid_support.load_nodfile, "Load nodfile")
        add_command(self.load, pygrid_support.load_llzfile, "Load llzfile")
        add_command(self.load, pygrid_support.load_fvcomfile, "Load fvcom")
        add_command(self.load, pygrid_support.load_markerfile,
                    "Load markerfile")

        self.options = Menu(top, tearoff=0)
        add_cascade(self.menubar, self.options, "Options")
        add_command(self.options, self.getGeneralOptionBox, "General Options")
        add_command(self.options, self.getCoastOptionBox, "Coastline Options")
        add_command(self.options, self.getSegOptionBox, "Seg Options")
        add_command(self.options, self.getNeiOptionBox, "Nei Options")
        add_command(self.options, self.getNodOptionBox, "Nod Options")
        add_command(self.options, self.getllzOptionBox, "llz Options")
        add_command(self.options, self.getFvcomOptionBox, "Fvcom Options")
        add_command(self.options, self.getMarkerOptionBox, "Marker Options")

        self.help = Menu(top, tearoff=0)
        add_cascade(self.menubar, self.help, "Help")
        add_command(self.help, pygrid_support.TODO, "About")

        ################################################################
        #
        #   Checkboxes
        #
        ################################################################
        self.Frame3 = Frame(top)
        self.Frame3.place(relx=0.0, rely=0.0, relheight=0.07, relwidth=0.78)
        self.Frame3.configure(relief=GROOVE, borderwidth="2", width=805)

        self.types = [
            'coast', 'seg', 'nei', 'nod', 'llz', 'neic', 'fvcom', 'marker'
        ]
        self.CBVar = {}
        for typ in self.types:
            self.CBVar[typ] = IntVar()

        def cbutton(frm, x, y, h, w, t, c, v):
            cb = Checkbutton(frm)
            cb.place(relx=x, rely=y, relheight=h, relwidth=w)
            cb.configure(activebackground="#d9d9d9", justify=LEFT)
            cb.configure(text=t, command=c, variable=v)
            return cb

        cbutton(self.Frame3, 0.01, 0.04, 0.91, 0.15, '''Show coastline''',
                pygrid_support.toggle_coastline, self.CBVar['coast'])
        cbutton(self.Frame3, 0.16, 0.04, 0.91, 0.15, '''Show Segfile''',
                pygrid_support.toggle_segfile, self.CBVar['seg'])
        cbutton(self.Frame3, 0.31, 0.04, 0.91, 0.12, '''Show Neifile''',
                pygrid_support.toggle_neifile, self.CBVar['nei'])
        cbutton(self.Frame3, 0.43, 0.04, 0.91, 0.14, '''Show Nodfile''',
                pygrid_support.toggle_nodfile, self.CBVar['nod'])
        cbutton(self.Frame3, 0.57, 0.04, 0.91, 0.12, '''Show llzfile''',
                pygrid_support.toggle_llzfile, self.CBVar['llz'])
        cbutton(self.Frame3, 0.70, 0.04, 0.91, 0.15, '''Show nei color''',
                pygrid_support.toggle_neifilecolor, self.CBVar['neic'])

        self.NeiMenuVar = StringVar(root)
        self.NeiChoices = {'Depth', 'dhh', 'Sidelength'}
        self.NeiMenuVar.set('Depth')
        self.NeiMenu = OptionMenu(self.Frame3, self.NeiMenuVar,
                                  *self.NeiChoices)
        self.NeiMenu.place(relx=0.850,
                           rely=0.04,
                           relheight=0.91,
                           relwidth=0.15)
        self.NeiMenuVar.trace('w', pygrid_support.change_neimenu)

        ########################################################################
        #
        #   Make notebook
        #
        ######################################################################

        self.nb = ttk.Notebook(top)

        self.Frame2 = Frame(self.nb)
        self.Frame2.place(relx=0.78, rely=0.0, relheight=0.75, relwidth=0.22)
        self.Frame2.configure(relief=GROOVE, borderwidth="2", width=215)

        self.Frame5 = Frame(self.nb)
        self.Frame5.place(relx=0.78, rely=0.0, relheight=0.75, relwidth=0.22)
        self.Frame5.configure(relief=GROOVE, borderwidth="2", width=215)

        self.Frame6 = Frame(self.nb)
        self.Frame6.place(relx=0.78, rely=0.0, relheight=0.75, relwidth=0.22)
        self.Frame6.configure(relief=GROOVE, borderwidth="2", width=215)

        self.Frame7 = Frame(self.nb)
        self.Frame7.place(relx=0.78, rely=0.0, relheight=0.75, relwidth=0.22)
        self.Frame7.configure(relief=GROOVE, borderwidth="2", width=215)

        self.Frame8 = Frame(self.nb)
        self.Frame8.place(relx=0.78, rely=0.0, relheight=0.75, relwidth=0.22)
        self.Frame8.configure(relief=GROOVE, borderwidth="2", width=215)

        self.nb.add(self.Frame2, text='Nodes')
        self.nb.add(self.Frame5, text='Depth')
        self.nb.add(self.Frame6, text='Seg')
        self.nb.add(self.Frame7, text='FVCOM')
        self.nb.add(self.Frame8, text='Marker')

        self.nb.place(relx=0.78, rely=0, relheight=0.75, relwidth=0.22)

        rh = 0.055
        rw = 0.85
        rw2 = 0.4
        rw4 = 0.2
        sh = 0.06

        ########################################################################
        # functions for labels entrys etc that capture common elements
        ########################################################################
        def label(frm, x, y, h, w, t):
            l = Label(frm)
            l.place(relx=x, rely=y, relheight=h, relwidth=w)
            l.configure(activebackground="#f9f9f9")
            l.configure(text=t)
            return l

        def entry(frm, x, y, h, w, t):
            e = Entry(frm)
            e.place(relx=x, rely=y, relheight=h, relwidth=w)
            e.configure(background="white")
            e.configure(font="TkFixedFont")
            e.configure(selectbackground="#c4c4c4")
            e.insert(0, t)
            return e

        def button(frm, x, y, h, w, t, c):
            b = Button(frm)
            b.place(relx=x, rely=y, relheight=h, relwidth=w)
            b.configure(activebackground="#d9d9d9")
            b.configure(text=t)
            b.configure(command=c)
            return b

        ########################################################################
        #
        #   Node Tab
        #
        ########################################################################

        ry = 0.01

        label(self.Frame2, 0.075, ry, rh, rw2, '''Set resolution''')
        self.Entry1 = entry(self.Frame2, 0.525, ry, rh, rw2, '')
        button(self.Frame2, 0.075, ry + sh * 1, rh, rw, '''Spray Area''',
               pygrid_support.spray_area)
        button(self.Frame2, 0.075, ry + sh * 2, rh, rw, '''Remove Area''',
               pygrid_support.remove_area)
        button(self.Frame2, 0.075, ry + sh * 3, rh, rw,
               '''Remove Area (llz)''', pygrid_support.remove_area_llz)
        button(self.Frame2, 0.075, ry + sh * 5, rh, rw,
               '''Remove nodes inside seg''', pygrid_support.remove_nodeseg_in)
        button(self.Frame2, 0.075, ry + sh * 6, rh, rw,
               '''Remove nodes outside seg''',
               pygrid_support.remove_nodeseg_out)
        button(self.Frame2, 0.075, ry + sh * 7, rh, rw,
               '''Extract nod from nei''', pygrid_support.extract_nod)
        button(self.Frame2, 0.075, ry + sh * 8, rh, rw,
               '''Extract seg from nei''', pygrid_support.extract_seg)
        button(self.Frame2, 0.075, ry + sh * 9, rh, rw,
               '''Extract llz from nei''', pygrid_support.extract_llz)

        ########################################################################
        #
        #   Depth tab
        #
        ########################################################################

        ry = 0.01
        label(self.Frame5, 0.1, ry, rh, .2, '''Min''')
        label(self.Frame5, 0.375, ry, rh, .2, '''Max''')
        label(self.Frame5, 0.66, ry, rh, .2, '''Mean''')

        ry += sh
        self.Labelsmin = label(self.Frame5, 0.1, ry, rh, .2, '''na''')
        self.Labelsmax = label(self.Frame5, 0.375, ry, rh, .2, '''na''')
        self.Labelsmean = label(self.Frame5, 0.66, ry, rh, .2, '''na''')

        button(self.Frame5, 0.075, ry + 0.05, rh, rw, '''Calc Stats''',
               pygrid_support.calc_stats)

        ry += 2 * sh
        label(self.Frame5, 0.5, ry, rh, rw2, '''Set depth''')
        button(self.Frame5, 0.075, ry + 0.05, rh, rw2, '''Set depth''',
               pygrid_support.set_depth)
        self.Entry3 = entry(self.Frame5, 0.525, ry + 0.05, rh, rw2, '')

        ry += 2 * sh
        label(self.Frame5, 0.5, ry, rh, rw2, '''Avg. depth''')
        button(self.Frame5, 0.075, ry + 0.05, rh, rw2, '''Avg. depth''',
               pygrid_support.avg_depth)
        self.Entry4 = entry(self.Frame5, 0.525, ry + 0.05, rh, rw2, '')

        ry += 2 * sh
        label(self.Frame5, .275, ry, rh, .3, '''Limit Min''')
        label(self.Frame5, .625, ry, rh, .3, '''Limit Max''')

        ry += sh
        label(self.Frame5, .05, ry, rh, .2, '''Depth''')
        self.Entryhmin = entry(self.Frame5, 0.275, ry, rh, rw2 * .75, '')
        self.Entryhmax = entry(self.Frame5, 0.625, ry, rh, rw2 * .75, '')

        ry += sh
        label(self.Frame5, .05, ry, rh, .2, '''dhh''')
        self.Entrydhhmin = entry(self.Frame5, 0.275, ry, rh, rw2 * .75, '')
        self.Entrydhhmax = entry(self.Frame5, 0.625, ry, rh, rw2 * .75, '')

        ry += sh
        button(self.Frame5, 0.075, ry, rh, rw, '''Smooth''',
               pygrid_support.smooth)

        ########################################################################
        #
        #   Seg Tab
        #
        ########################################################################
        ry = 0.01
        button(self.Frame6, 0.075, ry, rh, rw2, '''Select Seg''',
               pygrid_support.select_seg)
        self.Entry2 = entry(self.Frame6, 0.525, ry, rh, rw2, '')
        button(self.Frame6, 0.075, ry + sh * 1, rh, rw, '''Create Seg''',
               pygrid_support.create_seg)
        button(self.Frame6, 0.075, ry + sh * 2, rh, rw, '''Delete Seg''',
               pygrid_support.delete_seg)

        ########################################################################
        #
        #   FVCOM Tab
        #
        ########################################################################
        ry = 0.01
        cbutton(self.Frame7, 0.075, ry, rh, rw, '''Show FVCOM''',
                pygrid_support.toggle_fvcom, self.CBVar['fvcom'])

        label(self.Frame7, .075, ry + sh, rh, rw4, '''Times:''')
        self.timemin = label(self.Frame7, .275, ry + sh, rh, rw4, '''na''')
        self.timemax = label(self.Frame7, .5, ry + sh, rh, rw4, '''na''')
        self.etime = entry(self.Frame7, 0.75, ry + sh, rh, rw4, '0')
        label(self.Frame7, .075, ry + sh * 2, rh, rw4, '''Levels:''')
        self.lvlmin = label(self.Frame7, .275, ry + sh * 2, rh, rw4, '''na''')
        self.lvlmax = label(self.Frame7, .5, ry + sh * 2, rh, rw4, '''na''')
        self.elvl = entry(self.Frame7, 0.75, ry + sh * 2, rh, rw4, '0')

        self.FVCOMMenuVar = StringVar(root)
        self.FVCOMChoices = {
            'speed_da', 'speed', 'dhh', 'sidelength', 'vorticity_da',
            'vorticity', 'density'
        }
        self.FVCOMMenuVar.set('speed_da')
        self.FVCOMMenu = OptionMenu(self.Frame7, self.FVCOMMenuVar,
                                    *self.FVCOMChoices)
        self.FVCOMMenu.place(relx=0.075,
                             rely=ry + sh * 3,
                             relheight=rh,
                             relwidth=rw)
        #self.FVCOMMenuVar.trace('w', pygrid_support.TODO)#change_fvcommenu)

        self.overmenu = entry(self.Frame7, 0.075, ry + sh * 4, rh, rw, '')

        self.fsb = Frame(self.Frame7)
        self.fsb.place(relx=rw + .01,
                       rely=ry + sh * 5,
                       relheight=.625,
                       relwidth=0.1)

        self.sb = Scrollbar(self.fsb, orient="vertical")
        self.sb.pack(side=RIGHT, fill=Y)

        self.listbox = Listbox(self.Frame7)
        self.listbox.place(relx=0.01,
                           rely=ry + sh * 5,
                           relheight=.625,
                           relwidth=rw)

        # attach listbox to scrollbar
        self.listbox.config(yscrollcommand=self.sb.set)
        self.sb.config(command=self.listbox.yview)

        button(self.Frame7, 0.075, ry + sh * 15.5, rh, rw, '''Plot FVCOM''',
               pygrid_support._plot_fvcomfile)

        ########################################################################
        #
        #   Markers Tab
        #
        ########################################################################
        ry = 0.01
        cbutton(self.Frame8, 0.075, ry, rh, rw, '''Show Markers''',
                pygrid_support.toggle_markerfile, self.CBVar['marker'])

        label(self.Frame8, .075, ry + sh, rh, rw2, '''Lon:''')
        self.mlon = entry(self.Frame8, 0.075, ry + sh * 2, rh, rw2, '')

        label(self.Frame8, .525, ry + sh, rh, rw2, '''Lat:''')
        self.mlat = entry(self.Frame8, 0.525, ry + sh * 2, rh, rw2, '')

        label(self.Frame8, .075, ry + sh * 3, rh, rw, '''Label:''')
        self.mlabel = entry(self.Frame8, 0.075, ry + sh * 4, rh, rw, '')

        button(self.Frame8, 0.075, ry + sh * 15.5, rh, rw, '''Add Marker''',
               pygrid_support._add_marker)

        ########################################################################
        #
        #   Selection controls
        #
        ########################################################################
        self.FrameSelection = Frame(top)
        self.FrameSelection.place(relx=0.78,
                                  rely=0.75,
                                  relheight=.1,
                                  relwidth=0.22)
        self.FrameSelection.configure(relief=GROOVE,
                                      borderwidth="2",
                                      width=215)

        button(self.FrameSelection, 0.05, 0.075, 0.4, rw,
               '''Clear Selection''', pygrid_support.clear_selection)
        button(self.FrameSelection, 0.05, 0.525, 0.4, rw, '''Select Area''',
               pygrid_support.select_area)

        ########################################################################
        #
        #   Colorbar controls
        #
        ########################################################################
        self.Frame4 = Frame(top)
        self.Frame4.place(relx=0.78, rely=0.85, relheight=.15, relwidth=0.22)
        self.Frame4.configure(relief=GROOVE, borderwidth="2", width=215)

        label(self.Frame4, 0.05, 0.03, 0.255, rw2, '''Max''')
        self.Entry41 = entry(self.Frame4, 0.525, 0.03, 0.255, rw2, '')
        label(self.Frame4, 0.05, 0.33, 0.255, rw2, '''Min''')
        self.Entry42 = entry(self.Frame4, 0.525, 0.33, 0.255, rw2, '')
        button(self.Frame4, 0.075, .66, 0.255, rw2, '''Redraw llz''',
               pygrid_support.redraw_llz)
        button(self.Frame4, 0.525, .66, 0.255, rw2, '''Redraw nei''',
               pygrid_support.redraw_nei)
    def plot(self):
        # ------
        # Start simulation
        Sim = SolarSystemSimulation()

        # ------
        # Create new window to plot the simulation
        sim_window = tk.Toplevel()
        sim_window.title('SolarSystemSimulation')
        sim_window.focus_force()  # Auto-focus on window

        # Add interrupt button
        killswitch = ttk.Button(sim_window,
                                text="Close Simulation",
                                command=sim_window.destroy)
        killswitch.pack()

        fig, ax, elapsedTime = self.setupPlot(Sim)

        # Check if HTO is plotted
        if gui.plotHohmann.get():
            Sim, travelTime, transferDistanceAU = self.hohmannTransfer(Sim)

        # ------
        # Add Information to Plot
        info = self.addInformation(ax)
        info['elapsedTime'].set_text('Elapsed Time: {:.2f} Earth years'.format(
            gui.duration.get()))

        if gui.plotHohmann.get():
            info['originDestination'].set_text(
                '%s \u2192 %s' % (Sim.originPlanet, Sim.destinationPlanet))
            info['transferTime'].set_text('Transfer Time: %.2f Earth Years' %
                                          travelTime)
            info['transferDistance'].set_text('Transfer Distance: %.1f AU' %
                                              transferDistanceAU)

        # ------
        # Create plotting canvas
        canvas = FigureCanvasTkAgg(fig, sim_window)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        # Add matplotlib toolbar to the plot
        toolbar = NavigationToolbar2TkAgg(canvas, sim_window)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        # ------
        # Simulate and plot

        # For each planet in simulation, calculate trajectories
        planetTrajectories = {}
        for key, planet in Sim.Planets.items():
            planetTrajectories[key] = [planet.position]

        sphereOfInfluence = Sim.Planets[
            Sim.destinationPlanet].sphereOfInfluence  # in AU

        for i in range(Sim.steps):
            Sim.timeStep()
            for key, planet in Sim.Planets.items():
                planetTrajectories[key].append(planet.position)

                # If orbit insertion is performed, check if spacecraft has arrived at planet
                if gui.plotHohmann.get():
                    if gui.orbitInsertion.get():
                        distanceToDestination = np.sqrt((
                            Sim.Planets['HTO'].position[0] -
                            Sim.Planets[Sim.destinationPlanet].position[0]
                        )**2 + (
                            Sim.Planets['HTO'].position[1] -
                            Sim.Planets[Sim.destinationPlanet].position[1])**2)

                        if distanceToDestination < sphereOfInfluence:
                            Sim.Planets['HTO'].performOrbitInsertion(Sim)

        # Plot final trajectories
        for key, planet in Sim.Planets.items():
            ax.plot(*zip(*planetTrajectories[key]),
                    ls=planet.linestyle,
                    c=planet.colour,
                    lw=0.5)
            ax.plot(*planetTrajectories[key][-1],
                    marker=planet.marker,
                    c=planet.colour)

        # Add Sun
        sun, = ax.plot((0, 0), c='orange', marker='o', ls='')

        canvas.draw()
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        parent.deiconify()

        #Plot Widgets
        self.plot_frame = tk.LabelFrame(parent, text='Filter Data')
        self.plot_fig = Figure(figsize=(7, 5), dpi=100)
        self.plot_canvas = FigureCanvasTkAgg(self.plot_fig,
                                             master=self.plot_frame)
        self.plot_toolbar_frame = tk.Frame(self.plot_frame)
        self.plot_toolbar = NavigationToolbar2TkAgg(self.plot_canvas,
                                                    self.plot_toolbar_frame)
        self.plot_toolbar.update()

        self.plot_frame.grid(row=0, column=0, columnspan=6, sticky=tk.N + tk.S)
        self.plot_toolbar_frame.grid(row=1, column=0, columnspan=6)
        self.plot_canvas.get_tk_widget().grid(row=0, column=0, columnspan=6)

        #Control Widgets
        self.control_frame = tk.LabelFrame(parent, text='Controls')
        self.control_frame.grid(row=1,
                                column=0,
                                columnspan=6,
                                sticky=tk.N + tk.S + tk.E + tk.W)

        self.fs_entry = tk.Entry(self.control_frame)
        self.fs_entry.insert(0, '500')
        self.fs_label = tk.Label(self.control_frame,
                                 text='Sampling Frequency (kHz)')
        self.fs_label.grid(row=0, column=0, sticky=tk.E + tk.W)
        self.fs_entry.grid(row=0, column=1, sticky=tk.E + tk.W)

        self.fc_entry = tk.Entry(self.control_frame)
        self.fc_entry.insert(0, '95')
        self.fc_label = tk.Label(self.control_frame,
                                 text='Cutoff Frequency (kHz)')
        self.fc_label.grid(row=0, column=2, sticky=tk.E + tk.W)
        self.fc_entry.grid(row=0, column=3, sticky=tk.E + tk.W)

        self.poles = tk.IntVar(parent)
        self.poles.set(8)
        self.pole_option = tk.OptionMenu(self.control_frame, self.poles, 2, 4,
                                         6, 8, 10)
        self.pole_label = tk.Label(self.control_frame, text='Poles')
        self.pole_label.grid(row=0, column=4, sticky=tk.E + tk.W)
        self.pole_option.grid(row=0, column=5, sticky=tk.E + tk.W)

        self.fit_button = tk.Button(self.control_frame,
                                    text='Fit Filter',
                                    command=self.update_filter)
        self.fit_button.grid(row=1, column=1, sticky=tk.E + tk.W)

        self.residuals = tk.IntVar()
        self.residuals.set(0)
        self.residuals_check = tk.Checkbutton(self.control_frame,
                                              text='Plot Residuals',
                                              variable=self.residuals)
        self.residuals_check.grid(row=1, column=2, sticky=tk.E + tk.W)

        #Feedback Widgets
        self.feedback_frame = tk.LabelFrame(parent, text='Fit Parameters')
        self.feedback_frame.grid(row=2,
                                 column=0,
                                 columnspan=6,
                                 sticky=tk.N + tk.S + tk.E + tk.W)

        self.fit_report = tk.StringVar()
        self.fit_report_label = tk.Label(self.feedback_frame,
                                         textvariable=self.fit_report)
        self.fit_report_label.grid(row=0,
                                   column=0,
                                   columnspan=6,
                                   sticky=tk.E + tk.W)
Example #14
0
    return (x1(s + 0.001, k, lmb) - x1(s, k, lmb)) / 0.001


def x2derr(s, k, lmb):
    return (x2(s + 0.001, k, lmb) - x2(s, k, lmb)) / 0.001


a2.plot(s, x2derr(s, k, lmb))

canvas = FigureCanvasTkAgg(f, master=rootframe)
canvas.show()
canvas.get_tk_widget().grid(row=1, column=0, columnspan=5, sticky='W')

framen = Tk.Frame(rootframe)
framen.grid(row=0, column=0, columnspan=5, sticky=Tk.W)
toolbar = NavigationToolbar2TkAgg(canvas, framen)
toolbar.update()


def on_key_event(event):
    print('you pressed %s' % event.key)
    key_press_handler(event, canvas, toolbar)


canvas.mpl_connect('key_press_event', on_key_event)


def _quit():
    root.quit()  # stops mainloop
    root.destroy()  # this is necessary on Windows to prevent
    # Fatal Python Error: PyEval_RestoreThread: NULL tstate
Example #15
0
    def add_graph_subplot(self):
        plot_dict = {}
        plot_dict['fig'] = pylab.figure(1)
        plot_dict['frame_main_plot'] = Tkinter.Frame(self.root)
        plot_dict['frame_graph_fig'] = Tkinter.Frame(
            plot_dict['frame_main_plot'])
        plot_dict['frame_graph_info'] = Tkinter.Frame(
            plot_dict['frame_main_plot'])

        plot_dict['frame_graph_control'] = Tkinter.Frame(
            plot_dict['frame_graph_info'])
        plot_dict['frame_graph_text'] = Tkinter.Frame(
            plot_dict['frame_graph_info'])

        plot_dict['canvas'] = FigureCanvasTkAgg(
            plot_dict['fig'], master=plot_dict['frame_graph_fig'])
        plot_dict['canvas'].show()

        # Add matlotlib toolbar
        plot_dict['button_quit'] = Tkinter.Button(
            master=plot_dict['frame_graph_control'],
            text='Quit',
            command=lambda: self._quit())
        plot_dict['button_reset'] = Tkinter.Button(
            master=plot_dict['frame_graph_control'],
            text='Reset',
            command=lambda: self.reset())

        # Add matlotlib toolbar
        plot_dict['wScale'] = Tkinter.Scale(
            master=plot_dict['frame_graph_control'],
            from_=10,
            to=5500,
            sliderlength=30,
            label="X",
            orient=Tkinter.HORIZONTAL)
        plot_dict['wScale'].set(100)

        # Add matlotlib toolbar
        plot_dict['wScale_udp_packet'] = Tkinter.Scale(
            master=plot_dict['frame_graph_control'],
            from_=1,
            to=50,
            sliderlength=30,
            label="UDP-kbps",
            orient=Tkinter.HORIZONTAL)
        plot_dict['wScale_udp_packet'].set(5)

        # Add matlotlib toolbar
        plot_dict['toolbar'] = NavigationToolbar2TkAgg(
            plot_dict['canvas'], plot_dict['frame_graph_info'])
        plot_dict['toolbar'].update()

        plot_dict['wScale'].pack(side=Tkinter.LEFT)
        plot_dict['wScale_udp_packet'].pack(side=Tkinter.LEFT)
        plot_dict['button_quit'].pack(side=Tkinter.RIGHT)
        plot_dict['button_reset'].pack(side=Tkinter.RIGHT)

        # Add matlotlib toolbar
        plot_dict['TextInfo'] = Tkinter.Text(plot_dict['frame_graph_text'],
                                             height=6)
        plot_dict['TextInfo_timeinfo'] = Tkinter.Text(
            plot_dict['frame_graph_text'], height=6)

        plot_dict['TextInfo_timeinfo'].pack(side=Tkinter.TOP,
                                            fill=Tkinter.BOTH,
                                            expand=1)
        plot_dict['TextInfo'].pack(side=Tkinter.TOP,
                                   fill=Tkinter.BOTH,
                                   expand=1)

        plot_dict['canvas'].get_tk_widget().pack(side=Tkinter.TOP,
                                                 fill=Tkinter.BOTH,
                                                 expand=1)

        plot_dict['frame_graph_text'].pack(side=Tkinter.TOP,
                                           fill=Tkinter.BOTH,
                                           expand=1)
        plot_dict['frame_graph_control'].pack(side=Tkinter.TOP,
                                              fill=Tkinter.BOTH,
                                              expand=1)

        plot_dict['frame_graph_fig'].pack(side=Tkinter.TOP,
                                          fill=Tkinter.BOTH,
                                          expand=1)
        plot_dict['frame_graph_info'].pack(side=Tkinter.TOP,
                                           fill=Tkinter.BOTH,
                                           expand=1)
        plot_dict['frame_main_plot'].pack(side=Tkinter.LEFT,
                                          fill=Tkinter.BOTH,
                                          expand=1)

        #add subplot
        self.add_subplot(plot_dict['fig'], 0, 'ax_0_0', "udp-0",
                         [0, 1000, 700, 5000])
        self.add_subplot(plot_dict['fig'], 1, 'ax_1_0', "udp-1",
                         [0, 1000, 700, 5000])
        #self.add_subplot(plot_dict['fig'], 2, 'ax_2_0', "udp-2", [0,1000,700,5000])
        #self.add_subplot(plot_dict['fig'], 3, 'ax_3_0', "udp-3", [0,1000,700,5000])
        #self.add_subplot(plot_dict['fig'], 4, 'ax_4_0', "udp-4", [0,1000,700,5000])

        xAchse = pylab.arange(0, 100, 1)
        yAchse = pylab.array([0] * 100)
        self.add_line('ax_0_0', 'udp', xAchse, yAchse, '-')

        return plot_dict
Example #16
0
    def view_chart(self, df, field_name):
        '''
        f = Figure(figsize=(5,5), dpi=100)
        a = f.add_subplot(111)
        a.clear()
        a.plot(df)
        a.plot(df.index, df.iloc[: , 0:1] , "#00A3E0", label="Days")
        a.plot(df.index, df.iloc[: , 1:2] , "#183A54", label="Count")
        a.legend(bbox_to_anchor=(0, 1.02, 1, .102), loc=3, ncol=2, borderaxespad=0)
        a.set_title('Bar_chart ' + field_name)
        a.set_xlabel(field_name)
        '''
        # df = df_Geraete_große.copy(deep=True)
        # fieldName = 'Geräte_große'
        fieldName = field_name

        # fig, ax = plt.subplots()

        fig = Figure(figsize=(5, 5), dpi=100)
        ax = fig.add_subplot(111)

        ax.clear()
        index = df.index
        ind = np.arange(len(df))  # the x locations for the groups
        bar_width = 0.45  # the width of the bars

        mean = df['F_t_Fail_time_days']  # mean = df.iloc[: , 0:1].values

        count = df['count']  # count = df.iloc[: , 1:2].values

        opacity = 0.4
        error_config = {'ecolor': '0.3'}
        rects1 = ax.bar(ind,
                        mean,
                        bar_width,
                        alpha=opacity,
                        color='b',
                        error_kw=error_config,
                        label='Mean time to failure')
        rects2 = ax.bar(ind + bar_width,
                        count,
                        bar_width,
                        alpha=opacity,
                        color='r',
                        error_kw=error_config,
                        label='number of Equipment')

        # fig.set_figwidth(7) # set figure width
        # fig.set_figheight(5) # set figure height
        # add some  text for lables, title and axes ticks
        ax.set_xlabel(fieldName)
        ax.set_ylabel('amount')
        ax.set_title('Mean time to first Failure by' + fieldName)
        ax.set_xticks(ind + bar_width / 2)  # + bar_width / 2
        ax.set_xticklabels(
            index, rotation=10)  # rotation=x degree set rotation for ticks
        ax.legend()

        fig.tight_layout()

        def autolable(rects):
            for rect in rects:
                height = rect.get_height()
                ax.text(rect.get_x() + rect.get_width() / 2.,
                        1.05 * height,
                        '%d' % int(height),
                        ha='center',
                        va='bottom')

        autolable(rects1)
        autolable(rects2)
        # plt.show()

        # global canvas
        canvas = FigureCanvasTkAgg(fig, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        # global toolbar
        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        return canvas, toolbar
Example #17
0
    def layouts(self, histo_num):
		if histo_num>0 and histo_num < 7:
			columns=2
		elif histo_num>=7 and histo_num<=9:
			columns=3
		else:
			ERROR="Nie planuje."
			return ERROR
		histo_num=float(histo_num)
		histo_in_row=int(round(histo_num/columns))
		rows=1+(histo_in_row*2)
		row_size=600/histo_in_row
		for r in range(rows):
			if r%2==0:
				self.win.rowconfigure(r, minsize=10)
			else:
				self.win.rowconfigure(r, minsize=row_size)

		self.win.columnconfigure(0,minsize=200)
		column_size=1000/columns		
		for c in range(1,columns+1):
			self.win.columnconfigure(c,minsize =column_size)

		if histo_num>0 and histo_num <=9:
			histo_ID=0
			if histo_num%2 == 0 and histo_num<7:
				tab=list(range(1,rows))
			elif (histo_num%3==1 or histo_num%3==2) and histo_num>=7:
				tab=list(range(1,rows-2))
			elif histo_num%2 != 0 and histo_num<7:
				tab=list(range(1,rows-2))
			print("ROWS %d" %rows)
			for r in tab[0::2]:
				for c in range(1,columns+1):
					self.canvas[0][histo_ID].get_tk_widget().grid(row=r,column=c)
					histo_ID+=1
			histo_ID=0
			for r in tab[1::2]:
				for c in range(1,columns+1):
					self.TOOLBAR.append(NavigationToolbar2TkAgg(self.canvas[0][histo_ID],self.win))
					self.TOOLBAR[histo_ID].grid(row=r,column=c)
					histo_ID+=1
                        if histo_num==1:
                          self.canvas[0][histo_ID].get_tk_widget().grid(row=rows-2, column=1,columnspan=2,sticky=N+S+W+E)
                          self.TOOLBAR.append(NavigationToolbar2TkAgg(self.canvas[0][histo_ID],self.win))
                          self.TOOLBAR[histo_ID].grid(row=rows-1,column=1,columnspan=2,sticky=N+S) 

			if histo_num%2 != 0 and histo_num<7 and histo_num>1:
				self.canvas[0][histo_ID].get_tk_widget().grid(row=rows-2, column=1,columnspan=2,sticky=N+S)
				self.TOOLBAR.append(NavigationToolbar2TkAgg(self.canvas[0][histo_ID],self.win))
				self.TOOLBAR[histo_ID].grid(row=rows-1,column=1,columnspan=2,sticky=N+S)
			elif histo_num%3==1 and histo_num>=7:
				self.canvas[0][histo_ID].grid(row=rows-2,column=2)
				self.TOOLBAR.append(NavigationToolbar2TkAgg(self.canvas[0][histo_ID],self.win))
				self.TOOLBAR[histo_ID].grid(row=rows-1,columns=2)
			elif histo_num%3==2 and histo_num>=7:
				self.canvas[0][histo_ID].grid(row=rows-2,column=1,columnspan=2,sticky=W)
				self.TOOLBAR.append(NavigationToolbar2TkAgg(self.canvas[0][histo_ID],self.win))
				self.TOOLBAR[histo_ID].grid(row=rows-1,columns=3,columnspan=2,sticky=W)
				self.canvas[0][histo_ID+1].grid(row=rows-2,column=2,columnspan=2,sticky=E)
				self.TOOLBAR.append(NavigationToolbar2TkAgg(self.canvas[0][histo_ID+1],self.win))
				self.TOOLBAR[histo_ID+1].grid(row=rows-1,columns=2,columnspan=2,sticky=E)
		else:
			ERROR="Nie planuje."
			return ERROR
    def __init__(self, master):
        self.master = master

        self.frameTOP = Frame(master)
        self.frameTOP.grid(row=0, column=0, columnspan=2)

        self.frameBOT = Frame(master)
        self.frameBOT.grid(row=1, column=0, columnspan=2)

        self.frameLEFT = Frame(master)
        self.frameLEFT.grid(row=2, column=0, padx=5)

        self.frameRIGHT = Frame(master)
        self.frameRIGHT.grid(row=2, column=1, padx=5)

        self.frameBOTBOT = Frame(master)
        self.frameBOTBOT.grid(row=3, column=0, columnspan=2)

        self.file_name = ''

        self.checkVar = IntVar()
        self.checkVarFilter = IntVar()
        self.checkVarPath1 = IntVar()
        self.checkVarPath2 = IntVar()
        self.checkVarCurs = IntVar()
        self.checkVarPos1 = IntVar()
        self.checkVarPos2 = IntVar()
        self.checkVarFor1 = IntVar()
        self.checkVarFor2 = IntVar()

        self.fig = plt.Figure()

        self.checkBoxFilter = Checkbutton(self.frameTOP,
                                          variable=self.checkVarFilter)
        self.checkBoxFilter.grid(row=0, column=0)
        self.labelFilter1 = Label(self.frameTOP,
                                  text='Filter (Size :').grid(row=0, column=1)
        self.filterEntry = Entry(self.frameTOP, width=4)
        self.filterEntry.grid(row=0, column=2)
        self.filterEntry.insert(0, '100')
        self.labelFilter2 = Label(self.frameTOP, text=')').grid(row=0,
                                                                column=3)

        self.loadButton = Button(self.frameTOP,
                                 text="LOAD DATA",
                                 command=loadDataFromFile,
                                 state=DISABLED)
        self.loadButton.grid(row=0, column=4)

        self.plotButton = Button(self.frameTOP,
                                 text="PLOT",
                                 command=plot,
                                 state=DISABLED)
        self.plotButton.grid(row=0, column=5)

        self.plotChoicesButton = Button(self.frameTOP,
                                        text="PLOT CHOICES",
                                        command=plotChoices,
                                        state=DISABLED)
        self.plotChoicesButton.grid(row=0, column=6)

        #        self.quitButton = Button(self.frameTOP, text = "QUIT", fg = 'red', command = master.destroy)
        #        self.quitButton.pack(side = RIGHT)

        ##################################################
        self.checkBoxPath1 = Checkbutton(self.frameRIGHT,
                                         text='Path 1',
                                         variable=self.checkVarPath1)
        self.checkBoxPath1.grid(row=0, sticky=W)
        self.checkBoxPath1.select()

        self.checkBoxPath2 = Checkbutton(self.frameRIGHT,
                                         text='Path 2',
                                         variable=self.checkVarPath2)
        self.checkBoxPath2.grid(row=1, sticky=W)
        self.checkBoxPath2.select()

        self.checkBoxCurs = Checkbutton(self.frameRIGHT,
                                        text='Curs',
                                        variable=self.checkVarCurs)
        self.checkBoxCurs.grid(row=2, sticky=W)
        self.checkBoxCurs.select()

        self.checkBoxPos1 = Checkbutton(self.frameRIGHT,
                                        text='Pos 1',
                                        variable=self.checkVarPos1)
        self.checkBoxPos1.grid(row=3, sticky=W)
        self.checkBoxPos1.deselect()

        self.checkBoxPos2 = Checkbutton(self.frameRIGHT,
                                        text='Pos 2',
                                        variable=self.checkVarPos2)
        self.checkBoxPos2.grid(row=4, sticky=W)
        self.checkBoxPos2.deselect()

        self.checkBoxFor1 = Checkbutton(self.frameRIGHT,
                                        text='Force 1',
                                        variable=self.checkVarFor1)
        self.checkBoxFor1.grid(row=5, sticky=W)
        self.checkBoxFor1.select()

        self.checkBoxFor2 = Checkbutton(self.frameRIGHT,
                                        text='Force 2',
                                        variable=self.checkVarFor2)
        self.checkBoxFor2.grid(row=6, sticky=W)
        self.checkBoxFor2.select()

        ###################################################
        self.canvas = FigureCanvasTkAgg(self.fig, self.frameLEFT)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frameLEFT)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1, padx=5)

        ###################################################
        self.fileEntry = Entry(self.frameBOT, width='80')
        self.fileEntry.pack(side=LEFT)

        self.fileButton = Button(self.frameBOT,
                                 text='FILE',
                                 command=self.choosefile)
        self.fileButton.pack(side=RIGHT)
Example #19
0
m.drawmeridians(np.linspace(m.llcrnrlon, m.urcrnrlon, meridianres),
                labels=[False, False, False, True])
m.drawstates()
x = np.linspace(0, m.urcrnrx, dim[1])
y = np.linspace(0, m.urcrnry, dim[2])
xx, yy = np.meshgrid(x, y)

quad = m.pcolormesh(xx,
                    yy,
                    np.transpose(np.squeeze(ftledata[timestep, :, :])),
                    shading='gouraud',
                    cmap='viridis')
#quad = m.contourf(xx,yy, np.transpose(np.squeeze(ftledata[timestep,:,:])),shading='gouraud',cmap='viridis')
cbar = fig.colorbar(quad, ax=ax, pad=0.01)
ax.set_title('Time Step {0}'.format(timestep))
ridges = m.contour(xx,
                   yy,
                   np.transpose(np.squeeze(ftledata[timestep, :, :])),
                   levels=[-1])

canvas = FigureCanvasTkAgg(fig, root)
canvas.show()
canvas.get_tk_widget().grid(row=1, column=3, rowspan=40)

toolbar_frame = tk.Frame(root)
toolbar_frame.grid(row=0, column=3, sticky="w")
toolbar = NavigationToolbar2TkAgg(canvas, toolbar_frame)
toolbar.update()

#root.mainloop()
tk.mainloop()
Example #20
0
def arginine(self):
    ch_min = [0, 0, 40]
    ch_max = [-20, 30, 70]

    cc_min = [0, 0, 40]
    cc_max = [40, -20, 70]

    co_min = [45, -40, 10]
    co_max = [60, -40, -50]

    nh_min = [-45, 40, 10]
    nh_max = [-50, 40, -50]

    cn_min = [0, 0, 40]
    cn_max = [-45, 40, 10]

    cc1_min = [0, 0, 40]
    cc1_max = [45, -40, 10]

    c3_min = [40, -20, 70]
    c3_max = [80, -45, 60]

    c3h1_min = [80, -45, 60]
    c3h1_max = [70, -20, 40]

    c3h2_min = [80, -45, 60]
    c3h2_max = [100, -60, 40]

    c3c4_min = [80, -45, 60]
    c3c4_max = [125, -70, 100]

    c4h1_min = [125, -70, 100]
    c4h1_max = [145, -45, 80]

    c4h2_min = [125, -70, 100]
    c4h2_max = [155, -20, 120]

    c4n1_min = [125, -70, 100]
    c4n1_max = [175, -85, 80]

    c5n1_min = [175, -85, 80]
    c5n1_max = [280, -120, 130]

    c5n2_min = [280, -120, 130]
    c5n2_max = [310, -150, 100]

    c5n2h1_min = [310, -150, 100]
    c5n2h1_max = [350, -190, 130]

    c5n2h2_min = [310, -150, 100]
    c5n2h2_max = [270, -200, 70]

    c5n3_min = [280, -120, 130]
    c5n3_max = [250, -180, 160]

    c5n3h1_min = [250, -180, 160]
    c5n3h1_max = [300, -240, 200]

    c5n3h2_min = [250, -180, 160]
    c5n3h2_max = [200, -230, 130]

    c4n1h1_min = [175, -85, 80]
    c4n1h1_max = [185, -110, 40]

    c2h1_min = [40, -20, 70]
    c2h1_max = [50, -50, 100]

    c2h2_min = [40, -20, 70]
    c2h2_max = [25, 10, 100]

    fig = Figure(figsize=(10, 6), dpi=100, facecolor='black')
    canvas = FigureCanvasTkAgg(fig, self)
    canvas.draw()
    ax = fig.add_subplot(111, projection="3d")
    ax.set_axis_bgcolor("black")

    ch = ax.plot([ch_max[0], ch_min[0]], [ch_max[1], ch_min[1]],
                 [ch_max[2], ch_min[2]],
                 linewidth=5,
                 color=ch_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    cc = ax.plot([cc_max[0], cc_min[0]], [cc_max[1], cc_min[1]],
                 [cc_max[2], cc_min[2]],
                 linewidth=5,
                 color=cc_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    co = ax.plot([co_max[0], co_min[0]], [co_max[1], co_min[1]],
                 [co_max[2], co_min[2]],
                 linewidth=5,
                 color=co_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    nh = ax.plot([nh_max[0], nh_min[0]], [nh_max[1], nh_min[1]],
                 [nh_max[2], nh_min[2]],
                 linewidth=5,
                 color=nh_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    cn = ax.plot([cn_max[0], cn_min[0]], [cn_max[1], cn_min[1]],
                 [cn_max[2], cn_min[2]],
                 linewidth=5,
                 color=cn_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    ccl = ax.plot([cc1_max[0], cc1_min[0]], [cc1_max[1], cc1_min[1]],
                  [cc1_max[2], cc1_min[2]],
                  linewidth=5,
                  color=cc_color,
                  marker='o',
                  markerfacecolor='orange',
                  markersize=12)
    c3 = ax.plot([c3_max[0], c3_min[0]], [c3_max[1], c3_min[1]],
                 [c3_max[2], c3_min[2]],
                 linewidth=5,
                 color=cc_color,
                 marker='o',
                 markerfacecolor='orange',
                 markersize=12)
    c3h1 = ax.plot([c3h1_max[0], c3h1_min[0]], [c3h1_max[1], c3h1_min[1]],
                   [c3h1_max[2], c3h1_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c3h2 = ax.plot([c3h2_max[0], c3h2_min[0]], [c3h2_max[1], c3h2_min[1]],
                   [c3h2_max[2], c3h2_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c3c4 = ax.plot([c3c4_max[0], c3c4_min[0]], [c3c4_max[1], c3c4_min[1]],
                   [c3c4_max[2], c3c4_min[2]],
                   linewidth=5,
                   color=cc_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c4h1 = ax.plot([c4h1_max[0], c4h1_min[0]], [c4h1_max[1], c4h1_min[1]],
                   [c4h1_max[2], c4h1_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c4h2 = ax.plot([c4h2_max[0], c4h2_min[0]], [c4h2_max[1], c4h2_min[1]],
                   [c4h2_max[2], c4h2_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c4n1 = ax.plot([c4n1_max[0], c4n1_min[0]], [c4n1_max[1], c4n1_min[1]],
                   [c4n1_max[2], c4n1_min[2]],
                   linewidth=5,
                   color=cn_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c5n1 = ax.plot([c5n1_max[0], c5n1_min[0]], [c5n1_max[1], c5n1_min[1]],
                   [c5n1_max[2], c5n1_min[2]],
                   linewidth=5,
                   color=cn_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c5n2 = ax.plot([c5n2_max[0], c5n2_min[0]], [c5n2_max[1], c5n2_min[1]],
                   [c5n2_max[2], c5n2_min[2]],
                   linewidth=5,
                   color=cn_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c5n2h1 = ax.plot([c5n2h1_max[0], c5n2h1_min[0]],
                     [c5n2h1_max[1], c5n2h1_min[1]],
                     [c5n2h1_max[2], c5n2h1_min[2]],
                     linewidth=5,
                     color=nh_color,
                     marker='o',
                     markerfacecolor='orange',
                     markersize=12)
    c5n2h2 = ax.plot([c5n2h2_max[0], c5n2h2_min[0]],
                     [c5n2h2_max[1], c5n2h2_min[1]],
                     [c5n2h2_max[2], c5n2h2_min[2]],
                     linewidth=5,
                     color=nh_color,
                     marker='o',
                     markerfacecolor='orange',
                     markersize=12)
    c5n3 = ax.plot([c5n3_max[0], c5n3_min[0]], [c5n3_max[1], c5n3_min[1]],
                   [c5n3_max[2], c5n3_min[2]],
                   linewidth=5,
                   color=cn_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c5n3h1 = ax.plot([c5n3h1_max[0], c5n3h1_min[0]],
                     [c5n3h1_max[1], c5n3h1_min[1]],
                     [c5n3h1_max[2], c5n3h1_min[2]],
                     linewidth=5,
                     color=nh_color,
                     marker='o',
                     markerfacecolor='orange',
                     markersize=12)
    c5n3h2 = ax.plot([c5n3h2_max[0], c5n3h2_min[0]],
                     [c5n3h2_max[1], c5n3h2_min[1]],
                     [c5n3h2_max[2], c5n3h2_min[2]],
                     linewidth=5,
                     color=nh_color,
                     marker='o',
                     markerfacecolor='orange',
                     markersize=12)
    c4n1h1 = ax.plot([c4n1h1_max[0], c4n1h1_min[0]],
                     [c4n1h1_max[1], c4n1h1_min[1]],
                     [c4n1h1_max[2], c4n1h1_min[2]],
                     linewidth=5,
                     color=nh_color,
                     marker='o',
                     markerfacecolor='orange',
                     markersize=12)
    c2h1 = ax.plot([c2h1_max[0], c2h1_min[0]], [c2h1_max[1], c2h1_min[1]],
                   [c2h1_max[2], c2h1_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)
    c2h2 = ax.plot([c2h2_max[0], c2h2_min[0]], [c2h2_max[1], c2h2_min[1]],
                   [c2h2_max[2], c2h2_min[2]],
                   linewidth=5,
                   color=ch_color,
                   marker='o',
                   markerfacecolor='orange',
                   markersize=12)

    tch = plt.Rectangle((0, 0), 1, 1, fc=ch_color)
    tch1 = plt.Rectangle((0, 0), 1, 1, fc=ch_color)
    tcn = plt.Rectangle((0, 0), 1, 1, fc=cn_color)
    tcc = plt.Rectangle((0, 0), 1, 1, fc=cc_color)
    tbco = plt.Rectangle((0, 0), 1, 1, fc=co_color)
    tbnh = plt.Rectangle((0, 0), 1, 1, fc=nh_color)

    ax.legend([tch, tcn, tcc, tbco, tbnh], ['ch', 'cn', 'cc', 'co', 'nh'])
    ax.axis("off")
    toolbarFrame = Frame(self)
    toolbarFrame.grid(row=6, column=7)
    toolbar = NavigationToolbar2TkAgg(canvas, toolbarFrame)
    canvas.get_tk_widget().grid(row=4, column=7)
Example #21
0
    def do_plot(self):
        if self.plate != int(self.e1.get()) or self.mjd != int(self.e2.get()):
            self.plate = int(self.e1.get())
            self.mjd = int(self.e2.get())
            self.fiber = int(self.e3.get())
            self.znum = int(self.e5.get())
            self.platepath = join(environ['BOSS_SPECTRO_REDUX'],
                                  environ['RUN2D'], '%s' % self.plate,
                                  'spPlate-%s-%s.fits' % (self.plate, self.mjd))
            hdu = fits.open(self.platepath)
            self.specs = hdu[0].data
            self.wave = 10**(hdu[0].header['COEFF0'] +
                             n.arange(hdu[0].header['NAXIS1']) *
                             hdu[0].header['COEFF1'])
            self.models = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[2].data
            self.fiberid = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                          environ['RUN2D'], '%s' % self.plate,
                                          environ['RUN1D'],
                                          'redmonster-%s-%s.fits' %
                                          (self.plate,
                                           self.mjd)))[1].data.FIBERID
            self.type1 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS1
            self.type2 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS2
            self.type3 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS3
            self.type4 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS4
            self.type5 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS5
            self.z = n.zeros((self.fiberid.shape[0],5))
            self.z[:,0] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z1
            self.z[:,1] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z2
            self.z[:,2] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z3
            self.z[:,3] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z4
            self.z[:,4] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z5
            self.zwarning = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                           environ['RUN2D'], '%s' % self.plate,
                                           environ['RUN1D'],
                                           'redmonster-%s-%s.fits' %
                                           (self.plate,
                                            self.mjd)))[1].data.ZWARNING
        else:
            self.fiber = int(self.e3.get())
        f = Figure(figsize=(10,6), dpi=100)
        a = f.add_subplot(111)
        loc = n.where(self.fiberid == self.fiber)[0]
        if self.znum == 1:
            z = self.z[loc[0],0]
            thistype = self.type1[loc[0]]
        elif self.znum == 2:
            z = self.z[loc[0],1]
            thistype = self.type2[loc[0]]
        elif self.znum == 3:
            z = self.z[loc[0],2]
            thistype = self.type3[loc[0]]
        elif self.znum == 4:
            z = self.z[loc[0],3]
            thistype = self.type4[loc[0]]
        elif self.znum == 5:
            z = self.z[loc[0],4]
            thistype = self.type5[loc[0]]
        if self.var.get() == 0:
            if self.restframe.get() == 0:
                a.plot(self.wave, self.specs[self.fiber], color='black')
            elif self.restframe.get() == 1:
                a.plot(self.wave/(1+self.z[loc][0]), self.specs[self.fiber],
                       color='black')
        elif self.var.get() == 1:
            smooth = self.e4.get()
            if smooth is '':
                if self.restframe.get() == 0:
                    a.plot(self.wave, self.specs[self.fiber], color='black')
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), self.specs[self.fiber],
                           color='black')
            else:
                if self.restframe.get() == 0:
                    a.plot(self.wave, convolve(self.specs[self.fiber],
                                               Box1DKernel(int(smooth))),
                           color='black')
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), convolve(self.specs[self.fiber],
                                                     Box1DKernel(int(smooth))),
                           color='black')
            # Overplot model
            if len(loc) is not 0:
                if self.restframe.get() == 0:
                    #a.plot(self.wave, self.models[loc[0]], color='black')
                    # This for when multiple models are in redmonster file
                    a.plot(self.wave, self.models[loc[0],self.znum-1],
                           color='cyan')
                    if self.ablines.get() == 1:
                        for i, line in enumerate(self.ablinelist):
                            if ((line*(1+z) > self.wave[0]) &
                                    (line*(1+z) < self.wave[-1])):
                                a.axvline(line*(1+z), color='blue',
                                          linestyle='--',
                                          label=self.ablinenames[i])
                    if self.emlines.get() == 1:
                        for i, line in enumerate(self.emlinelist):
                            if (line*(1+z) > self.wave[0]) & (line*(1+z) < \
                                                              self.wave[-1]):
                                a.axvline(line*(1+z), color='red',
                                          linestyle='--',
                                          label=self.emlinenames[i])
                    if self.ablines.get() == 1 or self.emlines.get() == 1:
                        a.legend(prop={'size':10})
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), self.models[loc[0],self.znum-1],
                           color='cyan')
                    if self.ablines.get() == 1:
                        for i, line in enumerate(self.ablinelist):
                            if (line > self.wave[0]) & (line < self.wave[-1]):
                                a.axvline(line, color='blue', linestyle='--',
                                          label=self.ablinenames[i])
                    if self.emlines.get() == 1:
                        for i, line in enumerate(self.emlinelist):
                            if (line > self.wave[0]) & (line < self.wave[-1]):
                                a.axvline(line, color='red', linestyle='--',
                                          label=self.emlinenames[i])
                    if self.ablines.get() == 1 or self.emlines.get() == 1:
                        a.legend(prop={'size':10})
                a.set_title('Plate %s Fiber %s: z=%s class=%s zwarning=%s' %
                            (self.plate, self.fiber, z, thistype,
                             self.zwarning[loc[0]]))
            else:
                print('Fiber %s is not in redmonster-%s-%s.fits' % \
                        (self.fiber, self.plate, self.mjd))
                a.set_title('Plate %s Fiber %s' % (self.plate, self.fiber))

        if self.restframe.get() == 1:
            lower_data, upper_data = self.set_limits()
            a.axis([self.wave[0]/(1+z)-100,self.wave[-1]/(1+z)+100,
                    lower_data,upper_data])
        elif self.restframe.get() == 0:
            lower_data, upper_data = self.set_limits()
            a.axis([self.wave[0]-100,self.wave[-1]+100,lower_data,upper_data])
        a.set_xlabel('Wavelength ($\AA$)')
        a.set_ylabel('Flux ($10^{-17} erg\ cm^2 s^{-1} \AA^{-1}$)')
        canvas = FigureCanvasTkAgg(f, master=self.root)
        canvas.get_tk_widget().grid(row=0, column=5, rowspan=20)
        toolbar_frame = Frame(self.root)
        toolbar_frame.grid(row=20,column=5)
        toolbar = NavigationToolbar2TkAgg( canvas, toolbar_frame )
        canvas.show()
Example #22
0
                    position=(0., 0.9),
                    color='b')
t3 = ax3.set_ylabel("",
                    labelpad=-15,
                    rotation="horizontal",
                    position=(0., 0.9),
                    color='b')

t4 = Label(window, text="  isodoses :")
t6 = Label(window, text="structures :")

graph1 = FigureCanvasTkAgg(fig1, master=window)
canvas1 = graph1.get_tk_widget()

toolbar_frame = Frame(window)
toolbar = NavigationToolbar2TkAgg(graph1, toolbar_frame)
#toolbar = NavigationToolbar2Tk( graph1, toolbar_frame )

toolbar.pan()  # default widget

check1 = Checkbutton(window, command=show_isodose)
check2 = Checkbutton(window, command=show_ROI)

w1 = Scale(window,
           from_=0,
           to=dim_x - 1,
           orient=VERTICAL,
           command=w1move,
           showvalue=0)
w2 = Scale(window,
           from_=0,
Example #23
0
    def __init__(self, parent, controller):
        self.controller = controller
        self.title = "Backtest"
        ttk.Frame.__init__(self, parent)

        # Left Pane
        left_frame = ttk.Frame(self, padding=20)
        left_frame.pack(side="left")

        label = ttk.Label(left_frame, text="Pre-trained Stock")
        label.pack(padx=10, anchor=tk.W)
        symbol_list = ttk.Combobox(left_frame, width=18, font=("Calibri", 12))
        symbol_list.pack(padx=20, pady=(0, 35), anchor=tk.W)

        label = ttk.Label(left_frame, text="Start Date - ex: 2015-03-31")
        label.pack(
            padx=10,
            anchor=tk.W,
        )
        start_entry = ttk.Entry(left_frame, width=20, font=("Calibri", 12))
        start_entry.pack(padx=20, anchor=tk.W)

        label = ttk.Label(left_frame, text="End Date")
        label.pack(
            padx=10,
            anchor=tk.W,
        )
        end_entry = ttk.Entry(left_frame, width=20, font=("Calibri", 12))
        end_entry.pack(padx=20, pady=(0, 35), anchor=tk.W)

        label = ttk.Label(left_frame, text="Predictive Model")
        label.pack(
            padx=10,
            anchor=tk.W,
        )
        models = self.controller.get_trained_models(symbol_list.get())
        type_list = ttk.Combobox(left_frame, width=18, font=("Calibri", 12))
        type_list.pack(padx=20, anchor=tk.W)

        run_btn = ttk.Button(left_frame,
                             text="Run Backtesting",
                             padding=(25, 10, 25, 10),
                             command=lambda: run_backtest())
        run_btn.pack(pady=50, padx=15, anchor=tk.W)

        # Right Pane
        right_frame = ttk.Frame(self, padding=20)
        right_frame.pack(side="right")

        figure = Figure(figsize=(12, 8), dpi=60, facecolor='white')
        canvas = FigureCanvasTkAgg(figure, right_frame)
        canvas.get_tk_widget().grid(row=0, column=1)
        toolbar = NavigationToolbar2TkAgg(canvas, right_frame)
        toolbar.grid(row=1, column=1, pady=20)

        def update_selections(event):
            trained_symbols = self.controller.get_trained_symbols()
            symbol_list['value'] = trained_symbols
            if trained_symbols:
                symbol_list.current(0)
            models = self.controller.get_trained_models(symbol_list.get())
            type_list['value'] = models
            if trained_symbols:
                type_list.current(0)

        self.bind("<Visibility>", update_selections)

        def symbol_change_handler(event):
            trained_models = self.controller.get_trained_models(
                symbol_list.get())
            type_list['value'] = trained_models
            if len(trained_models) == 0:
                type_list['value'] = ["No trained models found"]
            type_list.current(0)

        symbol_list.bind("<<ComboboxSelected>>", symbol_change_handler)

        def on_key_event(event):
            key_press_handler(event, canvas, toolbar)

        canvas.mpl_connect('key_press_event', on_key_event)

        def on_click(event):
            canvas._tkcanvas.focus_set()

        canvas.mpl_connect('button_press_event', on_click)

        def run_backtest():
            # extract variables needed for execuation
            symbol = symbol_list.get()
            start_date = start_entry.get()
            end_date = end_entry.get()
            model = type_list.get()

            # run selected model backtest
            try:
                plot = self.controller.run_backtest(symbol, model, start_date,
                                                    end_date)
            except ValidationError as input_error:
                print input_error.message

            figure.clear()
            plot_data(figure, plot)
            canvas.draw()
Example #24
0
    def __init__(self, odf, plotter):
        self.f = Figure()

        # Save reference to the model
        self.odf = odf
        # Save reference to the plotter
        self.plotter = plotter

        self.leftMask = None
        self.rightMask = None
        self.activeLine = None

        self.root = tk.Tk()
        self.root.wm_title("PyA Model Explorer")
        # Make the widgets expand/shrink as window size changes
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        # Bind the mouse wheel
        if platform.system() == "Linux":
            self.root.bind("<Button-4>", self._mouseWheel)
            self.root.bind("<Button-5>", self._mouseWheel)
        elif platform.system() == "Darwin":
            self.root.bind("<MouseWheel>", self._onWheel)  # for OS X

        # A frame containing the mpl plot
        self.plotFrame = tk.Frame()
        self.plotFrame.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
        self.canvas = FigureCanvasTkAgg(self.f, master=self.plotFrame)

        # A frame containing the box with selected points
        # and control buttons
        self.controlFrame = tk.Frame(self.root)
        self.controlFrame.pack(side=tk.RIGHT, expand=False, fill=tk.BOTH)
        self.selectedPar = tk.StringVar(self.controlFrame)

        # Get parameters of model
        ps = list(self.odf.parameters().keys())
        # Set default modification properties
        # Saves these properties for all parameters
        self.modProps = {}
        for p in ps:
            self.modProps[p] = {
                "modus": "mul",
                "modValMul": 1.02,
                "modValAdd": 0.01
            }

        # Frame containing all parameters
        self.parameterFrame = tk.Frame(self.controlFrame,
                                       height=2,
                                       bd=1,
                                       relief=tk.SUNKEN)

        # Dictionaries holding the specific information for each parameter
        self.singleParameterFrames = {}
        self.singleParameterEntry = {}
        self.singleParameterVar = {}
        # knows whether the parameter is free (value=True) or frozen (=False)
        self.singleParameterFree = {}

        # Closures around the functions adapting thaw/freeze
        def frozenChanged(k):
            def change():
                if self.singleParameterFree[k].get() == True:
                    self.odf.thaw(k)
                else:
                    self.odf.freeze(k)
                self._updateDof()

            return change

        # define what happens when a value is set to the entered parameter (closures)
        def hitReturn(k):
            def change(*args):
                self.selectedPar.set(k)
                self.odf[k] = float(self.singleParameterVar[k].get())
                self._parameterValueChanged()

            return change

        # defines what happens when a parameter's value is changed, but not set yet, i.e., not current (closures)
        def parameterValueChanged(k):
            def valueChanged(*args):
                pp, ll = str(self.singleParameterVar[k].get()).find("."), len(
                    str(self.singleParameterVar[k].get()))
                if round(self.odf[k], ll - pp - 1) != round(
                        self.singleParameterVar[k].get(), ll - pp - 1):
                    self.singleParameterEntry[k].configure(bg="red")
                else:
                    self.singleParameterEntry[k].configure(bg="white")

            return valueChanged

        # Create an entry for each parameter
        # Create a scrollable region
        # Check maximum number of characters for parameter names:
        maxParamLen = 0
        for k in sorted(self.odf.parameters().keys()):
            if len(k) > maxParamLen:
                maxParamLen = len(k)
            # Create an entry for each parameter
        for k in sorted(self.odf.parameters().keys()):
            x = tk.Frame(self.parameterFrame,
                         height=2,
                         bd=2,
                         relief=tk.SUNKEN,
                         pady=2)
            self.singleParameterFrames[k] = x
            y0 = tk.Radiobutton(x,
                                text=k,
                                variable=self.selectedPar,
                                value=k,
                                width=maxParamLen + 1,
                                indicatoron=0)
            y0.pack(side=tk.LEFT)
            #y1 = tk.StringVar()
            y1 = tk.DoubleVar()
            y1.set(self.odf[k])
            y2 = tk.Entry(x, textvariable=y1, width=8)
            y2.bind('<Return>', hitReturn(k))
            self.singleParameterVar[k] = y1
            self.singleParameterVar[k].trace('w', parameterValueChanged(k))
            self.singleParameterEntry[k] = y2
            y2.pack(side=tk.LEFT)
            self.singleParameterFrames[k].pack()
            modModus = tk.StringVar()
            modModus.set(self.modProps[k]["modus"])
            self.singleParameterFree[k] = tk.BooleanVar()
            self.singleParameterFree[k].set(k in self.odf.freeParamNames())
            y3 = tk.Radiobutton(x,
                                text="Thawed",
                                value=True,
                                variable=self.singleParameterFree[k],
                                command=frozenChanged(k))
            y4 = tk.Radiobutton(x,
                                text="Frozen",
                                value=False,
                                variable=self.singleParameterFree[k],
                                command=frozenChanged(k))
            y3.pack(side=tk.RIGHT)
            y4.pack(side=tk.RIGHT)
            self.parameterFrame.pack(fill=tk.X, expand=False)

        # Set of the menu to select the current parameter
        self.selectedPar.set(ps[0])

        # Chi2 frame:
        # , relief=tk.SUNKEN)
        self.chi2Frame = tk.Frame(self.controlFrame, borderwidth=10)
        self.chi2value = tk.DoubleVar()
        self.chi2value.set(self.plotter.chi2)
        self.dofValue = tk.IntVar()
        # self.dofValue.set(len(self.plotter.fitIdx))
        # self.dofValue.set(100)
        self.dofValue.set(
            len(self.plotter.x) - len(self.odf.freeParameters()) - 1)
        self.chi2Label = tk.Label(self.chi2Frame, text="Chi2: ")
        self.dofLabel = tk.Label(self.chi2Frame, text="dof: ")
        self.chi2Entry = tk.Entry(self.chi2Frame,
                                  textvariable=self.chi2value,
                                  bd=2,
                                  width=10)
        self.dofEntry = tk.Entry(self.chi2Frame,
                                 textvariable=self.dofValue,
                                 bd=2,
                                 width=10)
        self.chi2Label.pack(side=tk.LEFT)
        self.chi2Entry.pack(side=tk.LEFT)
        self.dofLabel.pack(side=tk.LEFT)
        self.dofEntry.pack(side=tk.LEFT)
        self.chi2Frame.pack()

        # Frame to bundle mouse-wheel inputs
        self.mouseWheelFrame = tk.Frame(self.controlFrame,
                                        height=2,
                                        bd=3,
                                        relief=tk.SUNKEN)
        self.mwmLabel = tk.Label(self.mouseWheelFrame,
                                 text="Mouse wheel manipulation")
        self.mwmLabel.pack()
        # Modify by multiplication or addition (modModus)
        self.modModus = tk.StringVar()
        self.modModus.set("mul")
        # Entry field and radiobutton to specify factor to be used
        self.factorFrame = tk.Frame(self.mouseWheelFrame)
        self.modEntryTextMul = tk.StringVar()
        self.modEntryFactor = tk.Entry(self.factorFrame,
                                       textvariable=self.modEntryTextMul,
                                       width=6)
        self.modEntryFactor.pack(side=tk.LEFT)
        self.radioMultipli = tk.Radiobutton(self.factorFrame,
                                            text="Multiply",
                                            value="mul",
                                            variable=self.modModus)
        self.radioMultipli.pack(side=tk.LEFT)
        self.factorFrame.pack(fill=tk.BOTH)
        # Entry field and radiobutton to specify step (delta) to be used
        self.addFrame = tk.Frame(self.mouseWheelFrame)
        self.modEntryTextAdd = tk.StringVar()
        self.modEntryAdd = tk.Entry(self.addFrame,
                                    textvariable=self.modEntryTextAdd,
                                    width=6)
        self.modEntryAdd.pack(side=tk.LEFT)
        self.radioAdd = tk.Radiobutton(self.addFrame,
                                       text="Add",
                                       value="add",
                                       variable=self.modModus)
        self.radioAdd.pack(side=tk.LEFT)
        self.addFrame.pack(fill=tk.BOTH)
        # Set text fields for modification factor/step to default
        self.modEntryTextMul.set(
            self.modProps[self.selectedPar.get()]["modValMul"])
        self.modEntryTextAdd.set(
            self.modProps[self.selectedPar.get()]["modValAdd"])
        self.modEntryTextAdd.trace("w", self._modModeChangedAdd)
        self.modEntryTextMul.trace("w", self._modModeChangedMul)
        # Show the frame
        #     self.mouseWheelFrame.grid(row=4, column=0, columnspan=3, pady=10)
        self.mouseWheelFrame.pack()

        # React to change in modify Modus
        self.modModus.trace('w', self._modModusChanged)
        # React to a change in the active parameter
        self.selectedPar.trace("w", self._activeParameterChanged)

        dummyLabel = tk.Label(self.controlFrame)
        dummyLabel.pack()

        # Fit button and fit ranges
        self.fitRangeFrame = tk.Frame(self.controlFrame,
                                      bd=3,
                                      relief=tk.SUNKEN)
        self.fit_lo = tk.DoubleVar()
        self.fit_hi = tk.DoubleVar()
        self.fit_lo.set(min(plotter.x))
        self.fit_hi.set(max(plotter.x))
        self.fitRangeLoLim = tk.Entry(self.fitRangeFrame,
                                      textvariable=self.fit_lo,
                                      width=9,
                                      bd=2)
        self.fitRangeHiLim = tk.Entry(self.fitRangeFrame,
                                      textvariable=self.fit_hi,
                                      width=9,
                                      bd=2)
        self.fitRangeLabel = tk.Label(self.fitRangeFrame, text="Fit range:")
        self.fitButton = tk.Button(self.fitRangeFrame,
                                   text="Fit",
                                   command=self._fitClicked)
        self.fitButton.pack(side=tk.BOTTOM, fill=tk.X)
        self.fitRangeLabel.pack(side=tk.LEFT, fill=tk.X)
        self.fitRangeHiLim.pack(side=tk.RIGHT)
        self.fitRangeLoLim.pack(side=tk.RIGHT)
        self.fitRangeFrame.pack(fill=tk.X)
        #self.fitRangeLoLim.bind('<Return>', self._fitRangeChanged())
        self.fit_lo.trace("w", self._fitRangeChanged)
        self.fit_hi.trace("w", self._fitRangeChanged)
        self.numberClicked = 0
        #self.modModus.trace('w', self._modModusChanged)
        #self.modModus.trace('w', self._modModusChanged)

        dummyLabel = tk.Label(self.controlFrame)
        dummyLabel.pack()

        # , relief=tk.SUNKEN)
        self.showFrame = tk.Frame(self.controlFrame, bd=3)
        self.showFrame.pack(side=tk.TOP)

        self.parSumButton = tk.Button(self.showFrame,
                                      text="Parameter summary",
                                      command=self._parameterSummaryClicked)
        self.parSumButton.pack(side=tk.LEFT)

        self.valSetButton = tk.Button(self.showFrame,
                                      text="Value set code",
                                      command=self._valueSetClicked)
        #     self.valSetButton.grid(row=7, column=2)
        self.valSetButton.pack(side=tk.RIGHT)

        # a tk.DrawingArea
        #     self.canvas.get_tk_widget().grid(column=0, columnspan=7, row=0, rowspan=10)
        self.canvas.get_tk_widget().pack()
        self.cid = self.f.canvas.mpl_connect('button_press_event',
                                             self._mouseButtonClicked)
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.plotFrame)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        def _quit():
            # stops main loop
            self.root.quit()
            # this is necessary on Windows to prevent
            # Fatal Python Error: PyEval_RestoreThread: NULL tstate
            self.root.destroy()

        self.quitButton = tk.Button(master=self.controlFrame,
                                    text='Quit',
                                    command=_quit)
        self.quitButton.pack(side=tk.BOTTOM)

        # Plot the model for the first time
        self._parameterValueChanged()

        # Whether or not parameter summary exists
        self.root.parSumWin = None

        if platform.system() == "Darwin":
            self.root.bind("<MouseWheel>", self._onWheel)  # for OS X
root.title("matplotlib in TK")
#设置图形尺寸与质量
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3, 0.01)
s = sin(2*pi*t)
#绘制图形
a.plot(t, s)


#把绘制的图形显示到tkinter窗口上
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
#把matplotlib绘制图形的导航工具栏显示到tkinter窗口上
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

#定义并绑定键盘事件处理函数
def on_key_event(event):
    print('you pressed %s' % event.key)
    key_press_handler(event, canvas, toolbar)
canvas.mpl_connect('key_press_event', on_key_event)

#按钮单击事件处理函数
def _quit():
    #结束事件主循环,并销毁应用程序窗口
    root.quit()
    root.destroy()
button = Tk.Button(master=root, text='Quit', command=_quit)
Example #26
0
    def createWidgets(self):
        """ Creates the widgets for this application """
        " Top frame "
        self.firstF = Frame(self.mainframe, bd=2, relief=RIDGE)
        self.firstF.grid()

        " Frame for device "
        self.device1 = LabelFrame(self.mainframe, bd=2, relief=RIDGE)
        self.device1.grid(row=1, column=0)  # , columnspan = 4)

        " Chiller feedback frame"
        self.chillerFeedback_LF = LabelFrame(
            self.mainframe,
            bd=2,
            relief=RIDGE,
            text='PUMP: Temp. feedback rep.rate')
        self.chillerFeedback_LF.grid(row=2, column=0)  # , columnspan = 4)

        self.save_LF = LabelFrame(self.mainframe, bd=2, relief=RIDGE)
        self.save_LF.grid(row=4, column=0)

        " Create the variables for the application "
        self.stopLoop = IntVar()
        self.stopLoop.set(0)

        self.LastDataSaved = IntVar()
        self.LastDataSaved.set(0)

        self.devices_initialised = IntVar()
        self.devices_initialised.set(0)

        self.deviationVoltage_DG = DoubleVar()
        self.deviationVoltage_DG.set(0.05)

        # 'record wether the last temperature change was up or down'
        self.lastTemperatureChange = 'None'
        self.temperature_data = []  #  last temperature data

        " Startbutton with 'gumbo'"
        self.startB = Button(self.firstF, text='gumbo', command=self.mainLoop)
        self.startB.pack(side=LEFT)

        " Checkbox for stopping "
        self.stopLoopCB = Checkbutton(self.firstF,
                                      text='halt',
                                      variable=self.stopLoop)
        self.stopLoopCB.pack(side=LEFT, padx=10)

        self.deleteDataB = Button(self.firstF,
                                  text='delete Data',
                                  command=self.deleteData)
        self.deleteDataB.pack(side=LEFT)

        self.testB = Button(self.firstF,
                            text='re-read set temp',
                            command=self.test)
        self.testB.pack(side=LEFT)

        self.deviationVoltage_DGE = Entry(
            self.firstF,
            textvariable=self.deviationVoltage_DG,
            bg='white',
            width=11)
        self.deviationVoltage_DGE.pack(side=LEFT)

        self.ShutdownAndQuitB = Button(self.firstF,
                                       text="Quit",
                                       command=self.Quit)
        self.ShutdownAndQuitB.pack(side=RIGHT)

        self.k = 1  #  number_dataArrays = 1
        #             self.k = number_dataArrays = 1 # Don't know what it does, but
        # probably it should be one if there's only one monitoring

        self.dat = []
        for a in range(self.k):
            self.dat.append([])

        self.t = []

        self.font_label = ('Helvetica', 20, 'bold')
        self.font_entry = ('Helvetica', 30, 'bold')

        self.sleep_time_per_meas = DoubleVar()
        self.sleep_time_per_meas.set(500)

        self.limit_plot_y_axis = IntVar()
        self.limit_plot_y_axis.set(0)

        self.y1lim = DoubleVar()
        self.y1lim.set(self.piezo_voltage_min)

        self.y2lim = DoubleVar()
        self.y2lim.set(self.piezo_voltage_max)

        self.sets_to_plot = IntVar()
        self.sets_to_plot.set(500)

        self.filename = StringVar()
        self.filename.set('temp.txt')

        Label(self.device1, text="sleep time [ms]").pack(side=LEFT)
        self.sleep_time_per_measE = Entry(
            self.device1,
            textvariable=self.sleep_time_per_meas,
            bg='white',
            width=5)
        self.sleep_time_per_measE.pack(side=LEFT)

        self.stopLoopCB = Checkbutton(self.device1,
                                      text='ylims',
                                      variable=self.limit_plot_y_axis)
        self.stopLoopCB.pack(side=LEFT, padx=10)

        self.y1E = Entry(self.device1,
                         textvariable=self.y1lim,
                         bg='white',
                         width=5)
        self.y1E.pack(side=LEFT)

        self.y2E = Entry(self.device1,
                         textvariable=self.y2lim,
                         bg='white',
                         width=5)
        self.y2E.pack(side=LEFT)

        Label(self.save_LF, text="sets to plot:").pack(side=LEFT)
        self.sets_to_plotE = Entry(self.save_LF,
                                   textvariable=self.sets_to_plot,
                                   bg='white',
                                   width=5)
        self.sets_to_plotE.pack(side=LEFT)

        self.saveB = Button(self.save_LF, text="save", command=self.save)
        self.saveB.pack(side=LEFT)

        self.filenameE = Entry(self.save_LF,
                               textvariable=self.filename,
                               bg='white',
                               width=50)
        self.filenameE.pack(side=LEFT)

        ### self.chillerFeedback_LF

        self.T_set = IntVar()
        self.T_set.set(0)
        self.T_min = IntVar()
        self.T_min.set(self.tmin)
        self.T_max = IntVar()
        self.T_max.set(self.tmax)
        voltage_range = self.piezo_voltage_max - self.piezo_voltage_min
        self.Vpi_lim_low = DoubleVar()

        self.Vpi_lim_low.set(self.piezo_voltage_min + 0.2 * voltage_range)
        self.Vpi_lim_high = DoubleVar()
        self.Vpi_lim_high.set(self.piezo_voltage_max - 0.2 * voltage_range)
        self.T_delta_t = DoubleVar()
        self.T_delta_t.set(self.t_delta_t)
        self.T_feedback = IntVar()
        self.T_feedback.set(0)

        self.counter_T_feedback = 0.
        self.counter_T_feedback_reset_bool = 1

        self.T_feedbackCB = Checkbutton(self.chillerFeedback_LF,
                                        text='lock',
                                        variable=self.T_feedback)
        self.T_feedbackCB.pack(side=LEFT, padx=10)

        Label(self.chillerFeedback_LF, text="T_set").pack(side=LEFT)
        self.T_setE = Entry(self.chillerFeedback_LF,
                            textvariable=self.T_set,
                            bg='white',
                            width=5)
        self.T_setE.pack(side=LEFT)

        Label(self.chillerFeedback_LF, text="T_min").pack(side=LEFT)
        self.T_minE = Entry(self.chillerFeedback_LF,
                            textvariable=self.T_min,
                            bg='white',
                            width=5)
        self.T_minE.pack(side=LEFT)

        Label(self.chillerFeedback_LF, text="T_max").pack(side=LEFT)
        self.T_maxE = Entry(self.chillerFeedback_LF,
                            textvariable=self.T_max,
                            bg='white',
                            width=5)
        self.T_maxE.pack(side=LEFT)

        Label(self.chillerFeedback_LF, text="Vpi_lim_low").pack(side=LEFT)
        self.Vpi_lim_lowE = Entry(self.chillerFeedback_LF,
                                  textvariable=self.Vpi_lim_low,
                                  bg='white',
                                  width=5)
        self.Vpi_lim_lowE.pack(side=LEFT)

        Label(self.chillerFeedback_LF, text="Vpi_lim_high").pack(side=LEFT)
        self.Vpi_lim_highE = Entry(self.chillerFeedback_LF,
                                   textvariable=self.Vpi_lim_high,
                                   bg='white',
                                   width=5)
        self.Vpi_lim_highE.pack(side=LEFT)

        Label(self.chillerFeedback_LF, text="T_delta_t").pack(side=LEFT)
        self.T_delta_tE = Entry(self.chillerFeedback_LF,
                                textvariable=self.T_delta_t,
                                bg='white',
                                width=5)
        self.T_delta_tE.pack(side=LEFT)

        ### for matplotlib
        self.fig = plt.figure(figsize=(5, 3))
        self.canvas = FigureCanvasTkAgg(self.fig, master=root)
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, root)
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH,
                                         expand=1)  #grid(row = 0, column = 2)#

        # get the tuples indicating the different background colors, used for a warning
        self.fig.set_facecolor('red')
        self.redbackground = self.fig.get_facecolor()
        self.fig.set_facecolor('white')
        self.whitebackground = self.fig.get_facecolor()

        self.ax = plt.subplot(211)
        self.raw_data_axis = plt.subplot(212)
        self.raw_data_axis.set_ylabel('Voltage')
        self.raw_data_axis.set_xlabel('Time')
        self.raw_data_axis.set_title('Bla')
        self.raw_data_axis.hold(False)
        self.ax.set_ylabel('signal [V]')
        self.ax.set_xlabel('t [s]')
        self.ax.plot([1, 4, 2])
        self.ax2 = self.ax.twinx()
        self.canvas.draw()
Example #27
0
    def initialize(self):

        #These variables are set at the start to be used later on in the plotting. As long as they are 'in scope' and are set before you try to use them, it doesn't matter where you set them. Being in scope means being declared where you are using them. An example of being out of scope would be if you had a "main" function, and a separate "graph" function that is called inside main. If you declare a variable min_val inside the graph function, and try to use it in the main, it won't work because main can't see it.
        min_val = 0
        max_val = 1024

        #Prints a line to the terminal asking user to input the port number as 'COMx'. You can check the port number in device manager when the Arduino is plugged in
        #port = raw_input("Enter the port number (e.g. 'COM4'): \n")
        port = 'com6'
        #Creates a variable called 'ser' that we will use to communicate with the serial port. Gives it the port number, the baud rate and timeout (not sure what timeout does but it fixed that 0000s problem)
        self.ser = serial.Serial(port, 230400, timeout=1)

        #Some commented out stuff experimenting with weird data
        #ser = serial.Serial('COM4', 9600, timeout=1)
        self.ser.flush()

        #Sleep tells the programme to wait for x seconds. Useful in serial comms when you want to be sure something has happened
        time.sleep(3)
        #This is an empty array of data that will be populated later with the values from the serial port
        self.valList = []
        self.startTime = time.time()
        frame = Frame(self)
        frame.pack(side="left", fill="both", expand=True)

        plotFrame = Frame(self)
        plotFrame.pack(side="right", fill="both", expand=True)

        #Left-hand-side
        self.l1 = Label(frame, text="Heading Text").grid(row=0, columnspan=2)

        self.l2 = Label(frame, text="Name").grid(row=1, sticky=W)
        self.l3 = Label(frame, text="Clicks (C)").grid(row=3, sticky=W)
        self.l4 = Label(frame, text="Clicks (R)").grid(row=5, sticky=W)
        self.l5 = Label(frame, text="Temp").grid(row=7, sticky=W)
        self.l6 = Label(frame, text="Notes").grid(row=9, sticky=W)

        self.e1 = Entry(frame, width=30)
        self.e2 = Entry(frame, width=30)
        self.e3 = Entry(frame, width=30)
        self.e4 = Entry(frame, width=30)
        self.e5 = Text(frame, width=23, height=5)

        self.e1.grid(row=2, column=0, sticky=W)
        self.e2.grid(row=4, column=0, sticky=W)
        self.e3.grid(row=6, column=0, sticky=W)
        self.e4.grid(row=8, column=0, sticky=W)
        self.e5.grid(row=10, column=0, sticky=W)

        self.btn_text = tk.StringVar()

        button = tk.Button(frame,
                           textvariable=self.btn_text,
                           fg="green",
                           command=self.OnButtonClick)
        self.btn_text.set("Start")
        button.grid(row=11, column=0, stick=W)

        #button = tk.Button(self,text="Start",command=self.OnButtonClick).pack(side=tk.LEFT,anchor=W)
        #button = tk.Button(plotFrame,text="Start",command=self.OnButtonClick).grid(row=11, column=0)
        #Right hand side with Graph
        Label(plotFrame, text="Graph Stuff heading").pack()

        f = Figure(figsize=(6, 4), dpi=100)
        a = f.add_subplot(111)
        x = []
        y = []
        self.line1, = a.plot(x, y)
        self.canvas = FigureCanvasTkAgg(f, plotFrame)
        self.canvas.show()
        #a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
        #canvas = FigureCanvasTkAgg(f, plotFrame)
        #canvas.show()
        self.canvas._tkcanvas.pack(side=tk.TOP,
                                   fill=tk.NONE,
                                   expand=False,
                                   anchor=W)
        self.update
        toolbar = NavigationToolbar2TkAgg(self.canvas,
                                          plotFrame).pack(side=tk.TOP)
        Label(plotFrame, text="Data One").pack(anchor=W)
        Label(plotFrame, text="Data Two").pack(anchor=W)
        Label(plotFrame, text="Data Three").pack(anchor=W)
Example #28
0
def main():
    # PLOTDIAGR = show
    PLOTRAWDISP = 0
    PLOTDISPALL = 0
    SAVEFILES = 0

    if not os.path.isdir("TOMO_DISP"):
        os.makedirs("TOMO_DISP")
    db = connect()
    PER = get_config(db, "ftan_periods", plugin="Tomo")
    PER = np.array([float(pi) for pi in PER.split(',')])
    fmin = float(get_config(db, "ftan_fmin", plugin="Tomo"))
    fmax = float(get_config(db, "ftan_fmax", plugin="Tomo"))
    vgmin = float(get_config(db, "ftan_vgmin", plugin="Tomo"))
    vgmax = float(get_config(db, "ftan_vgmax", plugin="Tomo"))
    bmin = float(get_config(db, "ftan_bmin", plugin="Tomo"))
    bmax = float(get_config(db, "ftan_bmax", plugin="Tomo"))

    diagramtype = get_config(db, "ftan_diagramtype", plugin="Tomo")

    nfreq = int(get_config(db, "ftan_nfreq", plugin="Tomo"))
    ampmin = float(get_config(db, "ftan_ampmin", plugin="Tomo"))
    global data
    data = pd.DataFrame()
    # nfreq = 100
    db = connect()

    def load_dir():
        folder = askdirectory(parent=root)
        files = sorted(
            glob.glob(os.path.join(os.path.realpath(folder), "*_MEAN.*")))
        cb['values'] = files
        cb_val.set(files[0])

    def save():
        global data
        print(data.head())
        filename = cb_val.get()
        filename = filename.replace("TOMO_SAC", "TOMO_DISP").replace(
            ".sac", ".csv").replace(".SAC", ".csv")
        if not os.path.isdir(os.path.split(filename)[0]):
            os.makedirs(os.path.split(filename)[0])
        data.to_csv(filename)

    def process(e=None):
        filename = cb_val.get()
        NET1, STA1, NET2, STA2, crap = os.path.split(filename)[1].split('_')

        st = read(filename)
        dist = st[0].stats.sac.dist
        dt = st[0].stats.delta

        p = ccf.gca()
        p.cla()
        taxis = np.arange(st[0].stats.npts) * st[0].stats.delta
        vaxis = dist / taxis[1:]
        zone = np.where((vaxis >= float(_vgmin.get()))
                        & (vaxis <= float(_vgmax.get())))[0]

        p.plot(taxis, st[0].data)
        p.plot(taxis[zone], st[0].data[zone], c='r')
        ccf.subplots_adjust(bottom=0.25)
        ccfcanvas.show()

        per, disper, seeds = pickgroupdispcurv(filename, _fmin.get(),
                                               _fmax.get(), _vgmin.get(),
                                               _vgmax.get(), _bmin.get(),
                                               _bmax.get(), diagramtype, nfreq,
                                               _ampmin.get(), dist)
        basename = "%s.%s_%s.%s_%s" % (NET1, STA1, NET2, STA2, crap)
        basename = basename.replace(".SAC", "")
        for _ in [
                "write_amp.txt",
                "write_disp.txt",
                "write_FP.txt",
                "write_ph.txt",
                "write_TV.txt",
        ]:
            shutil.move(_, _.replace("write", basename))

        U = np.loadtxt('%s_TV.txt' % basename)
        P = np.loadtxt('%s_FP.txt' % basename)
        xmin = min(P)
        xmax = max(P)
        ymin = min(U)
        ymax = max(U)
        amp = np.loadtxt('%s_amp.txt' % basename).T
        iu = np.where((disper >= ymin) & (disper <= ymax))
        per = per[iu]
        disper = disper[iu]
        Per, Vitg = np.meshgrid(P, U)
        f.clf()
        p = f.gca()
        p.cla()
        if int(_normed.get()):
            for i in range(amp.shape[1]):
                amp[:, i] /= amp[:, i].max()

        c = p.contourf(Per, Vitg, amp, 35, cmap=cm_val.get())
        f.colorbar(c)

        idxx = np.where(float(_minWL.get()) * per * disper < dist)[0]
        p.plot(per, disper, '-ok', lw=1.5)
        p.scatter(per[idxx],
                  disper[idxx],
                  marker='o',
                  s=100,
                  c="green",
                  lw=1.5)
        p.scatter(seeds[:, 0],
                  seeds[:, 1],
                  s=10,
                  marker='d',
                  facecolor='w',
                  edgecolor="k")
        global data
        data = pd.DataFrame(disper[idxx],
                            index=per[idxx],
                            columns=["Velocity"])
        data.index.name = "Period"

        # TODO add axes labels depending on diagramtype
        p.set_xlabel("Period (s)", fontsize=12)
        p.set_ylabel('Velocity (km/s)', fontsize=12)
        p.set_xlim(xmin, xmax)
        p.set_ylim(ymin, ymax)
        p.set_title("%s.%s - %s.%s (%.2f km)" % (NET1, STA1, NET2, STA2, dist))
        canvas.show()

    def previous_file(e=None):
        idx = cb['values'].index(cb.get())
        if idx > 0:
            idx -= 1
        cb.set(cb['values'][idx])
        process()

    def next_file(e=None):
        idx = cb['values'].index(cb.get())
        if idx < len(cb['values']):
            idx += 1
        cb.set(cb['values'][idx])
        process()

    #root
    root = Tk()
    root.title("MSNoise-TOMO: Time-Frequency & Dispersion Curve Picking Tool")
    # root.resizable(True, True)
    # menubar = Menu(root)
    # filemenu = Menu(menubar, tearoff=0)
    # filemenu.add_command(label="Open", command=openfile)
    # filemenu.add_separator()
    # filemenu.add_command(label="Exit", command=root.quit)
    # menubar.add_cascade(label="File", menu=filemenu)

    # root.config(menu=menubar)

    #mainframe
    gui_style = ttk.Style()
    gui_style.configure('My.TLabel', background='#ffffff')
    gui_style.configure('My.TButton', background='#ff0011')
    gui_style.configure('M2.TButton', background='#B7E2F0')
    gui_style.configure('My.TFrame', background='#ffffff')

    mainframe = ttk.Frame(root, padding="3 3 12 12", style='My.TFrame')
    mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
    mainframe.columnconfigure(0, weight=1)
    mainframe.rowconfigure(0, weight=1)

    _folder = StringVar(root, value=os.path.join(os.getcwd(), "TOMO_SAC"))
    ttk.Button(mainframe,
               text="Select Folder",
               command=load_dir,
               style='M2.TButton').grid(column=1, row=1, sticky=W)

    cb_val = StringVar()
    files = sorted(
        glob.glob(os.path.join(os.path.realpath(_folder.get()), "*_MEAN.*")))
    cb = ttk.Combobox(mainframe, width=55, textvariable=cb_val, height=4)
    cb.grid(column=2, row=1, sticky=(W, E), columnspan=2)
    if len(files):
        cb['values'] = files
        cb_val.set(files[0])
    else:
        cb_val.set("<-- SELECT A FOLDER BY CLICKING ON THE BUTTON")
    # PARAMS PANEL
    # myFont = Font(family="Helvetica", size=12)

    _vgmin = StringVar(root, value=vgmin)
    vgminSize = ttk.Entry(mainframe, width=7, textvariable=_vgmin)
    vgminSize.grid(column=2, row=2, sticky=(W, E))
    tmp = ttk.Label(mainframe, text="Vg Min ",
                    style='My.TLabel').grid(column=1, row=2, sticky=W)

    _vgmax = StringVar(root, value=vgmax)
    vgmaxSize = ttk.Entry(mainframe, width=7, textvariable=_vgmax)
    vgmaxSize.grid(column=2, row=3, sticky=(W, E))
    ttk.Label(mainframe, text="Vg Max ", style='My.TLabel').grid(column=1,
                                                                 row=3,
                                                                 sticky=W)

    _minSNR = StringVar(root, value=0.0)
    minSNRSize = ttk.Entry(mainframe, width=7, textvariable=_minSNR)
    minSNRSize.grid(column=2, row=4, sticky=(W, E))
    ttk.Label(mainframe, text="Min SNR ", style='My.TLabel').grid(column=1,
                                                                  row=4,
                                                                  sticky=W)

    _minWL = StringVar(root, value=1.0)
    minWLSize = ttk.Entry(mainframe, width=7, textvariable=_minWL)
    minWLSize.grid(column=2, row=5, sticky=(W, E))
    ttk.Label(mainframe, text="Min Wavelength ",
              style='My.TLabel').grid(column=1, row=5, sticky=W)

    _fmin = StringVar(root, value=fmin)
    fminSize = ttk.Entry(mainframe, width=7, textvariable=_fmin)
    fminSize.grid(column=2, row=6, sticky=(W, E))
    ttk.Label(mainframe, text="Min Frequency ",
              style='My.TLabel').grid(column=1, row=6, sticky=W)

    _fmax = StringVar(root, value=fmax)
    fmaxSize = ttk.Entry(mainframe, width=7, textvariable=_fmax)
    fmaxSize.grid(column=2, row=7, sticky=(W, E))
    ttk.Label(mainframe, text="Max Frequency ",
              style='My.TLabel').grid(column=1, row=7, sticky=W)

    _diagType = StringVar(root, value="PV")
    diagTypeSize = ttk.Entry(mainframe, width=7, textvariable=_diagType)
    diagTypeSize.grid(column=2, row=8, sticky=(W, E))
    ttk.Label(mainframe, text="Diagram (...) ",
              style='My.TLabel').grid(column=1, row=8, sticky=W)

    _bmin = StringVar(root, value=bmin)
    bminSize = ttk.Entry(mainframe, width=7, textvariable=_bmin)
    bminSize.grid(column=2, row=9, sticky=(W, E))
    ttk.Label(mainframe, text="Bmin ", style='My.TLabel').grid(column=1,
                                                               row=9,
                                                               sticky=W)

    _bmax = StringVar(root, value=bmax)
    bminSize = ttk.Entry(mainframe, width=7, textvariable=_bmax)
    bminSize.grid(column=2, row=10, sticky=(W, E))
    ttk.Label(mainframe, text="Bmax ", style='My.TLabel').grid(column=1,
                                                               row=10,
                                                               sticky=W)

    _ampmin = StringVar(root, value=ampmin)
    ampminSize = ttk.Entry(mainframe, width=7, textvariable=_ampmin)
    ampminSize.grid(column=2, row=11, sticky=(W, E))
    ttk.Label(mainframe, text="Amp Min ", style='My.TLabel').grid(column=1,
                                                                  row=11,
                                                                  sticky=W)

    maps = sorted(m for m in plt.cm.datad)
    cm_val = StringVar()
    cm = ttk.Combobox(mainframe, width=7, textvariable=cm_val, height=4)
    cm.grid(column=2, row=12, sticky=(W, E))
    ttk.Label(mainframe, text="Cmap ", style='My.TLabel').grid(column=1,
                                                               row=12,
                                                               sticky=W)
    cm['values'] = maps
    cm_val.set("hot_r")

    ccf = Figure(figsize=(5, 1), dpi=100)
    ccfcanvas = FigureCanvasTkAgg(ccf, master=mainframe)
    ccfcanvas.get_tk_widget().grid(row=2, column=3, rowspan=2)

    f = Figure(dpi=100)
    canvas = FigureCanvasTkAgg(f, master=mainframe)
    canvas.get_tk_widget().grid(row=4, column=3, rowspan=9)

    _normed = IntVar()
    chh = ttk.Checkbutton(mainframe, text="Normed", variable=_normed, \
                     onvalue=1, offvalue=0).grid(column=1, row=13, sticky=W)

    ttk.Button(mainframe, text="Compute", command=process,
               style='My.TButton').grid(column=2, row=13, sticky=W)

    ttk.Button(mainframe, text="Save", command=save,
               style='My.TButton').grid(column=2, row=14, sticky=W)

    toolbar = NavigationToolbar2TkAgg(canvas, mainframe)
    toolbar.update()
    toolbar.grid(column=3, row=14, columnspan=1, sticky=W)

    # canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=0)

    def onclick(event):
        print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
              (event.button, event.x, event.y, event.xdata, event.ydata))

    cid = f.canvas.mpl_connect('button_press_event', onclick)

    for child in mainframe.winfo_children():
        child.grid_configure(padx=0.5, pady=0.5)

    root.bind('<Return>', process)
    root.bind('<KP_Enter>', process)
    root.bind('<Control-Key-Left>', previous_file)
    root.bind('<Control-Key-Right>', next_file)
    icon = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'img',
                        'msnoise.gif')
    img = PhotoImage(file=icon)

    root.tk.call('wm', 'iconphoto', root._w, img)
    # print(os.path.isfile(icon))
    # root.iconbitmap(icon)

    root.mainloop()
Example #29
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.configure(bg=PADDING_COLOR,
                       highlightcolor=PADDING_COLOR,
                       highlightbackground=PADDING_COLOR)

        self.canvas = FigureCanvasTkAgg(f, self)
        self.canvas.get_tk_widget().grid(row=0,
                                         column=0,
                                         sticky='nsew',
                                         padx=5,
                                         pady=4,
                                         ipadx=0,
                                         ipady=0)
        self.canvas.get_tk_widget().configure(
            bg=BACKGROUND_COLOR,
            highlightcolor=PADDING_COLOR,
            highlightbackground=PADDING_COLOR,
            relief=tk.SUNKEN,
            bd=1)

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        frame2 = tk.Frame(self)
        frame2.grid(row=1, column=0, columnspan=1, sticky='WE', padx=7, pady=5)
        frame2.configure(bg=BACKGROUND_COLOR,
                         highlightcolor=BACKGROUND_COLOR,
                         highlightbackground=BACKGROUND_COLOR,
                         relief=tk.SUNKEN,
                         bd=1)
        # frame2.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1)

        frame3 = tk.Frame(self)
        frame3.grid(row=0, column=2, rowspan=2, sticky='NS', padx=3, pady=4)
        frame3.configure(bg=PADDING_COLOR,
                         highlightcolor=PADDING_COLOR,
                         highlightbackground=PADDING_COLOR)

        buttonsFrame = tk.Frame(self, relief=tk.SUNKEN, bd=1)
        buttonsFrame.configure(bg=BACKGROUND_COLOR,
                               highlightcolor=BACKGROUND_COLOR,
                               highlightbackground=BACKGROUND_COLOR)
        buttonsFrame.grid(row=0,
                          column=1,
                          rowspan=2,
                          sticky='NS',
                          pady=5.2,
                          padx=2)
        button1 = ttk.Button(buttonsFrame,
                             text="Force Release",
                             cursor='hand2',
                             command=lambda: SendPacket('r'))
        button1.grid(row=0, column=0, padx=2, pady=2, sticky='nsew')
        button2 = ttk.Button(buttonsFrame,
                             text="Capture",
                             cursor='hand2',
                             command=lambda: SendPacket('c'))
        button2.grid(row=0, column=1, padx=0, pady=2, sticky='nsew')
        button3 = ttk.Button(buttonsFrame,
                             text="Picture",
                             cursor='hand2',
                             command=lambda: controller.show_frame(StartPage))
        button3.grid(row=1, column=0, padx=2, pady=0, sticky='nsew')
        button4 = ttk.Button(
            buttonsFrame,
            text="Send State",
            cursor='hand2',
            command=lambda: SendPacket(self.sendentry.get() + '\n'))
        button4.grid(row=1, column=1, padx=0, pady=0, sticky='nsew')

        sendlabel = tk.Label(buttonsFrame, text="Send State", font=SMALL_FONT)
        sendlabel.grid(row=2,
                       column=0,
                       columnspan=2,
                       sticky='NS',
                       padx=5,
                       pady=5)
        sendlabel.configure(bg=BACKGROUND_COLOR,
                            fg=TEXT_COLOR,
                            highlightcolor=BACKGROUND_COLOR,
                            highlightbackground=BACKGROUND_COLOR)
        self.sendentry = ttk.Entry(buttonsFrame, width=7)
        self.sendentry.grid(row=3,
                            column=0,
                            columnspan=2,
                            sticky='NS',
                            padx=5,
                            pady=5)

        rangelabel = tk.Label(buttonsFrame, text="Plot Range", font=SMALL_FONT)
        rangelabel.grid(row=4,
                        column=0,
                        columnspan=2,
                        sticky='NS',
                        padx=5,
                        pady=5)
        rangelabel.configure(bg=BACKGROUND_COLOR,
                             fg=TEXT_COLOR,
                             highlightcolor=BACKGROUND_COLOR,
                             highlightbackground=BACKGROUND_COLOR)
        self.rangeentry1 = ttk.Entry(buttonsFrame, width=5)
        self.rangeentry1.grid(row=5,
                              column=0,
                              columnspan=2,
                              sticky='NS',
                              padx=5,
                              pady=5)
        rangebutton = ttk.Button(buttonsFrame,
                                 text="Update Range",
                                 cursor='hand2',
                                 command=self.GetSetPlotRange)
        rangebutton.grid(row=6,
                         column=0,
                         columnspan=2,
                         sticky='NS',
                         padx=5,
                         pady=5)
        # --------------------------------------------------------------------------------------------------------------

        mfFrame = tk.Frame(buttonsFrame)
        mfFrame.grid(row=7,
                     column=0,
                     columnspan=2,
                     sticky='nsew',
                     padx=5,
                     pady=5)
        mfFrame.configure(bg=BACKGROUND_COLOR,
                          highlightcolor=BACKGROUND_COLOR,
                          highlightbackground=BACKGROUND_COLOR)
        mfscrollbar = ttk.Scrollbar(mfFrame)
        mfscrollbar.grid(row=0, column=2, sticky='NS')
        self.marklistbox = tk.Listbox(mfFrame,
                                      selectmode=tk.SINGLE,
                                      yscrollcommand=mfscrollbar.set)
        self.marklistbox.grid(row=0, column=0, columnspan=2, sticky='nsew')
        mfscrollbar.config(command=self.marklistbox.yview)
        markerlist = [
            'point', 'pixel', 'circle', 'triangledown', 'triangleup',
            'triangleleft', 'triangleright', 'octagon', 'square', 'pentagon',
            'star', 'hexagon1', 'hexagon2', 'plus', 'X', 'diamond',
            'thindiamond', 'vline', 'hline', 'None'
        ]
        for marker in markerlist:
            self.marklistbox.insert(tk.END, marker)
        mkbutton = ttk.Button(mfFrame,
                              text='Set Marker',
                              cursor='hand2',
                              command=lambda: self.GetSetMarkerSymbol())
        mkbutton.grid(row=1,
                      column=1,
                      columnspan=1,
                      sticky='NS',
                      padx=5,
                      pady=5)
        self.mksize = tk.Entry(mfFrame, width=5)
        self.mksize.grid(row=1, column=0, padx=5, pady=5)

        toolbar = NavigationToolbar2TkAgg(self.canvas, frame2)
        toolbar.update()
        toolbar.configure(bg=BACKGROUND_COLOR,
                          highlightcolor=BACKGROUND_COLOR,
                          highlightbackground=BACKGROUND_COLOR,
                          padx=1)
 def _pack_navigation(self, canvas, frame):
     toolbar = NavigationToolbar2TkAgg(canvas, frame)
     toolbar.update()
     canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)