Ejemplo n.º 1
0
def main():
    x = np.array([5.0, 0.0, math.pi / 2, 0.0, 0.0])

    goal = np.array([5.0, 10.0])

    robot_prop = RobotProp()
    global mapx, mapy, framex, framey, obs
    mapx = [-1, 11]
    mapy = [-1, 11]
    framex = 200
    framey = 200
    obs = np.mat([[5.0, 5.0], [4.0, 4.0]])

    obs_r = 0.5
    robot_r = 0.1
    sum_r = obs_r + robot_r

    history_x = np.array(x)

    # 创建窗口
    global root
    root = tk.Tk()
    matplotlib.use('TkAgg')
    root.title("DWA 测试")

    # 创建图形
    f = plt.figure(1, figsize=(4, 4), dpi=100)
    a = f.add_subplot(111)

    # 把绘制的图形显示到tkinter窗口上
    canvas = FigureCanvasTkAgg(f, master=root)
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

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

    # 按钮
    button = tk.Button(master=root, text='Quit', command=_quit)
    button.pack(side=tk.BOTTOM)

    frame = tk.Frame(root, width=framex, height=framey, bg='green')
    frame.bind(sequence="<Button-1>", func=callback)
    frame.pack(side=tk.BOTTOM)

    for i in range(5000):
        # DWA参数输入 返回控制量 u = [v(m/s),w(rad/s)] 和 轨迹
        u, trajectory = dwa_control(x, goal, obs, sum_r, robot_prop)

        # 机器人移动到下一个时刻的状态量 根据当前速度和角速度推导 下一刻的位置和角度
        x = motion(x, u, robot_prop)

        # 历史轨迹的保存
        history_x = np.vstack((history_x, x))

        if show_animation:
            draw_dynamic_search(a, root, canvas, trajectory, x, goal, obs,
                                obs_r, robot_r, mapx, mapy)

        # 是否到达目的地
        if math.sqrt((x[0] - goal[0])**2 + (x[1] - goal[1])**2) <= 0.5:
            print('Arrive Goal!!!')
            break

    print("Done")
    plt.cla()
    plt.close()
    draw_path(history_x, goal, obs, x, obs_r, robot_r)
Ejemplo n.º 2
0
    axs = fig.subplots(2, 2)
    stacked_column(example_data, ax=axs[0,0], ylabel=abs_ylabel, title=abs_title,
                   xticks=times, tags=tags, width=width)
    stacked_column(example_data, ax=axs[0,1], ylabel=rel_ylabel,
                   title=rel_title, xticks=times, tags=tags,
                   relative=True, width=width)
    cum_data = cumulative_line(example_data, ax=axs[1,0], ylabel=abs_ylabel,
                               title=cum_title, xticks=times, tags=tags)[-1]
    pie(cum_data, ax=axs[1,1], labels=tags, title=prop_title)


    canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
    canvas.draw()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    toolbar = NavigationToolbar2Tk(canvas, root)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)


    def on_key_press(event):
        print("you pressed {}".format(event.key))
        key_press_handler(event, canvas, toolbar)


    canvas.mpl_connect("key_press_event", on_key_press)


    def _quit():
        root.quit()     # stops mainloop
        root.destroy()  # this is necessary on Windows to prevent
Ejemplo n.º 3
0
def windowInit():

    fen = Tk()

    version = 2.0
    fen.title("Plot (V" + str(version) + ")")

    #set the window on full screen on opening
    #https://stackoverflow.com/questions/7966119/display-fullscreen-mode-on-tkinter
    class FullScreenApp(object):
        def __init__(self, master, **kwargs):
            self.master = master
            pad = 3
            self._geom = '200x200+0+0'
            master.geometry("{0}x{1}+0+0".format(
                master.winfo_screenwidth() - pad,
                master.winfo_screenheight() - pad))
            master.bind('<Escape>', self.toggle_geom)

        def toggle_geom(self, event):
            geom = self.master.winfo_geometry()
            print(geom, self._geom)
            self.master.geometry(self._geom)
            self._geom = geom

    app = FullScreenApp(fen)

    #some colors definition
    myColor1 = '#78f8ff'
    myColor2 = '#78cbff'
    myColor3 = '#75a1ff'
    myColor4 = '#7575ff'
    myColor5 = '#445CFF'

    #definition of the widgets
    frame0 = Frame(fen)
    frame0.pack()

    title = Label(frame0, text="Plot")
    title.configure(font=('Courrier', 30), bg=myColor1)
    title.pack(side=TOP, fill=X)

    greatbarre1 = Label(
        frame0,
        text=
        "                                                                                                                                                                                                                                                                                                                                                 "
    )
    greatbarre1.configure(bg=myColor2, font=('Courrier', 20))
    greatbarre1.pack(side=TOP, fill=X)

    greatbarre2 = Label(frame0, text="")
    greatbarre2.configure(bg=myColor3, font=('Courrier', 10))
    greatbarre2.pack(side=TOP, fill=X)

    greatbarre3 = Label(frame0, text="")
    greatbarre3.configure(bg=myColor4, font=('Courrier', 5))
    greatbarre3.pack(side=TOP, fill=X)

    greatbarre4 = Label(frame0, text="")
    greatbarre4.configure(bg=myColor5, font=('Courrier', 2))
    greatbarre4.pack(side=TOP, fill=X)

    frame1 = Frame(fen, bg="white")
    frame1.pack(side=LEFT, fill=BOTH, expand=1)

    frame1.grid_columnconfigure(0, weight=1)
    frame1.grid_columnconfigure(1, weight=1)

    frame1.grid_rowconfigure(0, pad=0)
    frame1.grid_rowconfigure(1, pad=0)
    frame1.grid_rowconfigure(2, pad=0)
    frame1.grid_rowconfigure(3, pad=0)
    frame1.grid_rowconfigure(4, pad=0)
    frame1.grid_rowconfigure(5, pad=0)
    frame1.grid_rowconfigure(6, pad=0)
    frame1.grid_rowconfigure(7, pad=0)
    frame1.grid_rowconfigure(8, pad=20)
    frame1.grid_rowconfigure(9, pad=0)
    frame1.grid_rowconfigure(10, pad=0)
    frame1.grid_rowconfigure(11, pad=0)
    frame1.grid_rowconfigure(12, pad=0)
    frame1.grid_rowconfigure(13, pad=20)
    frame1.grid_rowconfigure(14, pad=0)
    frame1.grid_rowconfigure(15, pad=0)
    frame1.grid_rowconfigure(16, pad=0)
    frame1.grid_rowconfigure(17, pad=0)
    frame1.grid_rowconfigure(18, pad=20)
    frame1.grid_rowconfigure(19, pad=0)
    frame1.grid_rowconfigure(20, pad=0)
    frame1.grid_rowconfigure(21, pad=0)
    frame1.grid_rowconfigure(22, pad=0)
    frame1.grid_rowconfigure(23, pad=0)
    frame1.grid_rowconfigure(24, pad=0)
    frame1.grid_rowconfigure(25, pad=0)
    frame1.grid_rowconfigure(26, pad=0)
    frame1.grid_rowconfigure(27, pad=0)

    funConsigne = Label(frame1, text="Écrivez ici les données à afficher : ")
    funConsigne.configure(font=('Courrier', 15), bg=myColor1)
    funConsigne.grid(row=0, column=0, columnspan=2, sticky=EW)

    moreConsigne1 = Label(
        frame1,
        text="Les deux vecteurs doivent être de la même taille.",
        font="Courrier 10 italic",
        bg="white")
    moreConsigne1.grid(row=1, column=0, columnspan=2, sticky=W)

    moreConsigne2 = Label(
        frame1,
        text="Le vecteur des abscisses doit être dans l'ordre croissant.",
        font="Courrier 10 italic",
        bg="white")
    moreConsigne2.grid(row=2, column=0, columnspan=2, sticky=W)

    exemple = Label(frame1,
                    text="EXEMPLE : 0.5;2.0;1.97;3.03",
                    font="Courrier 10 bold",
                    bg="white")
    exemple.grid(row=3, column=0, columnspan=2, sticky=W)

    abslabel = Label(frame1, text="Abscisses : ")
    abslabel.configure(font=('Courrier', 15), bg="white")
    abslabel.grid(row=4, column=0, columnspan=1, sticky=W)

    absexpr = Entry(frame1)
    absexpr.grid(row=4, column=1, columnspan=1, sticky=EW)

    ordlabel = Label(frame1, text="Ordonnées : ")
    ordlabel.configure(font=('Courrier', 15), bg="white")
    ordlabel.grid(row=5, column=0, columnspan=1, sticky=W)

    ordexpr = Entry(frame1)
    ordexpr.grid(row=5, column=1, columnspan=1, sticky=EW)

    error1 = Label(
        frame1,
        text=
        "Il semblerait que vous ayez entré un caractère non pris en charge.",
        font="Courrier 9 bold italic",
        bg="white",
        fg="white")
    error1.grid(row=6, column=0, columnspan=2, sticky=W)

    error2 = Label(
        frame1,
        text="Seuls les chiffres, les '.' et les ';' sont autorisés",
        font="Courrier 9 bold italic",
        bg="white",
        fg="white")
    error2.grid(row=7, column=0, columnspan=2, sticky=W)

    evalconsigne = Label(frame1,
                         text="Ou écrivez ici une fonction de x :",
                         font="Courrier 15",
                         bg=myColor2)
    evalconsigne.grid(row=8, column=0, columnspan=2, sticky=EW)

    evallabel = Label(frame1, text="f(x) = ", font="courrier 15", bg="white")
    evallabel.grid(row=9, column=0, columnspan=1, sticky=W)

    evalexpr = Entry(frame1)
    evalexpr.grid(row=9, column=1, columnspan=1, sticky=EW)

    tuto1 = Label(
        frame1,
        text="Mutliplication : ()*() ; Division : ()/() ; Puissance : ()**()",
        font="courrier 10",
        bg="white")
    tuto1.grid(row=10, column=0, columnspan=2, sticky=W)

    tuto2 = Label(
        frame1,
        text=
        "Les fonctions trigonométriques, exp(), log(), sqrt() et abs() sont également autorisées",
        font="courrier 10",
        bg="white")
    tuto2.grid(row=11, column=0, columnspan=2, sticky=W)

    error5 = Label(frame1,
                   text="erreur5",
                   font="courrier 9 bold italic",
                   fg="white",
                   bg="white")
    error5.grid(row=12, column=0, columnspan=2, sticky=W)

    absconsigne = Label(frame1,
                        text="Entrez les abscisses minimale et maximale : ")
    absconsigne.configure(font=('Courrier', 15), bg=myColor3)
    absconsigne.grid(row=13, column=0, columnspan=2, sticky=EW)

    absminlabel = Label(frame1, text="Abscisse minimale : ")
    absminlabel.configure(font=('Courrier', 15), bg="white")
    absminlabel.grid(row=14, column=0, columnspan=1, sticky=W)

    absminexpr = Entry(frame1)
    absminexpr.grid(row=14, column=1, columnspan=1, sticky=EW)

    absmaxlabel = Label(frame1, text="Abscisse maximale : ")
    absmaxlabel.configure(font=('Courrier', 15), bg="white")
    absmaxlabel.grid(row=15, column=0, columnspan=1, sticky=W)

    absmaxexpr = Entry(frame1)
    absmaxexpr.grid(row=15, column=1, columnspan=1, sticky=EW)

    error3 = Label(frame1,
                   text="Remplissez ces champs afin de pouvoir continuer",
                   font="courrier 9 bold italic",
                   fg="white",
                   bg="white")
    error3.grid(row=16, column=0, columnspan=2, sticky=W)

    error4 = Label(
        frame1,
        text="Il semblerait qu'il y ait une erreur dans vos abscisses",
        font="courrier 9 bold italic",
        fg="white",
        bg="white")
    error4.grid(row=17, column=0, columnspan=2, sticky=W)

    optconsigne = Label(frame1, text="Options supplémentaires : ")
    optconsigne.configure(font=('Courrier', 15), bg=myColor4)
    optconsigne.grid(row=18, column=0, columnspan=2, sticky=EW)

    titlelabel = Label(frame1, text=("Titre : "))
    titlelabel.configure(font=('Courrier', 15), bg="white")
    titlelabel.grid(row=19, column=0, columnspan=1, sticky=W)

    titleexpr = Entry(frame1)
    titleexpr.grid(row=19, column=1, columnspan=1, sticky=EW)

    xlabel = Label(frame1, text=("Nom de l'axe x : "))
    xlabel.configure(font=('Courrier', 15), bg="white")
    xlabel.grid(row=20, column=0, columnspan=1, sticky=W)

    xlabelexpr = Entry(frame1)
    xlabelexpr.grid(row=20, column=1, columnspan=1, sticky=EW)

    ylabel = Label(frame1, text=("Nom de l'axe y : "))
    ylabel.configure(font=('Courrier', 15), bg="white")
    ylabel.grid(row=21, column=0, columnspan=1, sticky=W)

    ylabelexpr = Entry(frame1)
    ylabelexpr.grid(row=21, column=1, columnspan=1, sticky=EW)

    approxlabel = Label(frame1,
                        text="Approximation (degré) : ",
                        font="Courrier 15",
                        fg="black",
                        bg="white")
    approxlabel.grid(row=22, column=0, columnspan=2, sticky=W)

    approxvariable = StringVar(frame1)
    approxvariable.set("/")
    approxmenu = OptionMenu(frame1, approxvariable, "/", "0", "1", "2", "3",
                            "4", "5")
    approxmenu.config(font=('courrier', (10)), bg='white', relief=FLAT)
    approxmenu.grid(row=22, column=1, columnspan=1, sticky=EW)

    interplabel = Label(frame1,
                        text="Interpolation : ",
                        font="Courrier 15",
                        fg="black",
                        bg="white")
    interplabel.grid(row=23, column=0, columnspan=1, sticky=W)

    interpvariable = StringVar(frame1)
    interpvariable.set("aucune")
    interpmenu = OptionMenu(frame1, interpvariable, "aucune", "linéaire",
                            "splines cubiques", "degré n")
    interpmenu.config(font=('courrier', (10)), bg='white', relief=FLAT)
    interpmenu.grid(row=23, column=1, columnspan=1, sticky=EW)

    var = IntVar()
    gridcheckbutton = Checkbutton(frame1,
                                  text="Afficher la grille",
                                  highlightthickness=0,
                                  bd=0,
                                  variable=var)

    gridcheckbutton.configure(font=('Courrier', 15), bg="white")
    gridcheckbutton.grid(row=24, column=0, columnspan=2, sticky=EW)

    frame2 = Frame(fen, bg="white")
    frame2.pack(fill=BOTH, expand=1)

    fig = Figure(figsize=(15, 8))
    a = fig.add_subplot(111)

    #adding of the plot on the window
    canvas = FigureCanvasTkAgg(fig, frame2)
    canvas.draw()
    canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

    #adding of the toolbar beneath the plot
    toolbar = NavigationToolbar2Tk(canvas, frame2)
    toolbar.update()
    canvas._tkcanvas.pack(side=TOP)

    ############################## user's vector expression translation to numpy array ##############################
    def vector(string):
        error1.configure(fg="white")
        error2.configure(fg="white")
        count = 0
        for i in range(0, len(string)):
            if (string[i] != ';') and (string[i].isdigit() == False) and (
                    string[i] != '.') and (string[i] != '-'):
                error1.configure(fg="red")
                error2.configure(fg="red")
            if (string[i] == ';'):
                count = count + 1
        x = np.zeros(count + 1)
        current = 0
        startindex = 0
        count2 = 0
        for i in range(0, len(string)):
            if (string[i] == ';'):
                x[current] = float(string[startindex:i])
                current = current + 1
                startindex = i + 1
                count2 = count2 + 1
                if count2 == count:
                    x[current] = float(string[i + 1:])
        return x

############################## get to know if the vector is sorted ##############################

    def isSorted(x):
        return np.all(x[:-1] < x[1:])

############################## plotting function ##############################

    def plotting():
        a.clear()
        canvas.draw()
        if (absexpr.get() != "") and (ordexpr.get() != ""):
            x = vector(absexpr.get())
            y = vector(ordexpr.get())
            if len(x) != len(y) or isSorted(x) == False:
                if len(x) != len(y):
                    moreConsigne1.configure(font="Courrier 10 italic bold",
                                            fg="red")
                if isSorted(x) == False:
                    moreConsigne2.configure(font="Courrier 10 italic bold",
                                            fg="red")
            if len(x) == len(y) or isSorted(x) == True:
                if len(x) == len(y):
                    moreConsigne1.configure(font="Courrier 10 italic",
                                            fg="black")
                if isSorted(x) == True:
                    moreConsigne2.configure(font="Courrier 10 italic",
                                            fg="black")
            if len(x) == len(y) and isSorted(x) == True:
                moreConsigne1.configure(font="Courrier 10 italic", fg="black")
                moreConsigne2.configure(font="Courrier 10 italic", fg="black")
                error1.configure(fg="white")
                error2.configure(fg="white")
                a.plot(x, y, 'or')
                a.set_title(titleexpr.get())
                a.set_ylabel(ylabelexpr.get())
                a.set_xlabel(xlabelexpr.get())
                if (absminexpr.get() != "") and (absmaxexpr.get() != ""):
                    if (float(absminexpr.get()) >= float(absmaxexpr.get())):
                        error4.configure(fg="red")
                    else:
                        error4.configure(fg="white")
                        a.set_xlim(
                            [float(absminexpr.get()),
                             float(absmaxexpr.get())])
                if var.get() == 1:
                    a.grid()
                elif var.get() == 0:
                    a.grid(False)
                canvas.draw()
                if (approxvariable.get() != "/"):
                    deg = int(approxvariable.get())
                    xabs = np.linspace(x[0], x[-1], 1000)
                    z = np.polyfit(x, y, deg)
                    a.plot(xabs, np.polyval(z, xabs), 'b--')
                    canvas.draw()
                if (interpvariable.get() != "aucune"):
                    if (interpvariable.get() == "linéaire"):
                        a.plot(x, y, 'b--')
                        canvas.draw()
                    if (interpvariable.get() == "splines cubiques"):
                        xabs = np.linspace(x[0], x[-1], 1000)
                        u = spline(x, y)(xabs)
                        a.plot(xabs, u, 'b--')
                        canvas.draw()
                    if (interpvariable.get() == "degré n"):
                        xabs = np.linspace(x[0], x[-1], 1000)
                        u = np.polyfit(x, y, len(x) - 1)
                        a.plot(xabs, np.polyval(u, xabs), '--b')
                        canvas.draw()
        if (evalexpr.get() != ""):
            if (absminexpr.get == "") or (absmaxexpr.get() == ""):
                error3.configure(fg="red")
            elif (float(absmaxexpr.get()) <= float(absminexpr.get())):
                error3.configure(fg="white")
                error4.configure(fg="red")
            else:
                error3.configure(fg="white")
                error4.configure(fg="white")
                i = (int(
                    (float(absmaxexpr.get()) - float(absminexpr.get())) / 1000)
                     + 1) * 1000
                x = np.linspace(float(absminexpr.get()),
                                float(absmaxexpr.get()), i)
                #dictionnary
                fun_dict = {
                    'sin': np.sin,
                    'cos': np.cos,
                    'exp': np.exp,
                    'arccos': np.arccos,
                    'tan': np.tan,
                    'arcsin': np.arcsin,
                    'arctan': np.arctan,
                    'sinh': np.sinh,
                    'cosh': np.cosh,
                    'tanh': np.tanh,
                    'log': np.log,
                    'tan': np.tan,
                    'sqrt': np.sqrt,
                    'abs': np.abs,
                    'x': x
                }
                try:
                    error5.config(fg="white")
                    y = eval(evalexpr.get(), fun_dict)
                    a.plot(x, y)
                    a.set_title(titleexpr.get())
                    a.set_ylabel(ylabelexpr.get())
                    a.set_xlabel(xlabelexpr.get())
                    if var.get() == 1:
                        a.grid()
                    elif var.get() == 0:
                        a.grid(False)
                    canvas.draw()
                except (NameError, SyntaxError, ValueError):
                    error5.config(
                        text=
                        "Il semblerait que votre expression comporte une erreur. Réessayez svp.",
                        fg="red")

######################### menu déroulant (de boutons) des différents graphes ########################
#https://stackoverflow.com/questions/7966119/display-fullscreen-mode-on-tkinter
#https://stackoverflow.com/questions/39447138/how-can-i-identify-buttons-created-in-a-loop
#https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index
#https://stackoverflow.com/questions/31762698/dynamic-button-with-scrollbar-in-tkinter-python
#https://stackoverflow.com/questions/45728548/how-can-i-get-the-button-id-when-it-is-clicked
#https://stackoverflow.com/questions/50787864/how-do-i-make-a-tkinter-button-in-an-list-of-buttons-return-its-index
#https://stackoverflow.com/questions/15009117/how-to-have-image-text-in-one-button-in-tkinter
#https://stackoverflow.com/questions/35282482/tkinter-button-changes-color-after-having-hovered-on-it
#https://stackoverflow.com/questions/2744795/background-color-for-tk-in-python
#https://stackoverflow.com/questions/51889265/how-create-button-with-png-background-in-tkinter
#https://stackoverflow.com/questions/40780634/tkinter-canvas-window-size
#https://stackoverflow.com/questions/5612237/inserting-a-button-into-a-tkinter-listbox-on-python

    display = Frame(frame1, bg="white")
    display.grid(row=25, column=0, columnspan=1, sticky=EW)

    scframe = VerticalScrolledFrame(display)
    scframe.pack()

    photo1 = ImageTk.PhotoImage(file="button1v3.png")
    photo2 = ImageTk.PhotoImage(file="button2v3.png")

    class HoverButton(Button):
        def __init__(self, master, **kw):
            Button.__init__(self,
                            master=master,
                            compound="center",
                            image=photo1,
                            bg="white",
                            activebackground="white",
                            relief=FLAT,
                            **kw)
            self.bind("<Enter>", self.on_enter)
            self.bind("<Leave>", self.on_leave)

        def on_enter(self, e):
            self['image'] = photo2

        def on_leave(self, e):
            self['image'] = photo1
            self['background'] = "white"

    mylist = [
        'graph1', 'graph2', 'graph3', 'graph4', 'graph5', 'graph6', 'graph7',
        'graph8', 'graph9', 'graph10', 'graph11', 'graph12'
    ]
    button_identities = []

    def suppress(n):
        bname = (button_identities[n])
        bname.destroy()

    for i in range(len(mylist)):
        btn = HoverButton(scframe.interior,
                          text=mylist[i],
                          command=partial(suppress, i))
        btn.pack(padx=10, pady=5, side=TOP)
        button_identities.append(btn)

    butts = Frame(frame1, bg="white")
    butts.grid(row=25, column=1, columnspan=1, sticky=EW)

    plot = Button(butts, text="Plot !", command=plotting, relief=FLAT)
    plot.configure(font=('Courrier', 18), bg=myColor5, fg="white")
    plot.pack(side=TOP, fill=BOTH)

    addanother = Button(butts, text="Ajouter un graphe", relief=FLAT)
    addanother.configure(font=('Courrier', 18), bg=myColor5, fg="white")
    addanother.pack(side=TOP, fill=BOTH)

    ############################## clearing function ##############################
    def clearall():
        absexpr.delete(0, 'end')
        ordexpr.delete(0, 'end')
        absminexpr.delete(0, 'end')
        absmaxexpr.delete(0, 'end')
        titleexpr.delete(0, 'end')
        xlabelexpr.delete(0, 'end')
        ylabelexpr.delete(0, 'end')
        error1.configure(fg="white")
        error2.configure(fg="white")
        error3.configure(fg="white")
        error4.configure(fg="white")
        moreConsigne1.configure(font="Courrier 10 italic", fg="black")
        moreConsigne2.configure(font="Courrier 10 italic", fg="black")
        approxvariable.set("/")
        interpvariable.set("aucune")
        evalexpr.delete(0, 'end')
        for item in button_identities:
            item.destroy()
        a.clear()
        canvas.draw()

    clearall = Button(butts,
                      text="Effacer tout",
                      command=clearall,
                      relief=FLAT)
    clearall.configure(font=('Courrier', 18), bg=myColor5, fg="white")
    clearall.pack(side=TOP, fill=BOTH)

    return fen
Ejemplo n.º 4
0
    def __init__(self, title, dataset, show_img_stats=False):
        """initialize visualization

        Args:
            title (str): title of visualizer
            dataset (object): vortex dataset
            show_img_stats (bool, optional): show histogram & boxplot. Defaults to False.
        """
        # dataset
        # observed_nodes = list(dataset.keys())
        self.dataset = dataset

        root = tkinter.Tk()
        root.title(title)
        # Add a grid
        mainframe = tkinter.Frame(root)
        sticky = (tkinter.N, tkinter.W, tkinter.E, tkinter.S)
        mainframe.grid(column=0, row=0, sticky=sticky)
        mainframe.columnconfigure(0, weight=1)
        mainframe.rowconfigure(0, weight=1)
        mainframe.pack(pady=10, padx=100)
        self.root = root
        self.mainframe = mainframe
        # Create a Tkinter variable
        tkvar = tkinter.StringVar(root)
        # Dictionary with options
        choices = list([str(i) for i in range(len(dataset))])
        tkvar.set('1')  # set the default option
        label = ttk.Label(mainframe, text="Index").grid(row=1, column=1)
        # note that width is not automatically adjusted
        combobox = ttk.Combobox(mainframe,
                                textvariable=tkvar,
                                values=choices,
                                width=90)
        combobox.grid(row=2, column=1)
        next_button = ttk.Button(mainframe, text="Next",
                                 command=self.next).grid(row=2, column=2)
        prev_button = ttk.Button(mainframe, text="Prev",
                                 command=self.prev).grid(row=2, column=0)
        # link function to change dropdown
        tkvar.trace('w', self.change_dropdown)
        self.label = label
        self.tkvar = tkvar
        self.combobox = combobox
        self.next_button = next_button
        self.prev_button = prev_button

        figure = plt.figure()
        # observer = dataset[observed_nodes[0]]
        self.show_img_stats = show_img_stats
        self.class_names = dataset.class_names if hasattr(
            dataset, 'class_names') else None
        visualization = visualize(dataset[0],
                                  dataset.data_format,
                                  figure,
                                  show_img_stats,
                                  class_names=self.class_names)
        figure.tight_layout()
        self.figure = figure
        # visualization.histogram.figure.show()

        # plotter
        canvas = FigureCanvasTkAgg(self.figure,
                                   master=root)  # A tk.DrawingArea.
        canvas.draw()
        canvas.get_tk_widget().pack(side=tkinter.TOP,
                                    fill=tkinter.BOTH,
                                    expand=1)

        toolbar = NavigationToolbar2Tk(canvas, root)
        toolbar.update()
        canvas.get_tk_widget().pack(side=tkinter.TOP,
                                    fill=tkinter.BOTH,
                                    expand=1)
        self.canvas = canvas
        self.toolbar = toolbar

        button = tkinter.Button(master=root, text="Quit", command=self.quit)
        button.pack(side=tkinter.BOTTOM)
        self.button = button
def process_coordinates_data(ents):

    if len(data) == 0:
        messagebox.showerror("Error", "Select GPX directory first.")
        return 0

    start = 0
    mid = 0
    end = 0

    if isFloat(ents['start_Lat'].get()) and isFloat(ents['start_Long'].get()):
        start = (float(ents['start_Lat'].get()),
                 float(ents['start_Long'].get()))
    if isFloat(ents['mid_Lat'].get()) and isFloat(ents['mid_Long'].get()):
        mid = (float(ents['mid_Lat'].get()), float(ents['mid_Long'].get()))
    if isFloat(ents['end_Lat'].get()) and isFloat(ents['end_Long'].get()):
        end = (float(ents['end_Lat'].get()), float(ents['end_Long'].get()))

    if (start == 0 or end == 0):
        messagebox.showerror("Error", "Enter valid start and end coordinates.")
        return 0

    info = get_coordinates_info(start, end, mid=(0, 0))

    if info == 0:
        messagebox.showerror("Error", "More than one path exists or no path.")
        return 0

    plot_window = Toplevel()
    plot_window.geometry("1000x1000")
    plot_window.title("Statistics")

    fig = Figure(figsize=(9, 9), dpi=100)

    plot = fig.add_subplot(111)

    plot.scatter(info['speed_plot'][0], info['speed_plot'][1])

    plot.set_title("Speed throughout trips (in km/hr)")

    fig.tight_layout()

    canvas = FigureCanvasTkAgg(fig, master=plot_window)
    canvas.draw()

    toolbar = NavigationToolbar2Tk(canvas, plot_window)
    toolbar.update()

    canvas.get_tk_widget().pack()

    summary_window = Toplevel()
    summary_window.geometry("400x300")
    mylist = Listbox(summary_window, width=20, height=10)
    mylist.pack(padx=10, pady=10, fill="both", expand=True)

    mylist.insert(END, "Distance Covered (in Km): {}".format(
        info['distance_covered']))
    mylist.insert(END, "Elevation Gain (in feet): {}".format(
        info['elevation_gain']))
    mylist.insert(END, "Mean Speed: {}".format(np.mean(info['speed_plot'][1])))
    mylist.insert(END, "Standard Deviation of speed: {}".format(
        np.std(info['speed_plot'][1])))

    plot_window.mainloop()
    summary_window.mainloop()
Ejemplo n.º 6
0
 def __init__(self, canvas_, parent, ax):
     NavigationToolbar2Tk.__init__(self, canvas_, parent)
     self._xlim = (0, 1)
     self._ylim = (0, 1)
     self._ax = ax
     self._canvas_ = canvas_
Ejemplo n.º 7
0
    def setupGUI(self, parent, controller):
        ### Initialise Frame
        tk.Frame.__init__(self, parent)

        ### Matplotlib 2 Tk Stuff
        canvas = FigureCanvasTkAgg(self.fig, self)
        canvas.draw()
        canvas.get_tk_widget().grid(row=0,column=0)
        #canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        ## Setup up toolbar in its own frame since it likes to pack shit
        toolbarFrame = ttk.Frame(self)
        toolbarFrame.grid(row=0, column=0, sticky="NW")
        toolbar = NavigationToolbar2Tk(canvas, toolbarFrame)
        toolbar.update()
        ## Draw the new canvas ting
        canvas._tkcanvas.grid(row=0,column=0)


        ### Set Current Button
        self.setCurrentButton = ttk.Button(controller)
        self.setCurrentButton.configure(text="Set Current", command=self.setCurrentLevel)
        self.setCurrentButton.grid(row=2, column=0, sticky="W")

        ### Live Label
        self.liveLabel = ttk.Label(controller, text="Live Values:")
        self.liveLabel.grid(row=1, column=0)

        ### Live Current Measurement
        self.liveCurrentLabel = ttk.Label(controller, text=str(self.liveCurrent)+"A")
        self.liveCurrentLabel.grid(row=2, column=0)

        ## Live Voltage Measurement
        self.liveVoltageLabel = ttk.Label(controller, text=str(self.liveVoltage)+"V")
        self.liveVoltageLabel.grid(row=3, column=0)

        ### Current Entry Field
        self.currentSetEntryWidget = ttk.Entry(controller)
        self.currentSetEntryWidget.grid(row=2,column=0, sticky="E")
        self.currentSetEntryWidget.insert(0,"Enter Desired Current")

        ### Set Cutoff Voltage Button
        self.setVoltageCutoffButton = ttk.Button(controller)
        self.setVoltageCutoffButton.configure(text="Set Cutoff Voltage", command=self.setVoltageCutoffLevel)
        self.setVoltageCutoffButton.grid(row=3, column=0, sticky="W")

        ### Voltage Cutoff Entry Field
        self.voltageCutoffEntryWidget = ttk.Entry(controller)
        self.voltageCutoffEntryWidget.grid(row=3, column=0, sticky="E")
        self.voltageCutoffEntryWidget.insert(0, "Enter Cutoff Voltage")

        ### Start Button
        self.startButton = ttk.Button(controller)
        self.startButton.configure(text="Start", command=self.startTest)
        self.startButton.grid(row=1, column=0, sticky="W")

        ### Stop Button
        self.stopButton = ttk.Button(controller)
        self.stopButton.configure(text="Stop", command=self.stopTest)
        self.stopButton.grid(row=1, column=0, sticky="E")

        ### COM List
        self.COMList = ttk.OptionMenu(controller, self.COMPort, *self.COMPorts)
        self.COMList.grid(row=0, column=0, stick="NE")

        ### Set COM Button
        self.setCOMButton = ttk.Button(controller)
        self.setCOMButton.configure(text="Connect", command=self.connectToSerial)
        self.setCOMButton.grid(row=0, column=0, sticky="NE", pady=25)

        ## Set Current Offset Scale
        self.setCurrentOffsetScale = tk.Scale(self.currentOffset, orient='horizontal', from_=-5, to=5, length=1000, resolution=0.01)
        self.setCurrentOffsetScale.grid(row=4, column=0)

        ## Set Current Offset Button
        self.setCurrentOffsetButton = ttk.Button(controller)
        self.setCurrentOffsetButton.configure(text="Set Current Offset", command=self.setCurrentOffset)
        self.setCurrentOffsetButton.grid(row=4, column=0, sticky="W")

        ## Set Voltage Offset Scale
        self.setVoltageOffsetScale = tk.Scale(self.voltageOffset, orient='horizontal', from_=-5, to=5, length=1000, resolution=0.01)
        self.setVoltageOffsetScale.grid(row=5, column=0)

        ## Set Voltage Offset Button
        self.setVoltageOffsetButton = ttk.Button(controller)
        self.setVoltageOffsetButton.configure(text="Set Voltage Offset", command=self.setVoltageOffset)
        self.setVoltageOffsetButton.grid(row=5, column=0, sticky="W")

        ### mAh Title
        self.mahTitleLabel = ttk.Label(controller, text="mAh")
        self.mahTitleLabel.grid(row=4, column=0, sticky="E", pady=30)

        ### mAh Count
        self.mahCountLabel = ttk.Label(controller, text="0")
        self.mahCountLabel.grid(row=5, column=0, sticky="E")
Ejemplo n.º 8
0
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        #Pre-configuration of interface
        self.winfo_toplevel().title("SE4TeC - Shapelets Extraction")
        self._root().geometry('820x620')
        self.k_list = list(range(10))
        self.guiFunc = gui_function(self)
        '''start of menubar'''
        menubar = Menu(self)
        filemenu = Menu(menubar, tearoff=0)

        filemenu.add_command(label="New training file",
                             command=self.guiFunc.add_dataset)
        # add the tkinter.Label which indicate the file name
        filemenu.add_separator()
        filemenu.add_command(label="exit", command=self.hello)
        menubar.add_cascade(label="File", menu=filemenu)
        self._root().config(menu=menubar)
        '''end of menubar'''

        #Frame1
        self.frame1 = tkinter.Frame(self, bg="SkyBlue4")
        #self.frame1.pack(fill = BOTH, side=TOP)
        self.frame1.pack(fill=X)
        self.frame1.config(borderwidth=2, relief=GROOVE)

        #Frame 1_1
        self.frame1_1 = tkinter.Frame(self.frame1, bg="SkyBlue4")
        self.frame1_1.grid(row=0, column=0, sticky=W)
        l1 = tkinter.Label(self.frame1_1,
                           text="SE4TeC",
                           background="SkyBlue4",
                           font="Helvetica 28 bold",
                           foreground="White")
        l1.grid(row=0, column=0, sticky=W, rowspan=2)

        self.frame1_2 = tkinter.Frame(self.frame1, bg="SkyBlue4")
        self.frame1_2.grid(row=0, column=1, sticky=W)
        '''b1 = tkinter.Button(self.frame1_2, text="Import Dataset", command=self.guiFunc.add_dataset, highlightthickness=4,
                      #highlightcolor="SkyBlue4",
                      anchor="center",
                      highlightbackground="SkyBlue4",
                      borderwidth=4)'''
        b1 = tkinter.Button(
            self.frame1_2,
            text="Import Dataset",
            command=self.guiFunc.add_dataset,
            highlightthickness=4,
            # highlightcolor="SkyBlue4",
            anchor="center",
            highlightbackground="SkyBlue4",
            borderwidth=4)
        b1.grid(row=0, column=0, sticky=W, padx=15, pady=10)

        #Frame 2: the middle part of GUI
        self.frame2 = tkinter.Frame(self, bg="gray90")
        self.frame2.pack(fill=BOTH)
        self.frame2.config(borderwidth=2, relief=GROOVE)

        # Placement of a single SOURCE visualization
        self.frame2_1 = SMAPPage(self.frame2, self)

        #Frame 1_3
        self.frame1_3 = tkinter.Frame(self.frame1, bg="SkyBlue4")
        self.frame1_3.grid(row=0, column=2, sticky=E, columnspan=2, padx=80)
        self.img_open = Image.open('CombinedLogo_360_40.jpg')
        self.img = ImageTk.PhotoImage(self.img_open)
        self.label_img = tkinter.Label(self.frame1_3, image=self.img)
        self.label_img.pack()
        '''l_algo = tkinter.Label(self.frame1_3, text="Select the algorithm: ", background= "SkyBlue4", foreground = "White")
        radVar = StringVar()
        b_USE = tkinter.Radiobutton(self.frame1_3, text="USE", variable=radVar, value="USEPage", indicatoron=0, command=lambda x=radVar: self.show_frame(self.frame2, x.get()), border=4)
        b_SMAP = tkinter.Radiobutton(self.frame1_3, text="SMAP", variable=radVar, value="SMAPPage", indicatoron=0, command=lambda x=radVar: self.show_frame(self.frame2, x.get()), border=4)
        b_SMAP_LB = tkinter.Radiobutton(self.frame1_3, text="SMAP_LB", variable=radVar, value="SMAPLBPage", indicatoron=0, command=lambda x=radVar: self.show_frame(self.frame2, x.get()), border=4)
        l_algo.grid(row=0, column=0, sticky=E, padx=(15,5), pady=10)  # position "West"
        b_USE.grid(row=0, column=1, ipadx=15, ipady=10, padx=15, pady=10)
        b_SMAP.grid(row=0, column=2, ipadx=15, ipady=10, padx=15, pady=10)
        b_SMAP_LB.grid(row=0, column=3, ipadx=15, ipady=10, padx=15, pady=10)'''
        self.frame1_3.grid_columnconfigure(0, weight=1)

        ####################################################################################
        #############################Frame 2_2, plot of results#############################
        self.frame2_2 = tkinter.Frame(self.frame2)
        self.frame2_2.grid(row=0, column=1, sticky=N, columnspan=2)
        self.figure = plt.figure(figsize=(8, 6), dpi=60)
        self.ax1 = self.figure.add_subplot(311)
        self.ax2 = self.figure.add_subplot(312, sharex=self.ax1)
        self.ax3 = self.figure.add_subplot(313, sharex=self.ax1)
        self.ax1.axis("off")
        self.ax2.axis("off")
        self.ax3.axis("off")
        self.canvas = FigureCanvasTkAgg(self.figure, self.frame2_2)
        self.canvas.draw()
        #canvas.get_tk_widget().pack(fill=tkinter.BOTH, expand=True)
        self.canvas.get_tk_widget().grid(row=1, column=0, sticky=E)

        toolbar = NavigationToolbar2Tk(self.canvas, self.frame2_2)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tkinter.TOP,
                                   fill=tkinter.BOTH,
                                   expand=True)
        #############################Frame 2_2, plot of results#############################
        ####################################################################################

        ####################################################################################
        #########################Frame 2_3, Properties of Training Dataset##################
        self.frame2_3 = tkinter.Frame(self.frame2, bg="gray90")
        self.frame2_3.grid(row=1, column=0, sticky="wn")
        l_info = tkinter.Label(self.frame2_3,
                               text="Info. of Training Dataset: ",
                               background="SkyBlue4",
                               foreground="White")

        l_info.grid(row=0, column=0, sticky="ws",
                    columnspan=2)  # position "West"
        #self.frame2.rowconfigure(0, weight=3)
        #blue
        l_info1 = Label(self.frame2_3, text="TS length: ", foreground="blue")
        l_info2 = Label(self.frame2_3, text="TS number: ", foreground="blue")
        l_info3 = Label(self.frame2_3, text="Nbr class: ", foreground="blue")

        l_info4 = Label(self.frame2_3,
                        text="Source class: ",
                        foreground="blue")
        l_info5 = Label(self.frame2_3,
                        text="Target class: ",
                        foreground="blue")

        self.v_dsname = StringVar()
        self.v_tslength = IntVar()
        self.v_tsnbr = IntVar()
        self.v_classnbr = IntVar()
        self.v_sourceC = StringVar()
        self.v_targetC = StringVar()

        l_dataset = Label(self.frame2_3,
                          textvariable=self.v_dsname,
                          foreground="red")
        l_tslength = Label(self.frame2_3,
                           textvariable=self.v_tslength,
                           foreground="red")
        l_tsnbr = Label(self.frame2_3,
                        textvariable=self.v_tsnbr,
                        foreground="red")
        l_classnbr = Label(self.frame2_3,
                           textvariable=self.v_classnbr,
                           foreground="red")

        l_sourceC = Label(self.frame2_3,
                          textvariable=self.v_sourceC,
                          foreground="red")
        l_targetC = Label(self.frame2_3,
                          textvariable=self.v_targetC,
                          foreground="red")
        l_dataset.grid(row=1, column=0, sticky="ws",
                       columnspan=2)  # position "West"
        l_info1.grid(row=2, column=0, sticky="ws")  # position "West"
        l_info2.grid(row=3, column=0, sticky="ws")  # position "West"
        l_info3.grid(row=4, column=0, sticky="ws")  # position "West"
        l_tslength.grid(row=2, column=1, sticky="ws")  # position "West"
        l_tsnbr.grid(row=3, column=1, sticky="ws")  # position "West"
        l_classnbr.grid(row=4, column=1, sticky="ws")  # position "West"
        l_tsnbr.grid(row=3, column=1, sticky="ws")  # position "West"
        l_classnbr.grid(row=4, column=1, sticky="ws")  # position "West"

        l_info4.grid(row=2, column=2, sticky="ws")  # position "West"
        l_info5.grid(row=3, column=2, sticky="ws")  # position "West"
        l_sourceC.grid(row=2, column=3, sticky="ws")  # position "West"
        l_targetC.grid(row=3, column=3, sticky="ws")  # position "West"
        #########################Frame 2_3, Properties of Training Dataset##################
        ####################################################################################

        ####################################################################################
        #########################Frame 2_3, Properties of Testing Dataset###################
        self.frame2_4 = tkinter.Frame(self.frame2, bg="gray90")
        self.frame2_4.grid(row=1, column=1, sticky="wn")
        l_testinfo = tkinter.Label(self.frame2_4,
                                   text="Info. of Testing Dataset: ",
                                   background="SkyBlue4",
                                   foreground="White")

        l_testinfo.grid(row=0, column=0, sticky="ws",
                        columnspan=2)  # position "West"
        # self.frame2.rowconfigure(0, weight=3)
        # blue
        l_testinfo1 = Label(self.frame2_4,
                            text="TS length: ",
                            foreground="blue")
        l_testinfo2 = Label(self.frame2_4,
                            text="TS number: ",
                            foreground="blue")
        l_testinfo3 = Label(self.frame2_4,
                            text="Nbr class: ",
                            foreground="blue")

        self.v_testdsname = StringVar()
        self.v_testtslength = IntVar()
        self.v_testtsnbr = IntVar()
        self.v_testclassnbr = IntVar()

        l_testdataset = Label(self.frame2_4,
                              textvariable=self.v_testdsname,
                              foreground="red")
        l_testtslength = Label(self.frame2_4,
                               textvariable=self.v_testtslength,
                               foreground="red")
        l_testtsnbr = Label(self.frame2_4,
                            textvariable=self.v_testtsnbr,
                            foreground="red")
        l_testclassnbr = Label(self.frame2_4,
                               textvariable=self.v_testclassnbr,
                               foreground="red")

        l_testdataset.grid(row=1, column=0, sticky="ws",
                           columnspan=2)  # position "West"
        l_testinfo1.grid(row=2, column=0, sticky="ws")  # position "West"
        l_testinfo2.grid(row=3, column=0, sticky="ws")  # position "West"
        l_testinfo3.grid(row=4, column=0, sticky="ws")  # position "West"
        l_testtslength.grid(row=2, column=1, sticky="ws")  # position "West"
        l_testtsnbr.grid(row=3, column=1, sticky="ws")  # position "West"
        l_testclassnbr.grid(row=4, column=1, sticky="ws")  # position "West"
        #########################Frame 2_4, Properties of Testing Dataset###################
        ####################################################################################

        ####################################################################################
        #########################Frame 2_4_1, Properties of Testing Dataset###################
        self.frame2_4_1 = tkinter.Frame(self.frame2, bg="gray90")
        self.frame2_4_1.grid(row=1, column=2, sticky="wn")
        l_timeinfo = tkinter.Label(self.frame2_4_1,
                                   text="Running Time (s): ",
                                   background="SkyBlue4",
                                   foreground="White")
        l_timeinfo.grid(row=0, column=0, sticky="ws",
                        columnspan=2)  # position "West"
        l_timeinfo1 = Label(self.frame2_4_1, text="USE ", foreground="blue")
        l_timeinfo2 = Label(self.frame2_4_1, text="SMAP: ", foreground="blue")
        l_timeinfo3 = Label(self.frame2_4_1,
                            text="SMAP_LB: ",
                            foreground="blue")
        self.v_timeUSE = IntVar()
        self.v_timeSMAP = IntVar()
        self.v_timeSMAPLB = IntVar()
        l_timeUSE = Label(self.frame2_4_1,
                          textvariable=self.v_timeUSE,
                          foreground="red")
        l_timeSMAP = Label(self.frame2_4_1,
                           textvariable=self.v_timeSMAP,
                           foreground="red")
        l_timeSMAPLB = Label(self.frame2_4_1,
                             textvariable=self.v_timeSMAPLB,
                             foreground="red")
        l_timeinfo1.grid(row=1, column=0, sticky="ws")  # position "West"
        l_timeinfo2.grid(row=2, column=0, sticky="ws")  # position "West"
        l_timeinfo3.grid(row=3, column=0, sticky="ws")  # position "West"
        l_timeUSE.grid(row=1, column=1, sticky="ws")  # position "West"
        l_timeSMAP.grid(row=2, column=1, sticky="ws")  # position "West"
        l_timeSMAPLB.grid(row=3, column=1, sticky="ws")  # position "West"
        #########################Frame 2_4_1, Properties of Testing Dataset###################
        ####################################################################################

        # Frame 3, extract Shapelets, predict the test instance
        self.frame3 = tkinter.Frame(self, bg="gray90")
        self.frame3.pack(fill=X)
        self.frame3.config(borderwidth=2, relief=GROOVE)

        ######################################################################################
        #########################Frame3_1, Show raw TS & Shapelets############################
        self.frame3_1 = tkinter.Frame(self.frame3, bg="gray90")
        self.frame3_1.grid(row=0, column=0, sticky=W)

        self.v_class = StringVar()
        self.v_k = IntVar()
        l_class = tkinter.Label(self.frame3_1, text="Class", bg="gray90")
        combb_shap_class = Combobox(self.frame3_1,
                                    values=["1.0", "-1.0"],
                                    textvariable=self.v_class,
                                    state='readonly',
                                    width=6)
        b_show_ds = tkinter.Button(self.frame3_1,
                                   text="show TS set",
                                   command=self.guiFunc.showTSset,
                                   highlightthickness=4,
                                   anchor="center",
                                   highlightbackground="gray90",
                                   borderwidth=0)
        l_k = tkinter.Label(self.frame3_1, text="select k", bg="gray90")
        combb_k = Combobox(self.frame3_1,
                           values=self.k_list,
                           textvariable=self.v_k,
                           state='readonly',
                           width=5)
        b_shap_extract = tkinter.Button(
            self.frame3_1,
            text="Show Shapelets",
            command=self.guiFunc.extractShapeletCandidate,
            highlightthickness=4,
            anchor="center",
            highlightbackground="gray90",
            borderwidth=0)
        l_class.grid(row=0, column=0, sticky=W)
        combb_shap_class.grid(row=0, column=1, sticky=W)
        b_show_ds.grid(row=1, column=0, sticky=W, columnspan=2)

        l_k.grid(row=0, column=2, sticky=W)
        combb_k.grid(row=0, column=3, sticky=W)
        b_shap_extract.grid(row=1,
                            column=2,
                            sticky=W + E + N + S,
                            columnspan=2)
        #########################Frame3_1, Show raw TS & Shapelets############################
        ######################################################################################

        self.frame3_2 = tkinter.Frame(self.frame3, bg="gray90")
        self.frame3_2.grid(row=0, column=2, sticky=E, padx=(100, 0))
        self.v_testInstance = StringVar()
        self.v_testInstance.set("select")
        b_testfile = tkinter.Button(
            self.frame3_2,
            text="Import testing data",
            command=self.guiFunc.add_testing_file,
            highlightthickness=4,
            # highlightcolor="SkyBlue4",
            anchor="center",
            highlightbackground="gray90",
            borderwidth=0)
        self.combb_test = Combobox(self.frame3_2,
                                   values=self.guiFunc.testdataset.tsNbrList,
                                   textvariable=self.v_testInstance,
                                   postcommand=self.update_combbtest,
                                   state='readonly',
                                   width=10)
        self.combb_test.bind('<<ComboboxSelected>>', self.callback_test)
        b_predict = tkinter.Button(
            self.frame3_2,
            text="predict",
            command=lambda: self.guiFunc.predict(self),
            highlightthickness=4,
            #highlightcolor="SkyBlue4",
            anchor="center",
            highlightbackground="gray90",
            borderwidth=0)
        b_testfile.grid(row=0, column=0, sticky=W)
        self.combb_test.grid(row=0, column=1, sticky=W)
        b_predict.grid(row=1, column=0, sticky=W + E + N + S, columnspan=2)
def predicted_graph():

    #global root
    root = tk.Tk()
    #root.wm_title("Embedding in Tk")

    fig = Figure(figsize=(10, 5), dpi=100)
    ax2 = fig.add_subplot(111)
    canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
    #ploting
    #Prediction
    pricemin = df2['Close'].min()
    df2['Close'].plot(kind='line',
                      linewidth=.8,
                      legend=True,
                      ax=ax2,
                      color='#3385ff',
                      fontsize=10)
    df2['Forecast'].plot(kind='line',
                         linewidth=.7,
                         legend=True,
                         ax=ax2,
                         color='#00e600',
                         fontsize=10)
    ax2.fill_between(df2.index,
                     pricemin,
                     df['Forecast'],
                     facecolor='#33ff33',
                     alpha=0.5)
    ax2.fill_between(df2.index,
                     pricemin,
                     df['Close'],
                     facecolor='#3385ff',
                     alpha=0.5)

    #Navigation toolbar
    canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
    canvas.draw()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    toolbar = NavigationToolbar2Tk(canvas, root)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    #button = tk.Button(master=root, text="Quit", command=terminate, bg='#ff0000', fg='white', font=('helvetica', 11, 'bold'))
    #button.pack(side=tk.BOTTOM)

    button2 = tk.Button(
        master=root,
        text="Moving Average Curve",
        command=lambda: [quit2(root), moving_average_curve()],
        bg='#0066ff',
        fg='white',
        font=('helvetica', 11, 'bold'))
    button2.pack(side=tk.BOTTOM)

    label_acc = tk.Label(master=root,
                         text='Accuracy Of Model : ' + str(accuracy))
    label_acc.config(font=('helvetica', 12))
    label_acc.pack(side=tk.RIGHT)

    root.title('Stock Market Predictor')
    ax2.set_title('Predicted Graph For ' + NOS, color='#ffb31a')

    tk.mainloop()
Ejemplo n.º 10
0
button = Button(fileF,
                text="Wybrać plik",
                bg='#f5ce93',
                font=15,
                command=open_file)
button.pack(side='left', fill='both')
fileLabel = Label(fileF, font=15)
fileLabel.pack(side='left', fill='both', expand=True)

f = Figure(figsize=(5, 5), dpi=100)
drawn_plot = f.add_subplot(111)
plotFigure = FigureCanvasTkAgg(f, plotF)
plotFigure.draw()
plotFigure.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
toolbar = NavigationToolbar2Tk(plotFigure, plotF)
toolbar.update()
plotFigure._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

fsLabel = Label(modF, text="Częstotliwość próbkowania", font=15)
fsLabel.place(relx=0, rely=0.2, relwidth=0.2, relheight=0.2)
samplingRate = Entry(modF, font=15, justify=CENTER)
samplingRate.place(relx=0.2, rely=0.2, relwidth=0.21, relheight=0.2)

scalingL = Label(modF, text="Współczynnik skalowania", font=15)
scalingL.place(relx=0, rely=0.4, relwidth=0.2, relheight=0.2)
scalingRate = Entry(modF, font=15, justify=CENTER)
scalingRate.place(relx=0.2, rely=0.4, relwidth=0.21, relheight=0.2)

lengthL = Label(modF, text="Długość: [s]", font=15)
lengthL.place(relx=0, rely=0.6, relwidth=0.2, relheight=0.2)
    def __init__(self, master):
        # load data
        datetime_list, barpress_list = [], []
        datetime_re = re.compile(r'[\d]{2,4}')  # regex to get datetime info
        for year in range(2012, 2016):
            fname = '../resources/Environmental_Data_Deep_Moor_{0}.txt'.format(
                year)
            print('Loading {0}'.format(fname))
            for row in DictReader(open(fname, 'r'), delimiter='\t'):
                barpress_list.append(float(row['Barometric_Press']))
                datetime_list.append(
                    date2num(
                        datetime(*list(
                            map(
                                int,
                                datetime_re.findall(
                                    row['date       time    ']))))))

        self.datetime_array = np.array(datetime_list)
        self.barpress_array = np.array(barpress_list)

        # build the gui
        master.title('Weather Statistics')
        master.resizable(True, True)
        master.state('zoomed')

        matplotlib.rc('font', size=18)
        f = Figure()
        f.set_facecolor((0, 0, 0, 0))
        self.a = f.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(f, master)
        self.canvas.draw()
        toolbar_frame = ttk.Frame(master)  # needed to put navbar above plot
        toolbar = NavigationToolbar2Tk(self.canvas, toolbar_frame)
        toolbar.update()
        toolbar_frame.pack(side=TOP, fill=X, expand=0)
        self.canvas._tkcanvas.pack(fill=BOTH, expand=1)

        controls_frame = ttk.Frame(master)
        controls_frame.pack()

        ttk.Label(controls_frame, text='Start',
                  font='Arial 18 bold').grid(row=0, column=0, pady=5)
        ttk.Label(controls_frame,
                  text='(YYYY-MM-DD HH:MM:SS)',
                  font='Courier 12').grid(row=1, column=0, padx=50, sticky='s')
        self.start = StringVar()
        ttk.Entry(controls_frame,
                  width=19,
                  textvariable=self.start,
                  font='Courier 12').grid(row=2, column=0, sticky='n')
        self.start.set(str(num2date(self.datetime_array[0]))[0:19])

        ttk.Label(controls_frame, text='End',
                  font='Arial 18 bold').grid(row=0, column=1, pady=5)
        ttk.Label(controls_frame,
                  text='(YYYY-MM-DD HH:MM:SS)',
                  font='Courier 12').grid(row=1, column=1, padx=50, sticky='s')
        self.end = StringVar()
        ttk.Entry(controls_frame,
                  width=19,
                  textvariable=self.end,
                  font='Courier 12').grid(row=2, column=1, sticky='n')
        self.end.set(str(num2date(self.datetime_array[-1]))[0:19])

        ttk.Button(controls_frame, text='Update',
                   command=self._update).grid(row=3,
                                              column=0,
                                              columnspan=2,
                                              pady=10)
        ttk.Style().configure('TButton', font='Arial 18 bold')

        self._update()
Ejemplo n.º 12
0
#try fitting
#

#construct figure
fig = Figure(figsize=(8, 6), dpi=100)
sp = fig.add_subplot(111)
sp.plot_date(ftl_dt, atl)
sp.plot_date(ftl_dt, atl_smooth)
sp.plot_date(ftl_dt_ex, f(ftl_ts_ex))

canvas = FigureCanvasTkAgg(fig, master=mainframe)
canvas.draw()
canvas.get_tk_widget().grid(column=2, row=2, sticky=W)
canvas.mpl_connect("key_press_event", on_key_press)

#add convenient toolbar
toolframe = ttk.Frame(root, padding="3 3 3 3")
toolframe.grid(column=0, row=1, sticky=(N, W, E, S))
toolbar = NavigationToolbar2Tk(canvas, toolframe)
toolbar.update()

#adjust child spacing for visibility
for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)

#start clock
keep_time()

#run main loop
root.mainloop()
Ejemplo n.º 13
0
    def __init__(self, master):
        self.master = master
        self.master.title("ZASADY BUDOWY ROBOTÓW: Projekt 1")
        master.geometry("1000x950")
        #master.resizable(False,False)
        self.style = tk.ttk.Style()
        self.style.theme_use("clam")
        #self.style.configure("TCombobox", foreground="black", background="blue")

        mainwindow = tk.Frame(master)  #,bg="black"
        mainwindow.pack(side="top", fill="both", expand="True")
        mainwindow.grid_columnconfigure(2, minsize=200)

        bottom = tk.Frame(master)
        bottom.pack(side="bottom", fill="both", expand="True")

        self.quit_button = Button(master,
                                  text="Exit",
                                  command=master.quit,
                                  cursor="star")
        self.quit_button.grid(in_=bottom, row=0, column=1, pady=10, padx=10)
        self.run_button = Button(master,
                                 text="Run",
                                 command=self.getData,
                                 cursor="trek")
        self.run_button.grid(in_=bottom, row=0, column=0, pady=10, padx=10)
        self.name_label = tk.Label(master, text="Michał Kiełczykowski,2018/19")
        self.name_label.place(relx=1.0, rely=1.0, anchor='se')

        ######################first data collumn#####################

        self.input_label = tk.Label(text="Dane Wejściowe")
        self.input_label.grid(in_=mainwindow, row=0, column=0, pady=10)

        self.inl1 = tk.Label(text="l1[m]")
        self.inl1.grid(in_=mainwindow, row=1, column=0, sticky="e")
        self.enl1 = tk.Entry(master)
        self.enl1.insert(0, '0.3')
        self.enl1.grid(in_=mainwindow, row=1, column=1)

        self.inl2 = tk.Label(text="l2[m]")
        self.inl2.grid(in_=mainwindow, row=2, column=0, sticky="e")
        self.enl2 = tk.Entry(master)
        self.enl2.insert(0, '1.2')
        self.enl2.grid(in_=mainwindow, row=2, column=1)

        self.inl3 = tk.Label(text="l3[m]")
        self.inl3.grid(in_=mainwindow, row=3, column=0, sticky="e")
        self.enl3 = tk.Entry(master)
        self.enl3.insert(0, '0.7')
        self.enl3.grid(in_=mainwindow, row=3, column=1)

        self.inl4 = tk.Label(text="l4[m]")
        self.inl4.grid(in_=mainwindow, row=4, column=0, sticky="e")
        self.enl4 = tk.Entry(master)
        self.enl4.insert(0, '0.4')
        self.enl4.grid(in_=mainwindow, row=4, column=1)

        self.inl5 = tk.Label(text="l5[m]")
        self.inl5.grid(in_=mainwindow, row=5, column=0, sticky="e")
        self.enl5 = tk.Entry(master)
        self.enl5.insert(0, '0.1')
        self.enl5.grid(in_=mainwindow, row=5, column=1)

        self.inl6 = tk.Label(text="l6[m]")
        self.inl6.grid(in_=mainwindow, row=6, column=0, sticky="e")
        self.enl6 = tk.Entry(master)
        self.enl6.insert(0, '0.2')
        self.enl6.grid(in_=mainwindow, row=6, column=1)

        self.inl7 = tk.Label(text="d[m]")
        self.inl7.grid(in_=mainwindow, row=7, column=0, sticky="e")
        self.enl7 = tk.Entry(master)
        self.enl7.insert(0, '0.2')
        self.enl7.grid(in_=mainwindow, row=7, column=1)

        self.inl8 = tk.Label(text="e[m]")
        self.inl8.grid(in_=mainwindow, row=8, column=0, sticky="e")
        self.enl8 = tk.Entry(master)
        self.enl8.insert(0, '0.1')
        self.enl8.grid(in_=mainwindow, row=8, column=1)

        self.inl9 = tk.Label(text="theta [deg]")
        self.inl9.grid(in_=mainwindow, row=9, column=0, sticky="e")
        self.enl9 = tk.Entry(master)
        self.enl9.insert(0, '30')
        self.enl9.grid(in_=mainwindow, row=9, column=1)

        self.inl10 = tk.Label(text="psi [deg]")
        self.inl10.grid(in_=mainwindow, row=10, column=0, sticky="e")
        self.enl10 = tk.Entry(master)
        self.enl10.insert(0, '40')
        self.enl10.grid(in_=mainwindow, row=10, column=1)

        self.inld1 = tk.Label(text="delta1")
        self.inld1.grid(in_=mainwindow, row=11, column=0, sticky="e")
        self.d1 = Combobox(master, state='readonly')
        self.d1['values'] = (1, -1)
        self.d1.current(1)
        self.d1.grid(in_=mainwindow, row=11, column=1)

        self.inld2 = tk.Label(text="delta2")
        self.inld2.grid(in_=mainwindow, row=12, column=0, sticky="e")
        self.d2 = Combobox(master, state='readonly')
        self.d2['values'] = (1, -1)
        self.d2.current(1)
        self.d2.grid(in_=mainwindow, row=12, column=1, padx=5)

        self.inld3 = tk.Label(text="delta3")
        self.inld3.grid(in_=mainwindow, row=13, column=0, sticky="e")
        self.d3 = Combobox(master, state='readonly')
        self.d3['values'] = (1, -1)
        self.d3.current(0)
        self.d3.grid(in_=mainwindow, row=13, column=1)

        ######################second data collumn#####################
        # self.coordinates_label = Label(master,text="Współrzędne maszynowe")
        # self.coordinates_label.grid(in_=mainwindow,row=0,column=2,pady=10)

        # self.fi1= tk.StringVar()
        # self.fi2= tk.StringVar()
        # self.fi3= tk.StringVar()
        # self.fi4= tk.StringVar()
        # self.fi5 = tk.StringVar()

        # self.fi1.set("fi1 =")
        # self.fi2.set("fi2 =")
        # self.fi3.set("fi3 =")
        # self.fi4.set("fi4 =")
        # self.fi5.set("fi5 =")

        # self.fi1_label = Label(master,textvariable=self.fi1)
        # self.fi2_label = Label(master,textvariable=self.fi2)
        # self.fi3_label = Label(master,textvariable=self.fi3)
        # self.fi4_label = Label(master,textvariable=self.fi4)
        # self.fi5_label = Label(master,textvariable=self.fi5)

        # self.fi1_label.grid(in_=mainwindow,row=1, column=2)
        # self.fi2_label.grid(in_=mainwindow,row=2, column=2)
        # self.fi3_label.grid(in_=mainwindow,row=3, column=2)
        # self.fi4_label.grid(in_=mainwindow,row=4, column=2)
        # self.fi5_label.grid(in_=mainwindow,row=5, column=2)

        self.route_label = Label(
            master,
            text="   Parametry toru ruchu\n(Współrzędne Postaci: 'x,y,z')",
        )
        self.route_label.grid(in_=mainwindow,
                              row=0,
                              column=2,
                              pady=10,
                              rowspan=2)

        self.route1_label = Label(master, text="Współrzędne punktu startowego")
        self.route1_label.grid(in_=mainwindow, row=2, column=2)

        self.route2_label = Label(master, text="Współrzędne punktu przejścia1")
        self.route2_label.grid(in_=mainwindow, row=4, column=2)

        self.route3_label = Label(master, text="Współrzędne punktu przejścia2")
        self.route3_label.grid(in_=mainwindow, row=6, column=2)

        self.route4_label = Label(master, text="Współrzędne punktu przejścia3")
        self.route4_label.grid(in_=mainwindow, row=8, column=2)

        self.route5_label = Label(master, text="Współrzędne punktu końcowego")
        self.route5_label.grid(in_=mainwindow, row=10, column=2)

        self.route5_label = Label(master, text="Rozdzielczość symulacji")
        self.route5_label.grid(in_=mainwindow, row=15, column=2)

        self.route5_label = Label(
            master,
            text="Błąd trajektorii robota od \ntrajektorii zadanej [m]")
        self.route5_label.grid(in_=mainwindow, row=17, column=2, rowspan=2)

        self.route1_entry = tk.Entry(master)
        self.route1_entry.insert(0, "1,1,1")
        self.route1_entry.grid(in_=mainwindow, row=3, column=2)

        self.route2_entry = tk.Entry(master)
        self.route2_entry.insert(0, "0,1,1")
        self.route2_entry.grid(in_=mainwindow, row=5, column=2)

        self.route3_entry = tk.Entry(master)
        self.route3_entry.insert(0, "1,0,1")
        self.route3_entry.grid(in_=mainwindow, row=7, column=2)

        self.route4_entry = tk.Entry(master)
        self.route4_entry.insert(0, "1,0,0")
        self.route4_entry.grid(in_=mainwindow, row=9, column=2)

        self.route5_entry = tk.Entry(master)
        self.route5_entry.insert(0, "0,1,0")
        self.route5_entry.grid(in_=mainwindow, row=11, column=2)

        self.route6_entry = tk.Entry(master)
        self.route6_entry.insert(0, "10")
        self.route6_entry.grid(in_=mainwindow, row=16, column=2)

        self.route7_entry = tk.Entry(master)
        self.route7_entry.insert(0, "0.1")
        self.route7_entry.grid(in_=mainwindow, row=19, column=2)

        #######adding plot to tinkter window#############

        self.f = Figure(figsize=(5, 8), dpi=100)
        self.a = self.f.add_subplot(211, projection='3d')
        self.a2 = self.f.add_subplot(212)

        self.a.set_xlabel("x")
        self.a.set_ylabel("y")
        self.a.set_zlabel("z")

        self.a2.set_ylabel("Wartość współrzędnej maszynowej [deg]")
        self.a2.set_xlabel("Punkt symulacji")

        canvas = FigureCanvasTkAgg(self.f, master)
        canvas.get_tk_widget().grid(in_=mainwindow,
                                    row=0,
                                    column=3,
                                    rowspan=30)
        toolbar = NavigationToolbar2Tk(canvas, master)
        toolbar.update()
        canvas._tkcanvas.grid(in_=mainwindow, row=1, column=3)
        axes3d.Axes3D.mouse_init(self.a)
Ejemplo n.º 14
0
    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)
        self.controller = controller

        top = tk.Frame(self)
        top.pack(side=tkinter.TOP)

        label = tk.Label(self, text="HLW8012 Live Stats", font=LARGE_FONT)
        label.pack(pady=10, padx=10, in_=top)

        ttk.Button(self,
                   text="Home",
                   width=7,
                   command=lambda: controller.show_frame(StartPage)).pack(
                       in_=top, side=tkinter.LEFT, padx=10)

        action = tk.Frame(self)
        action.pack(in_=top, side=tkinter.LEFT, padx=15)

        ttk.Button(self,
                   text="Current",
                   command=lambda: controller.set_plot_type('I')).grid(
                       in_=action, row=1, column=1)
        ttk.Button(self,
                   text="Voltage",
                   command=lambda: controller.set_plot_type('U')).grid(
                       in_=action, row=1, column=2)
        ttk.Button(self,
                   text="Power",
                   command=lambda: controller.set_plot_type('P')).grid(
                       in_=action, row=2, column=1)
        ttk.Button(self,
                   text="Pause",
                   command=lambda: controller.set_plot_type('')).grid(
                       in_=action, row=2, column=2)

        options = tk.Frame(self)
        options.pack(in_=top, side=tkinter.LEFT, padx=15)
        ttk.Label(self, text="Options:").grid(in_=options,
                                              row=1,
                                              column=1,
                                              columnspan=2,
                                              padx=5)
        ttk.Checkbutton(
            self,
            text="Convert Units",
            variable=controller.gui_settings['convert_units']).grid(
                in_=options, row=2, column=1)
        check2 = ttk.Checkbutton(
            self, text="Noise",
            variable=controller.gui_settings['noise']).grid(in_=options,
                                                            row=2,
                                                            column=2)

        ylimit = tk.Frame(self)
        ylimit.pack(in_=top, side=tkinter.LEFT, padx=15)
        ttk.Label(self, text="Lower Y Limit:").grid(in_=ylimit,
                                                    row=1,
                                                    column=1,
                                                    padx=5)
        scale1 = ttk.Scale(self,
                           from_=0,
                           to=100,
                           command=controller.set_y_range)
        scale1.grid(in_=ylimit, row=2, column=1, padx=10)

        retention = tk.Frame(self)
        retention.pack(in_=top, side=tkinter.LEFT, padx=15)
        ttk.Label(self, text="Data Retention:").grid(in_=retention,
                                                     row=1,
                                                     column=1,
                                                     columnspan=2,
                                                     padx=5)
        ttk.Entry(self,
                  width=5,
                  textvariable=controller.gui_settings['retention']).grid(
                      in_=retention, row=2, column=1)
        ttk.Label(self, text="seconds").grid(in_=retention, row=2, column=2)
        ttk.Entry(self,
                  width=5,
                  textvariable=controller.gui_settings['compress']).grid(
                      in_=retention, row=3, column=1)
        ttk.Label(self, text="seconds").grid(in_=retention, row=3, column=2)

        data = tk.Frame(self)
        data.pack(in_=top, side=tkinter.LEFT, padx=15)
        ttk.Label(self, text="Display Data:").grid(in_=data,
                                                   row=1,
                                                   column=1,
                                                   columnspan=2,
                                                   padx=5)
        ttk.Button(self,
                   text="Sensor",
                   width=7,
                   command=lambda: controller.toggle_data_state(0)).grid(
                       in_=data, row=2, column=1)
        ttk.Button(self,
                   text="Avg",
                   width=7,
                   command=lambda: controller.toggle_data_state(1)).grid(
                       in_=data, row=2, column=2)
        ttk.Button(self,
                   text="Integral",
                   width=7,
                   command=lambda: controller.toggle_data_state(2)).grid(
                       in_=data, row=3, column=1)
        ttk.Button(self,
                   text="Display",
                   width=7,
                   command=lambda: controller.toggle_data_state(3)).grid(
                       in_=data, row=3, column=2)

        canvas = FigureCanvasTkAgg(controller.plot.fig, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.BOTTOM,
                                    fill=tk.BOTH,
                                    expand=True,
                                    pady=5,
                                    padx=5)
        self.controller.plot.set_animation(False)

        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas.get_tk_widget().pack(side=tkinter.TOP,
                                    fill=tkinter.BOTH,
                                    expand=1)
Ejemplo n.º 15
0
    def __init__(self, master):
        global settings_file
        self.root = master
        self.root.title("ESS Module 2 Frame")
        full_screen = False
        if full_screen:
            self.root.attributes('-fullscreen',
                                 True)  # fullscreen on touchscreen
        else:
            self.root.geometry('800x480')  # actual size of RPi touchscreen
        #self.root.attributes('-fullscreen',True)
        self.root.configure(bg="sky blue")
        self.root.minsize(800, 480)  # min size the window can be dragged to

        #self.root.tk.call('wm','iconphoto', self.root._w, PhotoImage(file = "/home/pi/Desktop/BMO_Lab/ESS_png"))
        self.percent = 0  # battery percent variable
        self.battery_array = []
        self.charging = False
        self.open_loop_stop = None  # control open Loop button
        battery_font = tkFont.Font(family="Lucida Grande", size=8)
        label_font = tkFont.Font(family="Lucida Grande", size=12)
        warning_font = tkFont.Font(family="Lucida Grande", size=24)

        # parameters for buttons and frames
        #create all the buttons onto to the main window
        button_width = 10
        button_big_height = 8
        button_small_height = 3
        sticky_to = 'nsew'  # allows all buttons to resize

        # setup Serial port-
        ## Graphing Frame and fake plot
        self.graph_frame = Frame(self.root, background="white")
        self.graph_frame.grid(row=1,
                              column=1,
                              rowspan=8,
                              columnspan=8,
                              padx=5,
                              pady=2,
                              sticky=sticky_to)

        #initalize figure
        self.fig = plt.figure()
        plt.xlabel('Wavelength (nm)')
        plt.ylabel('ADC Counts')
        plt.xlim(300, 900)
        plt.ylim(0, 66500)
        plt.subplots_adjust(bottom=0.14, right=0.95, top=0.96)

        #initalize canvas for plotting
        self.canvas = FigureCanvasTkAgg(
            self.fig, master=self.graph_frame)  # A tk.DrawingArea.
        # create toolbar for canvas
        toolbar = NavigationToolbar2Tk(self.canvas, self.graph_frame)
        toolbar.update()
        self.canvas.get_tk_widget().pack(fill=BOTH, expand=True)

        # create function object for calling functions
        settings_func = _Settings(settings_file)

        try:
            settings_func.create_settings()
        except:
            pass

        self.func = functions(self.root, self.canvas, self.fig)

        self.open_new_button = Button(self.root,
                                      text="New Experiment",
                                      wraplength=80,
                                      fg='black',
                                      command=self.func.open_new_experiment,
                                      width=button_width,
                                      height=button_big_height)
        self.open_new_button.grid(row=0,
                                  column=0,
                                  padx=(0, 1),
                                  sticky=sticky_to)

        self.open_experiment_button = Button(
            self.root,
            text="Open Experiment",
            wraplength=80,
            fg='black',
            command=self.check_scan_number_open_file,
            width=button_width,
            height=button_big_height)
        self.open_experiment_button.grid(row=0, column=1, sticky=sticky_to)

        self.pump_prime_button = Button(self.root,
                                        text="Prime Pump",
                                        command=self.prime_pump,
                                        width=button_width,
                                        height=button_big_height)
        self.pump_prime_button.grid(row=0, column=2, padx=1, sticky=sticky_to)

        self.save_reference_button = Button(self.root,
                                            text="Save as Reference",
                                            wraplength=80,
                                            fg='black',
                                            command=self.check_ref_number,
                                            width=button_width,
                                            height=button_big_height,
                                            state=NORMAL)
        self.save_reference_button.grid(row=0,
                                        column=3,
                                        padx=(1, 0),
                                        sticky=sticky_to)

        self.save_spectra_button = Button(
            self.root,
            text="Save as Spectra",
            wraplength=80,
            fg='black',
            command=self.check_scan_number_save_spectra,
            width=button_width,
            height=button_big_height,
            state=NORMAL)
        self.save_spectra_button.grid(row=0,
                                      column=4,
                                      padx=(1, 1),
                                      sticky=sticky_to)

        self.settings_button = Button(
            self.root,
            text="Settings",
            fg='black',
            command=lambda: self.window_popup(self.root),
            width=button_width,
            height=button_big_height)
        self.settings_button.grid(row=0,
                                  column=5,
                                  padx=(1, 1),
                                  sticky=sticky_to)

        self.quit_button = Button(self.root,
                                  text="Quit",
                                  fg='Red',
                                  command=self.quit_button,
                                  width=button_width,
                                  height=button_big_height)
        self.quit_button.grid(row=0, column=6, padx=1, sticky=sticky_to)

        #left side column of buttons
        self.water_acquire_button = Button(
            self.root,
            text="Acquire",
            command=lambda: self.func.water_acquire(save=False),
            width=button_width,
            height=button_big_height)
        self.water_acquire_button.grid(row=1,
                                       column=0,
                                       padx=1,
                                       pady=(0, 1),
                                       sticky=sticky_to)

        self.water_acquire_save_button = Button(
            self.root,
            text="Acquire and Save",
            command=lambda: self.func.water_acquire(save=True),
            wraplength=80,
            width=button_width,
            height=button_big_height)
        self.water_acquire_save_button.grid(row=2,
                                            column=0,
                                            padx=1,
                                            pady=(0, 1),
                                            sticky=sticky_to)

        self.seq_button = Button(
            self.root,
            text="Sequence",
            command=lambda: self.func.water_sequence(save=False),
            width=button_width,
            height=button_big_height)
        self.seq_button.grid(row=3,
                             column=0,
                             padx=1,
                             pady=(0, 1),
                             sticky=sticky_to)

        self.seq_save_button = Button(
            self.root,
            text="Sequence and Save",
            wraplength=80,
            command=lambda: self.func.water_sequence(save=True),
            width=button_width,
            height=button_big_height)
        self.seq_save_button.grid(row=4,
                                  column=0,
                                  padx=1,
                                  pady=(0, 1),
                                  sticky=sticky_to)

        self.ratio_view_button = Button(self.root,
                                        text="Ratio View",
                                        fg='black',
                                        wraplength=80,
                                        command=self.ratio_view_toggle,
                                        width=button_width,
                                        height=button_big_height,
                                        state=NORMAL)
        self.ratio_view_button.grid(row=5,
                                    column=0,
                                    padx=1,
                                    pady=(0, 1),
                                    sticky=sticky_to)

        self.add_remove_button = Button(self.root,
                                        text="Add/Remove Plots",
                                        fg='black',
                                        wraplength=85,
                                        state=NORMAL,
                                        command=self.func.add_remove_func,
                                        width=button_width,
                                        height=button_big_height)
        self.add_remove_button.grid(row=6,
                                    column=0,
                                    padx=1,
                                    pady=(0, 1),
                                    sticky=sticky_to)

        self.module_label = Label(self.root,
                                  wraplength=100,
                                  text="Module 2: ESS Pump",
                                  height=button_big_height,
                                  width=button_width,
                                  bg="sky blue")
        self.module_label.grid(row=7,
                               column=0,
                               padx=1,
                               pady=(0, 1),
                               sticky=sticky_to)

        # show module connected
        self.battery_frame = Frame(self.root, bg='sky blue', width=4)
        self.battery_frame.grid(row=0, column=7, padx=1, pady=1, sticky='nsew')

        # allow buttons and frames to resize with the resizing of the root window
        # need to change this to however many rows/columns you hav
        self.root.grid_columnconfigure((0, 1, 2, 3, 4, 5, 6, 7), weight=1)
        self.root.grid_rowconfigure((0, 1, 2, 3, 4, 5, 6, 7), weight=1)

        battery_width = 6

        self.battery_label_1 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_1.grid(row=0, column=0, padx=1, sticky='nsew')

        self.battery_label_2 = Label(self.battery_frame,
                                     text="%",
                                     font=battery_font,
                                     height=1,
                                     bg="green",
                                     width=battery_width)
        self.battery_label_2.grid(row=1, column=0, padx=1, sticky='nsew')

        self.battery_label_3 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_3.grid(row=2, column=0, padx=1, sticky='nsew')

        self.battery_label_4 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_4.grid(row=3, column=0, padx=1, sticky='nsew')

        self.scan_label = Label(self.battery_frame,
                                bg='sky blue',
                                text="Scan: ",
                                font=battery_font,
                                height=1,
                                width=battery_width,
                                wraplength=80)
        self.scan_label.grid(row=4, column=0, padx=1, sticky='nsew')

        self.battery_frame.grid_rowconfigure((0, 1, 2, 3, 4), weight=1)
        self.battery_frame.grid_columnconfigure((0), weight=1)

        # show module connected
        #messagebox.showinfo('Module #','Module 0: Base ESS System connected (No attachments)')

        # check battery percent from arduino
        def battery_percent_check():
            self.percent = self.func.battery_check()
            self.charging = False
            # check for charging and then add percent to array for averaging
            if int(self.percent) == 1000:
                self.charging = True
            self.battery_array.append(int(self.percent))
            if len(self.battery_array) > 10:
                del self.battery_array[0]

            #average battery_array
            self.percent = int(
                sum(self.battery_array) / (len(self.battery_array)))

            if self.charging:
                self.battery_label_1.configure(bg='green')
                self.battery_label_2.configure(font=battery_font,
                                               text="Charging",
                                               bg='green')
                self.battery_label_3.configure(bg='green')
                self.battery_label_4.configure(bg='green')
            else:
                if int(self.percent) >= 75:

                    self.battery_label_1.configure(bg='green')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='green')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 75 and int(self.percent) >= 50:
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='green')
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 50 and int(self.percent) >= 25:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='red')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 25 and int(self.percent) >= 15:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='red')
                    self.battery_label_3.configure(bg='red')
                    self.battery_label_4.configure(bg='yellow')
                else:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text="LOW",
                                                   bg='red')
                    self.battery_label_3.configure(bg='red')
                    self.battery_label_4.configure(bg='red')

                    error_top = Toplevel(self.root, bg="red")
                    message = Label(
                        error_top,
                        bg="white",
                        text="Low Battery! Plug In device and Save Data",
                        font=warning_font,
                        wraplength=250)
                    message.grid(row=0, column=0, padx=10, pady=10)
                    error_top.title("Warning")
                    error_top.lift()

                    error_top.after(3000, error_top.destroy)

            try:
                self.root.after(10000, battery_percent_check)
            except:
                pass

        battery_percent_check()
Ejemplo n.º 16
0
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent.parent)
        self.parent = parent
        self.withdraw()
        self.title('Simulation')
        self.img = tk.PhotoImage(file=SignalIntegrity.App.IconsBaseDir +
                                 'AppIcon2.gif')
        self.tk.call('wm', 'iconphoto', self._w, self.img)
        self.protocol("WM_DELETE_WINDOW", self.onClosing)

        # the Doers - the holder of the commands, menu elements, toolbar elements, and key bindings
        self.WaveformSaveDoer = Doer(
            self.onWriteSimulatorToFile).AddHelpElement(
                'Control-Help:Save-Waveforms')
        # TODO: someday allow waveform reading
        self.WaveformReadDoer = Doer(
            self.onReadSimulatorFromFile).AddHelpElement(
                'Control-Help:Read-Waveforms').Activate(False)
        self.Matplotlib2tikzDoer = Doer(self.onMatplotlib2TikZ).AddHelpElement(
            'Control-Help:Output-to-LaTeX')
        # ------
        self.CalculationPropertiesDoer = Doer(
            self.onCalculationProperties).AddHelpElement(
                'Control-Help:Calculation-Properties')
        self.ExamineTransferMatricesDoer = Doer(
            self.onExamineTransferMatrices).AddHelpElement(
                'Control-Help:View-Transfer-Parameters')
        self.SimulateDoer = Doer(
            self.parent.parent.onCalculate).AddHelpElement(
                'Control-Help:Recalculate')
        # ------
        self.viewTimeDomain = tk.BooleanVar()
        self.viewTimeDomain.set(True)
        self.viewTimeDomainDoer = Doer(self.onViewTimeDomain)

        self.viewSpectralContent = tk.BooleanVar()
        self.viewSpectralContentDoer = Doer(self.onViewSpectralContent)

        self.viewSpectralDensity = tk.BooleanVar()
        self.viewSpectralDensityDoer = Doer(self.onViewSpectralDensity)

        # ------
        self.HelpDoer = Doer(self.onHelp).AddHelpElement(
            'Control-Help:Simulator-Open-Help-File')
        self.ControlHelpDoer = Doer(self.onControlHelp).AddHelpElement(
            'Control-Help:Simulator-Control-Help')
        self.PreferencesDoer = Doer(self.onPreferences).AddHelpElement(
            'Control-Help:Simulator-Preferences')
        # ------
        self.EscapeDoer = Doer(self.onEscape).AddKeyBindElement(
            self, '<Escape>').DisableHelp()

        # The menu system
        TheMenu = tk.Menu(self)
        self.config(menu=TheMenu)
        FileMenu = tk.Menu(self)
        TheMenu.add_cascade(label='File', menu=FileMenu, underline=0)
        self.WaveformSaveDoer.AddMenuElement(FileMenu,
                                             label="Save Waveforms",
                                             underline=0)
        self.WaveformReadDoer.AddMenuElement(FileMenu,
                                             label="Read Waveforms",
                                             underline=0)
        FileMenu.add_separator()
        self.Matplotlib2tikzDoer.AddMenuElement(FileMenu,
                                                label='Output to LaTeX (TikZ)',
                                                underline=10)
        # ------
        CalcMenu = tk.Menu(self)
        TheMenu.add_cascade(label='Calculate', menu=CalcMenu, underline=0)
        self.CalculationPropertiesDoer.AddMenuElement(
            CalcMenu, label='Calculation Properties', underline=12)
        self.ExamineTransferMatricesDoer.AddMenuElement(
            CalcMenu, label='View Transfer Parameters', underline=0)
        CalcMenu.add_separator()
        self.SimulateDoer.AddMenuElement(CalcMenu,
                                         label='Recalculate',
                                         underline=0)
        # ------
        ViewMenu = tk.Menu(self)
        TheMenu.add_cascade(label='View', menu=ViewMenu, underline=0)
        self.viewTimeDomainDoer.AddCheckButtonMenuElement(
            ViewMenu,
            label='View Time-domain',
            underline=5,
            onvalue=True,
            offvalue=False,
            variable=self.viewTimeDomain)
        self.viewSpectralContentDoer.AddCheckButtonMenuElement(
            ViewMenu,
            label='View Spectral Content',
            underline=14,
            onvalue=True,
            offvalue=False,
            variable=self.viewSpectralContent)
        self.viewSpectralDensityDoer.AddCheckButtonMenuElement(
            ViewMenu,
            label='View Spectral Density',
            underline=14,
            onvalue=True,
            offvalue=False,
            variable=self.viewSpectralDensity)
        # ------
        HelpMenu = tk.Menu(self)
        TheMenu.add_cascade(label='Help', menu=HelpMenu, underline=0)
        self.HelpDoer.AddMenuElement(HelpMenu,
                                     label='Open Help File',
                                     underline=0)
        self.ControlHelpDoer.AddMenuElement(HelpMenu,
                                            label='Control Help',
                                            underline=0)
        self.PreferencesDoer.AddMenuElement(HelpMenu,
                                            label='Preferences',
                                            underline=0)

        # The Toolbar
        ToolBarFrame = tk.Frame(self)
        ToolBarFrame.pack(side=tk.TOP, fill=tk.X, expand=tk.NO)
        iconsdir = SignalIntegrity.App.IconsDir + ''
        self.WaveformReadDoer.AddToolBarElement(
            ToolBarFrame,
            iconfile=iconsdir + 'document-open-2.gif').Pack(side=tk.LEFT,
                                                            fill=tk.NONE,
                                                            expand=tk.NO)
        self.WaveformSaveDoer.AddToolBarElement(
            ToolBarFrame,
            iconfile=iconsdir + 'document-save-2.gif').Pack(side=tk.LEFT,
                                                            fill=tk.NONE,
                                                            expand=tk.NO)
        tk.Frame(self, height=2, bd=2, relief=tk.RAISED).pack(side=tk.LEFT,
                                                              fill=tk.X,
                                                              padx=5,
                                                              pady=5)
        self.CalculationPropertiesDoer.AddToolBarElement(
            ToolBarFrame,
            iconfile=iconsdir + 'tooloptions.gif').Pack(side=tk.LEFT,
                                                        fill=tk.NONE,
                                                        expand=tk.NO)
        self.SimulateDoer.AddToolBarElement(
            ToolBarFrame,
            iconfile=iconsdir + 'system-run-3.gif').Pack(side=tk.LEFT,
                                                         fill=tk.NONE,
                                                         expand=tk.NO)
        tk.Frame(ToolBarFrame, height=2, bd=2,
                 relief=tk.RAISED).pack(side=tk.LEFT,
                                        fill=tk.X,
                                        padx=5,
                                        pady=5)
        self.HelpDoer.AddToolBarElement(
            ToolBarFrame,
            iconfile=iconsdir + 'help-contents-5.gif').Pack(side=tk.LEFT,
                                                            fill=tk.NONE,
                                                            expand=tk.NO)
        self.ControlHelpDoer.AddToolBarElement(ToolBarFrame,
                                               iconfile=iconsdir +
                                               'help-3.gif').Pack(side=tk.LEFT,
                                                                  fill=tk.NONE,
                                                                  expand=tk.NO)

        labelFrame = tk.Frame(self)
        labelFrame.pack(side=tk.TOP, fill=tk.X, expand=tk.NO)
        self.plotLabel = tk.Label(labelFrame, fg='black')
        self.plotLabel.pack(fill=tk.X)

        plotWidth = SignalIntegrity.App.Preferences['Appearance.PlotWidth']
        plotHeight = SignalIntegrity.App.Preferences['Appearance.PlotHeight']
        plotDPI = SignalIntegrity.App.Preferences['Appearance.PlotDPI']

        self.f = Figure(figsize=(plotWidth, plotHeight), dpi=plotDPI)

        self.plt = self.f.add_subplot(111)
        self.plt.set_xlabel('time (ns)')
        self.plt.set_ylabel('amplitude')

        self.waveformList = None
        self.waveformNamesList = None
        self.canvas = FigureCanvasTkAgg(self.f, master=self)
        #canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.TOP,
                                         fill=tk.BOTH,
                                         expand=tk.YES)

        toolbar = NavigationToolbar2Tk(self.canvas, self)
        toolbar.update()
        toolbar.pan()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        controlsFrame = tk.Frame(self)
        tk.Button(controlsFrame, text='autoscale',
                  command=self.onAutoscale).pack(side=tk.LEFT,
                                                 expand=tk.NO,
                                                 fill=tk.X)
        controlsFrame.pack(side=tk.TOP, fill=tk.X, expand=tk.NO)

        try:
            try:
                from tikzplotlib import save as tikz_save
            except:
                try:
                    from matplotlib2tikz import save as tikz_save
                except:
                    self.Matplotlib2tikzDoer.Activate(False)
        except:
            self.Matplotlib2tikzDoer.Activate(False)

        self.ExamineTransferMatricesDoer.Activate(False)
        self.SimulateDoer.Activate(False)

        self.geometry(
            "%+d%+d" %
            (self.parent.parent.root.winfo_x() +
             self.parent.parent.root.winfo_width() / 2 -
             self.winfo_width() / 2, self.parent.parent.root.winfo_y() +
             self.parent.parent.root.winfo_height() / 2 -
             self.winfo_height() / 2))
Ejemplo n.º 17
0
    def plotTest(self, directory, currentfile, bounding, subpathing, binpathing, framerate):
        global fps
        global threshold
        global binText
        fps = framerate
        x = []
        y = []
        afflictFile = open(directory + "/" + str(fps) + "FPS AfflictData.csv", "w+")
        afflictFile.write("Time(M),%Change, Af-Area(mm^2)\n")
        imi = str(subpathing) + "/isframe0.jpg"
        imiread = cv2.imread(imi)
        imireadGrayscale = cv2.cvtColor(imiread, cv2.COLOR_BGR2GRAY)
        retval, binarizedimi = cv2.threshold(imireadGrayscale, 75, 255, cv2.THRESH_BINARY)  # +cv2.THRESH_OTSU)
        cv2.imwrite(str(binpathing) + "/binarizedimi0.jpg", binarizedimi)
        binarizedimipath = str(binpathing) + "/binarizedimi0.jpg"
        w = 0
        for i in range(bounding):
            if testCancelled:
                return -1
            im = str(subpathing) + "/isframe" + str(i) + ".jpg"
            # print("Frame difference with initial " + str(i + 1))
            imread = cv2.imread(im)
            imreadGrayscale = cv2.cvtColor(imread, cv2.COLOR_BGR2GRAY)
            retval, binarizedim = cv2.threshold(imreadGrayscale, 75, 255, cv2.THRESH_BINARY)  # +cv2.THRESH_OTSU)
            cv2.imwrite(str(binpathing) + "/binarizedim" + str(i) + ".jpg", binarizedim)
            binarizedimpath = str(binpathing) + "/binarizedim" + str(i) + ".jpg"
            percent = imgcmp.image_diff_percent(binarizedimpath, binarizedimipath)
            # print("Percent of afflicted pixels in subtract: " + str(percent))
            x.append((i / (fps)) / 60)  # points on xaxis##########################################
            afflictFile.write(str((i / (fps)) / 60) + ",")  #########################################
            if percent >= threshold:
                y.append(percent)
                afflictFile.write(str(percent) + "," + str(percent / 100.0 * 0.485) + "\n")
                binText.append("%Affliction between Initial and Frame " + str(i + 1) + ":\n  - " + str(percent) + " - Appended Percent\n\n")  # printing if frame has been read
                self.consoleTableBin.configure(state="normal")
                self.consoleTableBin.insert(tk.INSERT, binText[i])
                self.consoleTableBin.see(tk.END)
                self.consoleTableBin.configure(state="disabled")
                self.programLoadingBar['value'] += 1
                self.programLoadingBar.update()
                self.update_idletasks()
                self.update()
                # print("Appended percent.")
                if w == 0:
                    w = percent
                x[i] -= w
            else:
                y.append(0)
                afflictFile.write("0,0\n")
                binText.append("%Affliction between Initial and Frame " + str(i + 1) + ":\n  - " + str(percent) + " - Appended Zero\n\n")
                self.consoleTableBin.configure(state="normal")
                self.consoleTableBin.insert(tk.INSERT, binText[i])
                self.consoleTableBin.see(tk.END)
                self.consoleTableBin.configure(state="disabled")
                self.update_idletasks()
                self.update()
        afflictFile.close()
        #    plt.plot(x, y)
        #    plt.xlabel('Time (secs)')#.1,.2,.3,etc.
        #    plt.ylabel('% area covered')
        #    plt.axis([0, bounding/10, 0, 0.5])
        #    plt.show()

        current = currentfile

        self.data1x = x
        self.data1y = y

        # root = tkinter.Tk()
        # root.wm_title("Embedding in Tk")

        # This is oneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
        # self.fig = Figure(figsize=(7, 6), dpi=100)
        # self.fig.add_subplot(111).plot(data1x, data1y)
        # axes = self.fig.get_axes()
        # ax1 = axes[0]

        self.fig, ax1 = plt.subplots()
        ax1.set_title("% Area Change vs Current vs Time", fontweight='bold')

        green = 'tab:green'
        ax1.set_xlabel('Time (Min)', fontweight='bold', labelpad=10)
        ax1.set_ylabel('% Area Covered', color=green, fontweight='bold', labelpad=10)
        ax1.plot(self.data1x, self.data1y, color=green)
        ax1.tick_params(axis='y', labelcolor=green, color=green)
        for tick in ax1.xaxis.get_major_ticks():
            tick.label1.set_fontweight('bold')
        for tick in ax1.yaxis.get_major_ticks():
            tick.label1.set_fontweight('bold')

        ax2 = ax1.twinx()

        self.data2x = []
        self.data2y = []
        with open(current) as f:
            reader = csv.reader(f, delimiter=',', quotechar='"')
            for row in reader:
                try:
                    self.data2x.append(float(row[0]))
                except:
                    pass
                try:
                    self.data2y.append(float(row[1]) * 1000000)
                except:
                    pass

        blue = 'tab:blue'
        ax2.set_ylabel('Current (μA)', color=blue, fontweight='bold',
                       labelpad=10)  # we already handled the x-label with ax1
        ax2.plot(self.data2x, self.data2y, color=blue)
        ax2.tick_params(axis='y', labelcolor=blue, color=blue)
        for tick in ax2.yaxis.get_major_ticks():
            tick.label2.set_fontweight('bold')
        for tick in ax2.xaxis.get_major_ticks():
            tick.label2.set_fontweight('bold')
        # ax2.set_aspect(1.5)
        self.fig.set_dpi(150)
        self.fig.tight_layout()
        tend1 = time.time()
        # plt.show()
        plt.savefig(directory + "/" + str(fps) + " Graph.jpg")
        # plt.grid()
        # plt.gcf().canvas.draw()
        # self.fig = plt.figure()
        # plt.axvline(x=20)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.FGraph)  # A tk.DrawingArea.
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        # self.fig.canvas.callbacks.connect('button_press_event', self.on_click)
        self.fig.canvas.callbacks.connect('button_release_event', self.on_click)
        # self.fig.canvas.callbacks.connect('motion_notify_event', self.on_click)



        self.currentLocationLine, v = plt.plot(0, 0, min(self.data2y), max(self.data2y), color='red', linewidth=2)

        toolbar = NavigationToolbar2Tk(self.canvas, self.FGraph)
        toolbar.update()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        if showingGraph:
            self.showOrHideGraph()
            self.showOrHideGraph()
        else:
            self.showOrHideGraph()
        return tend1
 def __init__(self, canvas, window):
     self.canvas = canvas
     self.window = window
     NavigationToolbar2Tk.__init__(self, canvas, window)
    def __init__(self):
        # VARIABLE SETUP
        # These variables are assigned values in the go() function.
        # Initialised in __init__ for better readability.
        self.material_list = None
        self.thickness = None
        self.total_thickness = None
        self.me = None
        self.mhh = None
        self.mlh = None
        self.Eg = None
        self.dielectric = None
        self.x = None
        self.V = None
        self.T = None
        self.eigvals = None
        self.eigvects = None
        self.N_points = None
        self.N_states = None
        self.particle = None
        self.num_materials = 1
        self.VB = None
        self.V_VB = None
        self.eigvals_VB = None
        self.eigvects_VB = None

        self.reset_settings()

        # TKINTER SETUP
        self.root = tk.Tk()
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.title('Band Structure Calculator')
        # self.root.state('zoomed') # Uncomment to open fullscreen
        self.root.wm_iconbitmap('icon.ico')

        # Add top menu toolbar
        self.menu = tk.Menu(self.root)
        self.root.config(menu=self.menu)
        self.file_menu = tk.Menu(self.menu, tearoff=False)
        self.menu.add_cascade(label='File', menu=self.file_menu)
        self.file_menu.add_command(label='New calculation...',
                                   command=self.restart)
        self.file_menu.add_separator()
        self.file_menu.add_command(label='Exit', command=self.root.destroy)

        self.options_menu = tk.Menu(self.menu, tearoff=False)
        self.menu.add_cascade(label='Settings', menu=self.options_menu)
        self.options_menu.add_cascade(label='Adjust Settings',
                                      command=self.adjust_settings)
        self.options_menu.add_cascade(label='Reset Defaults',
                                      command=self.reset_settings)

        # LEFT HAND SIDE
        self.LHS = tk.Frame(self.root)
        self.LHS.grid(row=0, column=0, sticky='news')
        self.vcmd = (self.LHS.register(self.validate_entry), '%P')
        # Temperature box
        temp_frame = tk.Frame(self.LHS)
        temp_frame.grid(row=0, column=0, columnspan=7)
        temperature_label = tk.Label(temp_frame, text='Temperature (K)')
        temperature_label.grid(row=0, column=0, padx=10, pady=5, sticky='n')
        self.temperature_entry = tk.Entry(temp_frame,
                                          validate='key',
                                          validatecommand=self.vcmd)
        self.temperature_entry.bind('<KeyRelease>', self.set_temperature)
        self.temperature_entry.grid(row=0, column=1)

        # Valence Band tickbox
        self.VB = tk.BooleanVar()
        self.VB.set(False)
        valence_band_label = tk.Label(temp_frame,
                                      text='Include '
                                      'Valence Band?')
        valence_band_label.grid(row=0,
                                column=2,
                                padx=(20, 10),
                                pady=5,
                                sticky='n')
        self.valence_band_tickbox = tk.Checkbutton(temp_frame,
                                                   onvalue=True,
                                                   offvalue=False,
                                                   variable=self.VB)
        self.valence_band_tickbox.grid(row=0, column=3)

        # Labels for adding in materials
        material_label = tk.Label(self.LHS, text='Material')
        material_label.grid(row=1, column=0, pady=10)
        x_label = tk.Label(self.LHS, text='x')
        x_label.grid(row=1, column=1, pady=10)
        thickness_label = tk.Label(self.LHS, text='Thickness\n(nm)')
        thickness_label.grid(row=1, column=2, pady=10)
        Eg_label = tk.Label(self.LHS, text='Eg\n(eV)')
        Eg_label.grid(row=1, column=3, pady=10)
        me_label = tk.Label(self.LHS, text='me\n(m0)')
        me_label.grid(row=1, column=4, pady=10)
        mh_label = tk.Label(self.LHS, text='mh\n(m0)')
        mh_label.grid(row=1, column=5, pady=10)
        mlh_label = tk.Label(self.LHS, text='mlh\n(m0)')
        mlh_label.grid(row=1, column=6, pady=10)
        dielectric_label = tk.Label(self.LHS, text=u'\u03f5')
        dielectric_label.grid(row=1, column=7, pady=10)

        # Set material parameters
        self.material_choices = [
            'InSb', 'GaAs', u'Al\u2093Ga\u208d\u2081\u208b\u2093\u208eAs',
            'AlAs', 'InP', 'InAs', 'GaSb', 'Custom'
        ]

        self.materials_dropdown = [
            ttk.Combobox(self.LHS,
                         state='disabled',
                         values=self.material_choices,
                         width=10)
        ]
        self.materials_dropdown[0].bind('<<ComboboxSelected>>',
                                        self.insert_parameters)
        self.x_entry = [
            tk.Entry(self.LHS,
                     validate='key',
                     state='disabled',
                     validatecommand=self.vcmd,
                     width=10)
        ]
        self.x_entry[0].bind('<KeyRelease>', self.insert_parameters)
        self.thickness_entry = [
            tk.Entry(self.LHS,
                     state='disabled',
                     validate='key',
                     validatecommand=self.vcmd,
                     width=10)
        ]
        self.Eg_entry = [
            tk.Entry(self.LHS,
                     state='disabled',
                     validate='key',
                     validatecommand=self.vcmd,
                     width=10)
        ]
        self.me_entry = [
            tk.Entry(self.LHS,
                     state='disabled',
                     validate='key',
                     validatecommand=self.vcmd,
                     width=10)
        ]
        self.mh_entry = [
            tk.Entry(self.LHS,
                     state='disabled',
                     validate='key',
                     validatecommand=self.vcmd,
                     width=10)
        ]
        self.mlh_entry = [
            tk.Entry(self.LHS,
                     state='disabled',
                     validate='key',
                     validatecommand=self.vcmd,
                     width=10)
        ]
        self.dielectric_entry = [
            tk.Entry(self.LHS,
                     state='disabled',
                     validate='key',
                     validatecommand=self.vcmd,
                     width=10)
        ]

        self.materials_dropdown[0].grid(row=2,
                                        column=0,
                                        padx=(5, 2),
                                        pady=(4, 0))
        self.x_entry[0].grid(row=2, column=1, padx=2, pady=(4, 0))
        self.thickness_entry[0].grid(row=2, column=2, padx=2, pady=(4, 0))
        self.Eg_entry[0].grid(row=2, column=3, padx=2, pady=(4, 0))
        self.me_entry[0].grid(row=2, column=4, padx=2, pady=(4, 0))
        self.mh_entry[0].grid(row=2, column=5, padx=2, pady=(4, 0))
        self.mlh_entry[0].grid(row=2, column=6, padx=2, pady=(4, 0))
        self.dielectric_entry[0].grid(row=2,
                                      column=7,
                                      padx=(2, 5),
                                      pady=(4, 0))

        # Button to add in new layers
        self.add_layer_button = tk.Button(self.LHS,
                                          command=self.add_layer,
                                          text='+',
                                          padx=5)
        self.add_layer_button.grid(row=3, column=0, pady=5)
        self.remove_layer_button = tk.Button(self.LHS,
                                             command=self.remove_layer,
                                             text='-',
                                             state='disabled',
                                             padx=8)
        self.remove_layer_button.grid(row=3, column=7, pady=5)

        # Calculate Potential Button and GO! button
        self.calc_pot_button = tk.Button(self.LHS,
                                         command=self.calculate_potential,
                                         text='Calculate Potential',
                                         state='disabled',
                                         padx=5,
                                         pady=5)
        self.calc_pot_button.grid(row=4, column=0, columnspan=4)
        self.go_button = tk.Button(self.LHS,
                                   command=self.go,
                                   text='GO!',
                                   state='disabled',
                                   padx=5,
                                   pady=5)
        self.go_button.grid(row=4, column=4, columnspan=4)

        # RIGHT HAND SIDE
        self.RHS = tk.Frame(self.root)
        self.RHS.grid(row=0, column=1, sticky='news')

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

        # matplotlib window
        fig = plt.Figure(figsize=(5.3, 4.3))
        self.figure = fig.add_subplot(111)
        self.figure.set_xlabel('Growth axis (nm)')
        self.figure.set_ylabel('E (eV)')
        self.figure.grid()
        self.plot = FigureCanvasTkAgg(fig, master=self.RHS)
        self.plot.get_tk_widget().grid(row=1,
                                       column=0,
                                       columnspan=5,
                                       sticky='nesw',
                                       padx=10,
                                       pady=(0, 10))

        self.toolbar_frame = tk.Frame(master=self.RHS)
        self.toolbar_frame.grid(row=0,
                                column=0,
                                columnspan=5,
                                padx=10,
                                pady=(10, 5),
                                sticky='news')
        self.toolbar = NavigationToolbar2Tk(self.plot, self.toolbar_frame)
        self.toolbar.update()
        self.toolbar.grid(row=0, column=0, sticky='ew')

        self.plot.draw()

        # mainloop
        self.root.mainloop()
Ejemplo n.º 20
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        # title and leading text #
        label = Label(self, text="Dashboard", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)

        # setting up the frame #
        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1)

        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=BOTTOM, fill=BOTH, expand=1)

        mb = Menubutton(self, text="Resume/Pause Updates")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_command(label="Resume",
                            command=lambda: load_chart('start'))
        mb.menu.add_command(label="Pause", command=lambda: load_chart('stop'))
        mb.pack(side='right')

        mb = Menubutton(self, text="Exchange")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_command(label="BTC-e",
                            command=lambda: change_exchange('BTC-e', 'btce'))
        mb.menu.add_command(
            label="Bitfinex",
            command=lambda: change_exchange('Bitfinex', 'bitfinex'))
        mb.menu.add_command(
            label="Bitstamp",
            command=lambda: change_exchange('Bitstamp', 'bitstamp'))
        mb.menu.add_command(label="Huobi",
                            command=lambda: change_exchange('Huobi', 'huobi'))
        mb.pack(side='left')

        mb = Menubutton(self, text="Data Time Frame")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_command(label="Tick",
                            command=lambda: change_time_frame('tick'))
        mb.menu.add_command(label="1 day",
                            command=lambda: change_time_frame('1d'))
        mb.menu.add_command(label="3 day",
                            command=lambda: change_time_frame('3d'))
        mb.menu.add_command(label="1 Week",
                            command=lambda: change_time_frame('7d'))
        mb.pack(side='left')

        mb = Menubutton(self, text="OHLC Interval")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_command(label="Tick",
                            command=lambda: change_time_frame('tick'))
        mb.menu.add_command(label="1 minute",
                            command=lambda: change_sample_size('1Min', 0.0005))
        mb.menu.add_command(label="5 minute",
                            command=lambda: change_sample_size('5Min', 0.003))
        mb.menu.add_command(label="15 minute",
                            command=lambda: change_sample_size('15Min', 0.008))
        mb.menu.add_command(label="30 minute",
                            command=lambda: change_sample_size('30Min', 0.016))
        mb.menu.add_command(label="1 Hour",
                            command=lambda: change_sample_size('1H', 0.032))
        mb.menu.add_command(label="3 Hour",
                            command=lambda: change_sample_size('3H', 0.096))

        mb.pack(side='left')

        mb = Menubutton(self, text="Top Indicator")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_command(label="None",
                            command=lambda: add_top_indicator('none'))
        mb.menu.add_command(label="RSI",
                            command=lambda: add_top_indicator('rsi'))
        mb.menu.add_command(label="MACD",
                            command=lambda: add_top_indicator('macd'))
        mb.pack(side='left')

        mb = Menubutton(self, text="Main Graph Indicator")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_command(label="None",
                            command=lambda: add_middle_indicator('none'))
        mb.menu.add_command(label="SMA",
                            command=lambda: add_middle_indicator('sma'))
        mb.menu.add_command(label="EMA",
                            command=lambda: add_middle_indicator('ema'))

        mb.pack(side='left')

        mb = Menubutton(self, text="Bottom Indicator")
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_command(label="None",
                            command=lambda: add_bottom_indicator('none'))
        mb.menu.add_command(label="RSI",
                            command=lambda: add_bottom_indicator('rsi'))
        mb.menu.add_command(label="MACD",
                            command=lambda: add_bottom_indicator('macd'))
        mb.pack(side='left')
Ejemplo n.º 21
0
    def __init__(self, master):
        global settings_file
        self.root = master
        self.root.title("ESS System Interface")
        full_screen = True
        if full_screen:
            self.root.attributes('-fullscreen',
                                 True)  # fullscreen on touchscreen
        else:
            self.root.geometry('800x480')  # actual size of RPi touchscreen
        #self.root.attributes('-fullscreen',True)
        self.root.configure(bg="sky blue")
        self.root.minsize(800, 480)  # min size the window can be dragged to

        self.open_loop_stop = None  # control open Loop button
        # parameters for buttons and frames
        #create all the buttons onto to the main window
        button_width = 8
        button_big_height = 4
        button_small_height = 3
        sticky_to = 'nsew'  # allows all buttons to resize

        # battery check functions
        self.percent = 0  # battery percent variable
        self.charging = False
        self.battery_array = []
        battery_font = tkFont.Font(family="Lucida Grande", size=9)
        label_font = tkFont.Font(family="Lucida Grande", size=12)
        warning_font = tkFont.Font(family="Lucida Grande", size=24)
        module_message = 'Module 0: Base ESS'
        # setup Serial port-
        ## Graphing Frame and fake plot
        self.graph_frame = Frame(self.root, background="white")
        self.graph_frame.grid(row=1,
                              column=1,
                              columnspan=7,
                              rowspan=5,
                              padx=1,
                              pady=3,
                              sticky=sticky_to)

        #initalize figure
        self.fig = plt.figure()
        plt.xlabel('Wavelength (nm)')
        plt.ylabel('ADC Counts')
        plt.xlim(300, 900)
        plt.ylim(0, 66500)
        plt.subplots_adjust(bottom=0.14, right=0.95, top=0.96)

        #initalize canvas for plotting
        self.canvas = FigureCanvasTkAgg(
            self.fig, master=self.graph_frame)  # A tk.DrawingArea.
        # create toolbar for canvas
        NavigationToolbar2Tk.toolitems = [
            t for t in NavigationToolbar2Tk.toolitems
            if t[0] not in ('Subplots', )
        ]
        self.toolbar = NavigationToolbar2Tk(self.canvas, self.graph_frame)
        self.toolbar.update()
        self.canvas.get_tk_widget().pack(fill=BOTH, expand=True)

        #toolbar.children['Subplots'].pack_forget()
        # create function object for calling functions
        settings_func = _Settings(settings_file)

        try:
            settings_func.create_settings()
        except:
            pass

        #(self.settings, self.wavelength) = settings_func.settings_read()
        self.func = functions(self.root, self.canvas, self.fig)
        #self.func.home()

        # allow buttons and frames to resize with the resizing of the root window
        self.root.grid_columnconfigure((0, 1, 2, 3, 4, 5, 6, 7), weight=1)
        self.root.grid_rowconfigure((0, 1, 2, 3, 4, 5, 6), weight=1)

        # __________________________    Create all buttons for the main GUI page _______________________________ #
        # with all their corresponding functions (command)
        self.quit_button = Button(self.root,
                                  text="Quit",
                                  fg='Red',
                                  command=self.quit_button,
                                  width=button_width,
                                  height=button_big_height)
        self.quit_button.grid(row=0, column=6, padx=1, sticky=sticky_to)

        self.help_button = Button(self.root,
                                  text="Help",
                                  fg='black',
                                  command=self.func.plot_selected,
                                  width=button_width,
                                  height=button_big_height)
        self.help_button.grid(row=0, column=5, sticky=sticky_to)

        self.settings_button = Button(
            self.root,
            text="Settings",
            fg='black',
            command=lambda: self.window_popup(self.root),
            width=button_width,
            height=button_big_height)
        self.settings_button.grid(row=0,
                                  column=4,
                                  padx=(1, 1),
                                  sticky=sticky_to)

        self.save_spectra_button = Button(self.root,
                                          text="Save as Spectra",
                                          wraplength=80,
                                          fg='black',
                                          command=self.check_spectra,
                                          width=button_width,
                                          height=button_big_height,
                                          state=NORMAL)
        self.save_spectra_button.grid(row=0,
                                      column=3,
                                      padx=(1, 1),
                                      sticky=sticky_to)

        self.save_reference_button = Button(self.root,
                                            text="Save as Reference",
                                            wraplength=80,
                                            fg='black',
                                            command=self.check_ref_number,
                                            width=button_width,
                                            height=button_big_height,
                                            state=NORMAL)
        self.save_reference_button.grid(row=0,
                                        column=2,
                                        padx=(1, 0),
                                        sticky=sticky_to)

        self.open_new_button = Button(self.root,
                                      text="New Experiment",
                                      wraplength=80,
                                      fg='black',
                                      command=self.func.open_new_experiment,
                                      width=button_width,
                                      height=button_big_height)
        self.open_new_button.grid(row=0,
                                  column=1,
                                  padx=(0, 1),
                                  sticky=sticky_to)

        self.open_experiment_button = Button(
            self.root,
            text="Open Experiment",
            wraplength=80,
            fg='black',
            command=self.check_scan_number_open_file,
            width=button_width,
            height=button_big_height)
        self.open_experiment_button.grid(row=0, column=0, sticky=sticky_to)

        self.acquire_button = Button(
            self.root,
            text="Acquire",
            wraplength=80,
            fg='black',
            command=lambda: self.func.acquire(save=False),
            width=button_width,
            height=button_big_height)
        self.acquire_button.grid(row=1,
                                 column=0,
                                 pady=(3, 1),
                                 sticky=sticky_to)

        self.acquire_save_button = Button(self.root,
                                          text="Acquire and Save",
                                          fg='black',
                                          wraplength=80,
                                          command=self.check_scan_number,
                                          width=button_width,
                                          height=button_big_height,
                                          state=NORMAL)
        self.acquire_save_button.grid(row=2,
                                      column=0,
                                      pady=(0, 1),
                                      sticky=sticky_to)

        self.autorange_button = Button(self.root,
                                       text="Auto-Range",
                                       fg='black',
                                       wraplength=80,
                                       command=self.func.autorange,
                                       width=button_width,
                                       height=button_big_height)
        self.autorange_button.grid(row=3,
                                   column=0,
                                   pady=(0, 5),
                                   sticky=sticky_to)

        self.open_loop_button = Button(self.root,
                                       text="Open Loop",
                                       fg='black',
                                       state=NORMAL,
                                       command=self.open_loop,
                                       width=button_width,
                                       height=button_big_height)
        self.open_loop_button.grid(row=4,
                                   column=0,
                                   pady=(5, 1),
                                   sticky=sticky_to)

        self.sequence_button = Button(
            self.root,
            text="Sequence",
            fg='black',
            wraplength=80,
            command=lambda: self.func.sequence(save=False),
            width=button_width,
            height=button_big_height)
        self.sequence_button.grid(row=5, column=0, sticky=sticky_to)

        self.sequence_save_button = Button(self.root,
                                           text="Sequence and Save",
                                           fg='black',
                                           wraplength=80,
                                           command=self.check_seq_number,
                                           width=button_width,
                                           height=button_big_height)
        self.sequence_save_button.grid(row=6, column=0, sticky=sticky_to)

        #self.scan_button = Button(self.root, text = "Scan", fg = 'black', wraplength = 80, command = lambda: self.func.scan(save = True), width = button_width, height = button_small_height)
        #self.scan_button.grid(row = 6, column = 1, padx = 1, sticky = sticky_to)

        self.ratio_view_button = Button(self.root,
                                        text="Ratio View",
                                        fg='black',
                                        wraplength=80,
                                        command=self.ratio_view_toggle,
                                        width=button_width,
                                        height=button_small_height,
                                        state=NORMAL)
        self.ratio_view_button.grid(row=6, column=1, padx=1, sticky=sticky_to)

        self.autoscale_button = Button(self.root,
                                       text="Autoscale",
                                       fg='black',
                                       wraplength=80,
                                       command=self.autoscale_toggle,
                                       width=button_width,
                                       height=button_small_height)
        self.autoscale_button.grid(row=6, column=2, padx=1, sticky=sticky_to)

        self.plot_selected_button = Button(self.root,
                                           text="Plot Selected",
                                           fg='black',
                                           wraplength=80,
                                           command=self.func.plot_selected,
                                           state=NORMAL,
                                           width=button_width,
                                           height=button_small_height)
        self.plot_selected_button.grid(row=6,
                                       column=3,
                                       padx=1,
                                       sticky=sticky_to)

        self.clear_button = Button(self.root,
                                   text="Clear",
                                   fg='black',
                                   wraplength=80,
                                   command=self.func.clear,
                                   width=button_width,
                                   height=button_small_height)
        self.clear_button.grid(row=6, column=4, padx=1, sticky=sticky_to)

        self.add_remove_button = Button(self.root,
                                        text="Add/Remove Plots",
                                        fg='black',
                                        wraplength=85,
                                        state=NORMAL,
                                        command=self.func.add_remove_func,
                                        width=button_width,
                                        height=button_small_height)
        self.add_remove_button.grid(row=6,
                                    column=5,
                                    columnspan=2,
                                    padx=5,
                                    pady=1,
                                    sticky=sticky_to)

        module_label = Label(self.root,
                             bg='sky blue',
                             text=module_message,
                             wraplength=80,
                             font=label_font)
        module_label.grid(row=6, column=7, padx=5, pady=1, sticky=sticky_to)

        #### Provide scan number in the top right of the GUI page
        self.scan_label = Label(self.root,
                                bg='sky blue',
                                text="Scan: ",
                                wraplength=80)
        self.scan_label.grid(row=0, column=7, padx=5, pady=1, sticky='nsew')

        ####### Battery label depending if its the battery powered system
        '''
Ejemplo n.º 22
0
    def calcShow(self):
        i = self.controller.shared_data['comboExample'].current(
        )  # Kollar vilken datahandler som är vald i dropdownen
        datahandlers = [
            dh.dateMean, dh.nightMean, dh.dayMean, dh.dayHours, dh.nightHours,
            dh.dateHours
        ]
        df = datahandlers[i](
            self.controller.shared_data["dataPath"])  # Kör valt alternativ

        shewhartoc = s.shewhart(df)
        cusumoc = c.cusum(df)
        ewmaoc = e.o_ewma(df)

        fig, (ax1, ax2, ax3) = plt.subplots(1, 3)

        ax1.set_title('Shewhart', fontsize=30)
        df.plot(y='Flow (l/s)',
                color='blue',
                label='Vattenflöde',
                ax=ax1,
                fontsize=11)
        df.plot(y='avg',
                color='black',
                label='Medelflöde',
                ax=ax1,
                fontsize=11)  #Plottar en medelvärdeslinje
        df.plot(y='UCL', color='red', ax=ax1, fontsize=11)  #Plottar UCL
        df.plot(y='LCL', color='red', ax=ax1, fontsize=11)  #Plottar LCL
        ax1.set_xlabel("Datum", fontsize=20)
        ax1.set_ylabel("Liter per sekund", fontsize=18)
        ax1.legend(loc=1, fontsize='x-large')

        ax2.set_title('CUSUM', fontsize=30)
        df.plot(y='cusum', color='green', label='CUSUM', ax=ax2,
                fontsize=11)  # Lägg till CUSUMen i plotten.
        df.plot(y='v-mask',
                color='red',
                label='Ur kontroll',
                ax=ax2,
                linewidth=2,
                fontsize=11)  # Gör de delar som är ur kontroll röda
        ax2.set_xlabel("Datum", fontsize=20)
        ax2.set_ylabel(r'$\sigma$', fontsize=25)
        ax2.legend(loc=1, fontsize='x-large')

        ax3.set_title('EWMA', fontsize=30)
        df.plot(y='EWMA', color='green', ax=ax3, fontsize=11)  # Plotta EWMA
        df.plot(y='UCL_EWMA', color='red', label='UCL', ax=ax3, fontsize=11)
        df.plot(y='LCL_EWMA', color='red', label='LCL', ax=ax3, fontsize=11)
        ax3.set_xlabel("Datum", fontsize=20)
        ax3.set_ylabel("Liter per sekund", fontsize=18)
        ax3.legend(loc=1, fontsize='x-large')

        fig.autofmt_xdate()

        try:  # Kollar om det redan finns en plot, i så fall förstörs den innan en ny skapas
            self.canvas.get_tk_widget().pack_forget()
        except AttributeError:
            pass

        try:
            self.toolbar.destroy()
        except AttributeError:
            pass

        try:  # Kollar om det redan finns en plot, i så fall förstörs den innan en ny skapas
            self.controller.shared_data['canvas2'].destroy()
        except AttributeError:
            pass

        try:  # Kollar om det redan finns en plot, i så fall förstörs den innan en ny skapas
            self.outOfControlDates.destroy()
        except AttributeError:
            pass

        self.canvas = FigureCanvasTkAgg(fig, master=self)  # A tk.DrawingArea.
        self.toolbar = NavigationToolbar2Tk(
            self.canvas,
            self)  # Navigationbar för att kunna zooma och spara plotten mm
        self.toolbar.update()

        self.outOfControlDates = [
        ]  # En lista som de tre listorna från diagrammen slås ihop i
        for shewDate in shewhartoc.values:
            self.outOfControlDates.append(shewDate)

        for cuDate in cusumoc.values:
            self.outOfControlDates.append(cuDate)

        for ewDate in ewmaoc.values:
            self.outOfControlDates.append(ewDate)

        datesWithCount = [
        ]  # Ny lista där datumen läggs in som tuple tillsammans med hur många diagram som säger samma datum
        for entry in self.outOfControlDates:
            times = self.outOfControlDates.count(entry)
            datesWithCount.append((entry, times))

        datesWithCount = list(
            dict.fromkeys(datesWithCount))  # Removes duplicates
        datesWithCount.sort()
        #for dates in datesWithCount:
        #print(dates[0])
        #print(dates[1])

        try:
            self.ocdText.destroy()
        except AttributeError:
            pass

        self.controller.shared_data['canvas2'] = tk.Canvas(width=400,
                                                           height=800,
                                                           bg='white')
        # Ett sätt att göra fyrkant:
        #self.controller.shared_data['canvas2'].create_rectangle(30, 10, 120, 80,
        #outline="#fb0", fill="#fb0")
        self.controller.shared_data['canvas2'].create_text(500,
                                                           0,
                                                           width=800,
                                                           text=datesWithCount)

        scrollbar = tk.Scrollbar(
            self.controller.shared_data['canvas2']
        )  # En scrollbar eftersom datumen just nu är på så liten yta
        scrollbar.pack(side="right", fill="y")
        scrollbar.config(command=self.controller.shared_data['canvas2'].yview)
        self.controller.shared_data['canvas2'].configure(
            yscrollcommand=scrollbar.set)

        self.controller.shared_data['canvas2'].pack(side='bottom',
                                                    fill="both",
                                                    expand=True)
        self.canvas.get_tk_widget().pack(fill='both', expand=True)
Ejemplo n.º 23
0
    def plot(self):
        "choix_fig_XY = 0 quand le traitement d'image n'a pas encore été effectué, et = 1 après le traitement. le graphe apparait après pression du bouton profils"
        try:
            for widget in self.cadre_plots.winfo_children():
                widget.destroy()
        except:
            pass
        if self.choix_fig == 0:
            self.fig_XY = Figure()
        else:
            try:
                self.photo2
            except:
                tk.messagebox.showerror(
                    "Graphiques impossibles",
                    "Il faut traiter le faisceau pour l'affichage des graphs. \n Pour cela cliquez sur le bouton traitement après ce message."
                )
                self.fig_XY = Figure()
                return self.fig_XY

            self.fig_XY = Figure()
            self.fig_width = self.cadre_plots.winfo_width()
            self.fig_height = self.cadre_plots.winfo_height()

            if self.choix_fig == 1:
                self.fig_XY, x, y = self.trmt.trace_profil(
                    self.dpi, self.fig_width, self.fig_height)
                self.titre_gauss1.set("Gaussienne X :")
                self.titre_gauss2.set("Gaussienne Y :")
                self.gauss_amp1.set('Amplitude: {} +\- {}'.format(
                    x[0] * self.pixel_size,
                    np.sqrt(x[3][0]) * self.pixel_size))
                self.gauss_mean1.set('Mean: {} +\- {}'.format(
                    x[1] * self.pixel_size,
                    np.sqrt(x[3][1]) * self.pixel_size))
                self.gauss_stddev1.set('Standard Deviation: {} +\- {}'.format(
                    x[2] * self.pixel_size,
                    np.sqrt(x[3][2]) * self.pixel_size))
                self.gauss_amp2.set('Amplitude: {} +\- {}'.format(
                    y[0] * self.pixel_size,
                    np.sqrt(y[3][0]) * self.pixel_size))
                self.gauss_mean2.set('Mean: {} +\- {}'.format(
                    y[1] * self.pixel_size,
                    np.sqrt(y[3][1]) * self.pixel_size))
                self.gauss_stddev2.set('Standard Deviation: {} +\- {}'.format(
                    y[2] * self.pixel_size,
                    np.sqrt(y[3][2]) * self.pixel_size))
            if self.choix_fig == 2:
                self.fig_XY, g, p = self.trmt.trace_ellipse(
                    self.dpi, self.fig_width, self.fig_height)
                self.titre_gauss1.set("Gaussienne ellipse G :")
                self.titre_gauss2.set("Gaussienne ellipse P :")
                self.gauss_amp1.set('Amplitude: {} +\- {}'.format(
                    g[0] * self.pixel_size,
                    np.sqrt(g[3][0]) * self.pixel_size))
                self.gauss_mean1.set('Mean: {} +\- {}'.format(
                    g[1] * self.pixel_size,
                    np.sqrt(g[3][1]) * self.pixel_size))
                self.gauss_stddev1.set('Standard Deviation: {} +\- {}'.format(
                    g[2] * self.pixel_size,
                    np.sqrt(g[3][2]) * self.pixel_size))
                self.gauss_amp2.set('Amplitude: {} +\- {}'.format(
                    p[0] * self.pixel_size,
                    np.sqrt(p[3][0]) * self.pixel_size))
                self.gauss_mean2.set('Mean: {} +\- {}'.format(
                    p[1] * self.pixel_size,
                    np.sqrt(p[3][1]) * self.pixel_size))
                self.gauss_stddev2.set('Standard Deviation: {} +\- {}'.format(
                    p[2] * self.pixel_size,
                    np.sqrt(p[3][2]) * self.pixel_size))
            if self.choix_fig == 3:
                self.fig_XY, d = self.trmt.plot_2D(self.dpi, self.fig_width,
                                                   self.fig_height)
                self.titre_gauss1.set("Gaussienne 2D :")
                self.titre_gauss2.set("")
                self.gauss_amp1.set('Amplitude: {} +\- {}'.format(
                    d[0] * self.pixel_size,
                    np.sqrt(d[6][0]) * self.pixel_size))
                self.gauss_mean1.set('Mean x: {} +\- {}'.format(
                    d[1] * self.pixel_size,
                    np.sqrt(d[6][1]) * self.pixel_size))
                self.gauss_stddev1.set('Mean y: {} +\- {}'.format(
                    d[2] * self.pixel_size,
                    np.sqrt(d[6][1]) * self.pixel_size))
                self.gauss_amp2.set('Standard Deviation x: {} +\- {}'.format(
                    d[3] * self.pixel_size,
                    np.sqrt(d[6][2]) * self.pixel_size))
                self.gauss_mean2.set('Standard Deviation y: {} +\- {}'.format(
                    d[4] * self.pixel_size,
                    np.sqrt(d[6][2]) * self.pixel_size))
                self.gauss_stddev2.set('Theta: {}'.format(d[5]) *
                                       self.pixel_size)

        #cadre affichage profils
        self.disp_XY = FigureCanvasTkAgg(self.fig_XY, self.cadre_plots)
        self.toolbar = NavigationToolbar2Tk(self.disp_XY,
                                            self.cadre_plots,
                                            pack_toolbar=False)
        self.toolbar.grid(row=0, column=0)
        self.toolbar.update()
        self.cadre_disp_XY = self.disp_XY.get_tk_widget()
        self.cadre_disp_XY.grid(row=1, column=0, sticky="NSEW")
        return self.fig_XY
Ejemplo n.º 24
0
 def load_graph(self, csv_filepath, start_date, end_date,
                display_moving_average_value, display_bollinger_bands,
                display_support_resistance_breaks, display_wbottom_mtop):
     #Read the csv file
     idf = pd.read_csv(csv_filepath, index_col=0, parse_dates=True)
     #Grabs a specified date range from the input data frame
     df = idf.loc[start_date:end_date]
     #Shows the 20-day moving average. Allows user to turn on/off the display of 20-day moving average
     #mav = (20) means to show the 20 days moving average
     mav = ()
     if display_moving_average_value == 1:
         mav = (20)
     ap0 = []
     #Shows the bollinger bands. Allows user to turn on/off the display of bollinger bands
     if display_bollinger_bands == 1:
         ap0 = [
             mpf.make_addplot(df['UpperB'],
                              color='g'),  # uses panel 0 by default
             mpf.make_addplot(df['LowerB'],
                              color='b'),  # uses panel 0 by default
         ]
     #Shows the support/resistance breaks. Allows user to turn off the display of support/resistance breaks
     seq_of_seq_of_points = []
     colors = []
     linewidths = []
     if display_support_resistance_breaks == 1:
         #The 1st value is the x axis, the 2nd value is the y axis
         # Yaxis value is the middle of the rectangle
         seq_of_seq_of_points += [[('2011-07-29', 129.29),
                                   ('2011-08-10', 112.81)],
                                  [('2011-09-22', 113.85),
                                   ('2011-10-04', 110.24)],
                                  [('2011-11-21', 120.29),
                                   ('2011-11-25', 116.65)],
                                  [('2011-07-01', 132.40),
                                   ('2011-07-07', 135.29)]]
         #corresponds to the seq_of_seq_of_points on top. This means the first 3 values will be highlighted red, 4th value will be highlighted green
         colors += ['r', 'r', 'r', 'g']
         #Sets how thick the line is
         linewidths += [20, 20, 20, 20]
     #Shows the w-bottoms/m-tops as vertical lines. Allows user to turn on/off the display of w-bottoms/m-tops
     seq_of_points = []
     if display_wbottom_mtop == 1:
         #the first value is the start of wbottom and second value is the end of wbottom
         seq_of_points += ['2011-11-15', '2012-02-03']
     #Refer to https://github.com/matplotlib/mplfinance/blob/master/examples/panels.ipynb and https://github.com/matplotlib/mplfinance/blob/master/examples/using_lines.ipynb for examples
     #returnfig = True to return f (figure) for tkinter to draw it
     f, ax = mpf.plot(df,
                      figsize=(14, 6),
                      type='candle',
                      mav=mav,
                      volume=True,
                      addplot=ap0,
                      alines=dict(alines=seq_of_seq_of_points,
                                  colors=colors,
                                  linewidths=linewidths,
                                  alpha=0.35),
                      vlines=dict(vlines=seq_of_points,
                                  linestyle='-.',
                                  alpha=1),
                      returnfig=True)
     #Normally its use plt.show(), but we want to show it on tkinter window directly
     #Use canvas to draw on the tkinter window directly
     canvas = FigureCanvasTkAgg(f, self)
     canvas.draw()
     #These 2 lines of code seems to be the same, so use either one
     canvas.get_tk_widget().grid(row=6, column=0, columnspan=8)
     #canvas._tkcanvas.grid(row=6, column=0, columnspan=8)
     #Adds a navigation toolbar for the graph (zoom, pan around etc)
     toolbarFrame = tk.Frame(self)
     #As the navigation toolbar will show a text value whenever the user hovers over the graph, it will resize column = 0, causing the input boxes on top to move right
     #To fix this, we allow it to occupy more columns and align it to the left using sticky = "W"
     toolbarFrame.grid(row=7, column=0, sticky="W", columnspan=8)
     toolbar = NavigationToolbar2Tk(canvas, toolbarFrame)
     toolbar.update()
Ejemplo n.º 25
0
    window.update()


window = tk.Tk()
window.title('scanning video')
window.geometry('1024x800')

font = tf.Font(size=12)

frame_left = Frame(window)
frame_left.pack(side=LEFT, fill=BOTH, expand=YES)

fig = Figure(figsize=(8, 4), dpi=72)
canvas = FigureCanvasTkAgg(fig, master=frame_left)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=YES)
toolbar = NavigationToolbar2Tk(canvas, frame_left)
toolbar.update()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=YES)

scrollbar_display = Scale(frame_left,
                          orient=HORIZONTAL,
                          from_=0,
                          to=500,
                          resolution=1,
                          command=display_frames)
scrollbar_display.pack(fill=X)

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

frame_right = Frame(window)
frame_right.pack(side=LEFT, padx=10, expand=YES)
Ejemplo n.º 26
0
    def __init__(self, master):
        global settings_file
        self.root = master
        self.root.title("ESS Module 7 Frame")
        full_screen = False
        if full_screen:
            self.root.attributes('-fullscreen',
                                 True)  # fullscreen on touchscreen
        else:
            self.root.geometry('800x480')  # actual size of RPi touchscreen
        #self.root.attributes('-fullscreen',True)
        self.root.configure(bg="sky blue")
        self.root.minsize(800, 480)  # min size the window can be dragged to

        self.root.tk.call('wm', 'iconphoto', self.root._w,
                          PhotoImage(file="/home/pi/Desktop/BMO_Lab/ESS_png"))

        self.open_loop_stop = None  # control open Loop button

        # parameters for buttons and frames
        #create all the buttons onto to the main window
        button_width = 10
        button_big_height = 4
        button_small_height = 3
        sticky_to = 'nsew'  # allows all buttons to resize

        # setup Serial port-
        ## Graphing Frame and fake plot
        self.graph_frame = Frame(self.root, background="white")
        self.graph_frame.grid(row=2, column=0, sticky=sticky_to)

        #initalize figure
        self.fig = plt.figure()
        plt.xlabel('Wavelength (nm)')
        plt.ylabel('ADC Counts')
        plt.xlim(300, 900)
        plt.ylim(0, 66500)
        plt.subplots_adjust(bottom=0.14, right=0.95, top=0.96)

        #initalize canvas for plotting
        self.canvas = FigureCanvasTkAgg(
            self.fig, master=self.graph_frame)  # A tk.DrawingArea.
        # create toolbar for canvas
        toolbar = NavigationToolbar2Tk(self.canvas, self.graph_frame)
        toolbar.update()
        self.canvas.get_tk_widget().pack(fill=BOTH, expand=True)

        # create function object for calling functions
        settings_func = _Settings(settings_file)

        try:
            settings_func.create_settings()
        except:
            pass

        self.func = functions(self.root, self.canvas, self.fig)

        # allow buttons and frames to resize with the resizing of the root window
        # need to change this to however many rows/columns you hav
        self.root.grid_columnconfigure((0), weight=1)
        self.root.grid_rowconfigure((0, 1, 2), weight=1)

        # with all their corresponding functions (command)
        self.quit_button = Button(self.root,
                                  text="Quit",
                                  fg='Red',
                                  command=self.quit_button,
                                  width=button_width,
                                  height=button_big_height)
        self.quit_button.grid(row=1, column=0, padx=1, sticky=sticky_to)
Entry1_7.configure(highlightbackground="#d9d9d9")
Entry1_7.configure(highlightcolor="black")
Entry1_7.configure(insertbackground="black")
Entry1_7.configure(selectbackground="#c4c4c4")
Entry1_7.configure(selectforeground="black")

fig = Figure()
ax = plt.subplot()
ax.set_title('Complete Binary Tree', fontsize=10)

#Adding the Graph into the TK window

visuals = FigureCanvasTkAgg(fig, master=Graph)  # A tk.DrawingArea.
# visuals.draw()

toolbar = NavigationToolbar2Tk(visuals, Graph)
toolbar.update()
button = tk.Button(master=Graph, text="Quit", command=Graph.quit)
button.pack(side=tk.BOTTOM)
visuals.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)


#----------------------------------------------------Functions-----------------------------------------------------------------
def mainmenu():
    root.destroy()
    import main


def Creation():
    #--------------------------------------DELETING/Getting rid of any previous graph-----------------------------------------
    global Graph, visuals, button, toolbar, G, fixed_nodes, fixed_positions, tree
Ejemplo n.º 28
0
    def createWidgets(self):
        #Definicion de labels
        upp = Frame(root)
        upp.pack()
        self.L0 = Label(
            upp,
            text=
            "Para salir haga click en quitar, si no lo encuentra maximice la pantalla"
        )
        self.L0.pack()

        self.L1 = Label(upp, text="Selecciona el archivo")
        self.L1.pack(side=LEFT)

        #Creacion de boton para acceder al archivo
        self.button = Button(upp,
                             text="Selecciona la entrada",
                             command=self.main)
        self.button.pack(side=LEFT)

        upp1 = Frame(root)
        upp1.pack()
        self.L2 = Label(upp1, text="El archivo seleccionado es :")
        self.L2.pack(side=LEFT)

        self.inCo = Button(upp1,
                           text="Ingresar constantes",
                           command=self.constWindow)
        self.inCo.pack(side=LEFT)

        self.lerr = Label(upp1, text="Ingrese el error")
        self.lerr.pack(side=LEFT)

        self.err = Entry(upp1)
        self.err.insert(END, '0')
        self.err.pack(side=LEFT)

        graphs = Frame(root)
        graphs.pack()
        graphscF = Frame(root)
        graphscF.pack()
        graphscFl = Frame(graphscF)
        graphscFl.pack(side=LEFT)
        graphscFr = Frame(graphscF)
        graphscFr.pack(side=LEFT)

        self.graph1 = FigureCanvasTkAgg(fig, graphs)
        self.graph1.draw()
        self.graph1.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)
        self.toolbar = NavigationToolbar2Tk(self.graph1, graphscFl)
        self.toolbar.update()
        self.graph1.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)

        self.graph2 = FigureCanvasTkAgg(fig2, graphs)
        self.graph2.draw()
        self.graph2.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)
        self.toolbar = NavigationToolbar2Tk(self.graph2, graphscFr)
        self.toolbar.update()
        self.graph1.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)

        pf = Frame(root)
        pf.pack()
        self.pausa = Button(pf, text='Start', command=self.startpause)
        self.pausa.pack()

        down = Frame(root)
        down.pack()
        #Permite salir del programa
        self.salir = Button(down, text='Quitar', command=self.quitApp)

        self.salir.pack(side=BOTTOM)
Ejemplo n.º 29
0
def button_output(return_simulation, loop_range, titel):
    # Extract values from the return string
    # return string is a list
    # [new_pop, [generation, parents, probability_model, best_gen_fitness]^for_each_generation, target_fitness, plot_fitness, best_fitness_found]
    # new_pop: starting Population
    #   generation: number of current generation -> followed by 3 values for that generation
    #   parents: chromosomes that have the best fitness this generation
    #   probability_model: probability vector for this generation
    #   best_gen_fitness: best fitness found in this generation
    #   gen_pop: population for this generation
    # target_fitness: best possible fitness
    # plot_fitness: numpy array containing all fitness values of each generation for plotting
    # best_fitness_found: best overrall achieved fitness
    new_pop = return_simulation[0]
    generation_all = return_simulation[1]

    target_fitness = return_simulation[2]
    solutions = return_simulation[3]
    plot_fitness = return_simulation[4]
    best_fitness_found = return_simulation[5]

    # output starting generation to Box1
    Output_Box_One.insert("end", new_pop)
    # setting x value for plot
    x = []
    # output of the inner list with values for each generation to box 2
    for i in range(loop_range):
        generation = return_simulation[1][i][0]
        parents = return_simulation[1][i][1]
        prob_model = return_simulation[1][i][2]
        best_gen_fitness = return_simulation[1][i][3]
        Output_Box_Two.insert("end", "Generation: " + str(generation) + "\n")
        Output_Box_Two.insert(
            "end",
            "Parents selected for mating: " + "\n" + str(parents) + "\n")
        Output_Box_Two.insert(
            "end",
            "Generated Probability Model: " + "\n" + str(prob_model) + "\n")
        Output_Box_Two.insert(
            "end",
            "Best Fitness this Generation: " + str(best_gen_fitness) + "\n")
        Output_Box_Two.insert("end", "\n")
        x.append(i + 1)

    # output of final values to Box 3
    Output_Box_Three.insert("end", "Ergebnisse" + "\n")
    Output_Box_Three.insert("end",
                            "Target Fitness: " + str(target_fitness) + "\n")
    Output_Box_Three.insert(
        "end", "Best Fitness found: " + str(best_fitness_found) + "\n")
    Output_Box_Three.insert("end", "Best Solution(s)" + str(solutions) + "\n")

    # output the plot
    # generating new widged containing the plot
    # plotting x(number generations) and the numpy array with all fitness values
    # setting titel and label
    output_plot = plt.Figure(figsize=(5, 4), dpi=100)
    ax = output_plot.add_subplot(111)
    ax.plot(x, plot_fitness)
    line = FigureCanvasTkAgg(output_plot, master)
    line.get_tk_widget().grid(row=15)
    ax.set_title(titel)
    ax.set_xlabel('Generation')
    ax.set_ylabel('Fitness')

    toolbarFrame = tk.Frame(master)
    toolbarFrame.grid(row=25)
    toolbar = NavigationToolbar2Tk(line, toolbarFrame)
Ejemplo n.º 30
0
    def __init__(self, master):
        global settings_file
        self.root = master
        self.root.title("ESS System Interface")
        full_screen = True
        if full_screen:
            self.root.attributes('-fullscreen',
                                 True)  # fullscreen on touchscreen
        else:
            self.root.geometry('800x480')  # actual size of RPi touchscreen
        #self.root.attributes('-fullscreen',True)
        self.root.configure(bg="sky blue")
        self.root.minsize(800, 480)  # min size the window can be dragged to

        self.open_loop_stop = None  # control open Loop button

        # module message/label
        battery_font = tkFont.Font(family="Lucida Grande", size=9)
        label_font = tkFont.Font(family="Lucida Grande", size=12)
        warning_font = tkFont.Font(family="Lucida Grande", size=24)
        self.battery_array = []
        self.percent = 0
        self.charging = False

        # parameters for buttons and frames

        #create all the buttons onto to the main window
        button_width = 10
        button_big_height = 8
        button_small_height = 3
        sticky_to = 'nsew'  # allows all buttons to resize

        # setup Serial port-
        ## Graphing Frame and fake plot
        self.graph_frame = Frame(self.root, background="white")
        self.graph_frame.grid(row=2,
                              column=0,
                              columnspan=8,
                              padx=1,
                              pady=3,
                              sticky=sticky_to)

        #initalize figure
        self.fig = plt.figure()
        plt.xlabel('Wavelength (nm)')
        plt.ylabel('ADC Counts')
        plt.xlim(300, 900)
        plt.ylim(0, 66500)
        plt.subplots_adjust(bottom=0.14, right=0.95, top=0.96)

        #initalize canvas for plotting
        self.canvas = FigureCanvasTkAgg(
            self.fig, master=self.graph_frame)  # A tk.DrawingArea.
        # create toolbar for canvas
        toolbar = NavigationToolbar2Tk(self.canvas, self.graph_frame)
        toolbar.update()
        self.canvas.get_tk_widget().pack(fill=BOTH, expand=True)

        # create function object for calling functions
        settings_func = _Settings(settings_file)

        try:
            settings_func.create_settings()
        except:
            pass

        #(self.settings, self.wavelength) = settings_func.settings_read()
        self.func = functions(self.root, self.canvas, self.fig)
        self.func.home()

        module_button = Button(self.root,
                               text="Module 1: Scanning ESS",
                               bg='sky blue',
                               bd=0,
                               highlightthickness=0,
                               width=button_width,
                               height=7)
        module_button.grid(row=0,
                           column=0,
                           columnspan=7,
                           padx=1,
                           sticky=sticky_to)

        # with all their corresponding functions (command)
        self.quit_button = Button(self.root,
                                  text="Quit",
                                  fg='Red',
                                  command=self.quit_button,
                                  width=button_width,
                                  height=button_big_height)
        self.quit_button.grid(row=1,
                              column=6,
                              padx=1,
                              pady=1,
                              sticky=sticky_to)

        self.help_button = Button(self.root,
                                  text="Help",
                                  fg='black',
                                  command=self.func.plot_selected,
                                  width=button_width,
                                  height=button_big_height)
        self.help_button.grid(row=1,
                              column=5,
                              padx=1,
                              pady=1,
                              sticky=sticky_to)

        self.settings_button = Button(
            self.root,
            text="Settings",
            fg='black',
            command=lambda: self.window_popup(self.root),
            width=button_width,
            height=button_big_height)
        self.settings_button.grid(row=1,
                                  column=4,
                                  padx=1,
                                  pady=1,
                                  sticky=sticky_to)

        self.save_reference_button = Button(
            self.root,
            text="Save as Reference",
            wraplength=80,
            fg='black',
            command=self.func.save_scan_reference,
            width=button_width,
            height=button_big_height)
        self.save_reference_button.grid(row=1,
                                        column=3,
                                        padx=1,
                                        pady=1,
                                        sticky=sticky_to)

        self.acquire_button = Button(
            self.root,
            text="Acquire",
            wraplength=80,
            fg='black',
            command=lambda: self.func.acquire(save=False),
            width=button_width,
            height=button_big_height)
        self.acquire_button.grid(row=1,
                                 column=2,
                                 pady=1,
                                 padx=1,
                                 sticky=sticky_to)

        self.scan_button = Button(self.root,
                                  text="Scan",
                                  fg='black',
                                  wraplength=80,
                                  command=self.func.scan,
                                  width=button_width,
                                  height=button_big_height)

        self.scan_button.grid(row=1,
                              column=1,
                              padx=1,
                              pady=1,
                              sticky=sticky_to)

        self.open_scan_file_button = Button(self.root,
                                            text='Create Scan File',
                                            fg='black',
                                            wraplength=80,
                                            command=self.func.new_scan,
                                            width=button_width,
                                            height=button_big_height)
        self.open_scan_file_button.grid(row=1,
                                        column=0,
                                        padx=1,
                                        pady=1,
                                        sticky=sticky_to)

        # allow buttons and frames to resize with the resizing of the root window
        self.root.grid_columnconfigure((0, 1, 2, 3, 4, 5, 6, 7), weight=1)
        self.root.grid_rowconfigure((0, 1, 2), weight=1)

        self.battery_frame = Frame(self.root, bg='sky blue', width=4)
        self.battery_frame.grid(row=1,
                                column=7,
                                padx=(0, 1),
                                pady=1,
                                sticky='nsew')

        battery_width = 8

        self.battery_label_1 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_1.grid(row=0, column=0, padx=1, sticky='nsew')

        self.battery_label_2 = Label(self.battery_frame,
                                     text="%",
                                     font=battery_font,
                                     height=2,
                                     bg="green",
                                     width=battery_width)
        self.battery_label_2.grid(row=1, column=0, padx=1, sticky='nsew')

        self.battery_label_3 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_3.grid(row=2, column=0, padx=1, sticky='nsew')

        self.battery_label_4 = Label(self.battery_frame,
                                     bg="green",
                                     height=1,
                                     width=battery_width)
        self.battery_label_4.grid(row=3, column=0, padx=1, sticky='nsew')

        self.battery_frame.grid_rowconfigure((0, 1, 2, 3), weight=1)
        self.battery_frame.grid_columnconfigure((0), weight=1)

        # show module connected
        #messagebox.showinfo('Module #','Module 0: Base ESS System connected (No attachments)')

        # check battery percent from arduino
        def battery_percent_check():
            self.percent = self.func.battery_check()
            self.charging = False
            # check for charging and then add percent to array for averaging
            if int(self.percent) == 1000:
                self.charging = True
            self.battery_array.append(int(self.percent))
            if len(self.battery_array) > 10:
                del self.battery_array[0]

            #average battery_array
            self.percent = int(
                sum(self.battery_array) / (len(self.battery_array)))

            if self.charging:
                self.battery_label_1.configure(bg='green')
                self.battery_label_2.configure(font=battery_font,
                                               text="Charging",
                                               bg='green')
                self.battery_label_3.configure(bg='green')
                self.battery_label_4.configure(bg='green')
            else:
                if int(self.percent) >= 75:
                    self.battery_label_1.configure(bg='green')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='green')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 75 and int(self.percent) >= 50:
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='green')
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 50 and int(self.percent) >= 25:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='red')
                    self.battery_label_3.configure(bg='green')
                    self.battery_label_4.configure(bg='green')

                elif int(self.percent) < 25 and int(self.percent) >= 15:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text=str(self.percent) +
                                                   " %",
                                                   bg='red')
                    self.battery_label_3.configure(bg='red')
                    self.battery_label_4.configure(bg='yellow')
                else:
                    self.battery_label_1.configure(bg='red')
                    self.battery_label_2.configure(font=battery_font,
                                                   text="LOW",
                                                   bg='red')
                    self.battery_label_3.configure(bg='red')
                    self.battery_label_4.configure(bg='red')

                    error_top = Toplevel(self.root, bg="red")
                    message = Label(
                        error_top,
                        bg="white",
                        text="Low Battery! Plug In device and Save Data",
                        font=warning_font,
                        wraplength=250)
                    message.grid(row=0, column=0, padx=10, pady=10)
                    error_top.title("Warning")
                    error_top.lift()

                    error_top.after(3000, error_top.destroy)

            try:
                self.root.after(10000, battery_percent_check)
            except:
                pass

        battery_percent_check()