Ejemplo n.º 1
0
    def richness_all_samples(self, working_samples, samples_list, tax_level):
        self.create_window()
        self.top.title('Richness')

        self.top.title('overview of richness of all samples on ' + tax_level +
                       ' level')
        self.inner_frame = Frame(self.frame)
        self.inner_frame.grid(row=1, column=0, columnspan=4)

        top_space = 20
        width = 600
        if len(samples_list) > 20:
            width = 1000

        start_idx = len(self.all_tax_levels) - list(
            self.all_tax_levels).index(tax_level)
        if self.abundance_df.groupAbsoluteSamples() is not None:
            absolute_working_samples = self.abundance_df.groupAbsoluteSamples()
            absolute_working_samples = absolute_working_samples[
                samples_list].astype('int')
            richness = absolute_working_samples.astype(bool).sum(axis=0)
        else:
            richness = working_samples.astype(bool).sum(axis=0)[start_idx:-2]

        fig = Figure(figsize=(4, 6), dpi=120)  #, tight_layout=True)
        ax = fig.add_subplot(211)
        bp = ax.boxplot(richness)
        for val in richness:
            x = np.random.normal(1, 0.04, 1)
            ax.scatter(x, val, c='grey', marker='.', alpha=0.4)

        ax.set_xticklabels([''])
        ax.set_ylabel('number of ' + tax_level)

        ax = fig.add_subplot(212)
        for i, val in enumerate(richness):
            ax.scatter(richness.index[i], val, marker='.')
        ax.set_xticklabels(richness.index, fontsize=8, rotation='vertical')
        ax.set_xlabel('samples')
        ax.set_ylabel('number of ' + tax_level)

        fig.subplots_adjust(left=0.1,
                            right=0.98,
                            bottom=0.2,
                            top=0.95,
                            hspace=0.2,
                            wspace=0.2)

        matplotlib_frame = Frame(self.frame)
        matplotlib_frame.grid(row=2, column=0, rowspan=2, columnspan=2)
        canvas = FigureCanvasTkAgg(fig, matplotlib_frame)
        canvas.draw()
        canvas.get_tk_widget().grid(row=1, column=0, columnspan=4)

        save_button = Button(
            self.inner_frame,
            text="Save (high resolution)",
            command=lambda fig=fig, title='Richness', initialfile=
            'richness_all_samples': self.save_high_resolution_figure(
                fig, title, initialfile))
        save_button.grid(row=1, column=0)
Ejemplo n.º 2
0
p4l8 = ttk.Label(p4f0, text="          ")
p4l8.pack(side=TOP, anchor=W)
yaxstr = StringVar()
p4l9 = ttk.Label(p4f0, text="y axis label")
p4l9.pack(side=TOP, anchor=W)
p4e1 = ttk.Entry(p4f0, width=20, textvariable=yaxstr)
p4e1.pack(side=TOP, anchor=W)

p4f1 = Frame(master=page4)
p4f1.pack(side=RIGHT, fill=BOTH, expand=1)
f = Figure(figsize=(6, 4), dpi=100)
a = f.add_subplot(111)
t = np.arange(0.0, 6.28, 0.01)
s = np.sin(t)
a.plot(t, s)
mcanvas = FigureCanvasTkAgg(f, master=p4f1)
mcanvas.draw()
mcanvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
toolbar = NavToolbar2Tk(mcanvas, p4f1)
toolbar.update()
mcanvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)


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


mcanvas.mpl_connect('key_press_event', on_key_event)

Ejemplo n.º 3
0
 def internal_plotting(self, data):
     fig = Figure(figsize=(5,5), dpi=100)
     ax = fig.add_subplot(111)
     ax.plot(data)
     chart = FigureCanvasTkAgg(fig, self)
     chart.get_tk_widget().pack(fill=tk.BOTH, expand=True)
Ejemplo n.º 4
0
        print("enter Float for tolS")
        tolSentry.delete(0)
        tolSentry.insert(0, '1.0')
    return (tolN, tolS)


def drawNewTree():
    tolN, tolS = getInputs()
    reDraw(tolS, tolN)


root = tkt.Tk()

#tkt.Label(root,text="Plot Place Holder").grid(row=0,columnspan=3)
reDraw.f = Figure(figsize=(5, 4), dpi=100)
reDraw.canvas = FigureCanvasTkAgg(reDraw.f, master=root)
reDraw.canvas.show()
reDraw.canvas.get_tk_widget().grid(row=0, columnspan=3)

tkt.Label(root, text="tolN").grid(row=1, column=0)

tolNentry = tkt.Entry(root)
tolNentry.grid(row=1, column=1)
tolNentry.insert(0, '10')

tkt.Label(root, text="tolS").grid(row=2, column=0)

tolSentry = tkt.Entry(root)
tolSentry.grid(row=2, column=1)
tolSentry.insert(0, '1.0')
Ejemplo n.º 5
0
               command=show_systemenergy,
               bg='#0e0906',
               fg='Silver',
               font=font2).place(x=10, y=670)
    else:
        win7 = Tk()
        Label(
            win7,
            text=
            "The lower bound is greater or equal to the upper bound. Please choose the lower bound and the upper bound again."
        ).pack()
        Button(win7, text="OK", command=win7.destroy).pack()
        win7.mainloop()


canvas1 = FigureCanvasTkAgg(f1, root)
canvas1.get_tk_widget().place(x=410, y=30)

canvas2 = FigureCanvasTkAgg(f2, root)
canvas2.get_tk_widget().place(x=1070, y=30)

canvas3 = FigureCanvasTkAgg(f3, root)
canvas3.get_tk_widget().place(x=1070, y=520)

canvas4 = FigureCanvasTkAgg(f4, root)
canvas4.get_tk_widget().place(x=410, y=520)

Label(root,
      text="Please choose the initial state:",
      bg='#0e0906',
      fg='Silver',
    def __init__(self, root, derivative, gui_app_title="ODE_GRAPH"):
        # internal parameters
        self.root = root
        self.update_flag = 0
        self.gui_app_geometry = "1503x600"
        self.gui_app_title = gui_app_title
        self.x0 = DoubleVar(value=1)
        self.X = DoubleVar(value=5)
        self.derivative = derivative
        self.y0 = DoubleVar(value=2)
        self.n = DoubleVar(value=10)
        self.N = DoubleVar(value=100)
        self.m1 = IntVar(0)
        self.m2 = IntVar(0)
        self.m3 = IntVar(0)

        # GUI construction
        self.root.geometry(self.gui_app_geometry)
        self.root.title(self.gui_app_title)
        self.function_graph_label = Label(
            self.root,
            text="Graph of functions of grid size N",
            font=("Helvetica", 15))
        self.function_graph_label.place(x=80, y=5)

        self.f1 = Figure(figsize=(5, 5), dpi=100)
        draw.Graph(self.f1, self.x0.get(), self.X.get(), self.y0.get(),
                   self.derivative)

        self.canvas1 = FigureCanvasTkAgg(self.f1, master=self.root)
        self.canvas1.draw()
        self.canvas1.get_tk_widget().place(x=5, y=35)
        #----------------------------------------------------------------------------
        self.function_graph_label = Label(self.root,
                                          text="Local errors of grid size N",
                                          font=("Helvetica", 15))
        self.function_graph_label.place(x=630, y=5)

        self.f2 = Figure(figsize=(5, 5), dpi=100)
        self.f2.clear()

        self.canvas2 = FigureCanvasTkAgg(self.f2, master=self.root)
        self.canvas2.draw()
        self.canvas2.get_tk_widget().place(x=505, y=35)
        #---------------------------------------------------------------------------
        self.function_graph_label = Label(
            self.root,
            text="Maximum local errors of grid sizes in range(n,N)",
            font=("Helvetica", 15))
        self.function_graph_label.place(x=1070, y=5)

        self.f3 = Figure(figsize=(5, 5), dpi=100)
        self.f3.clear()

        self.canvas3 = FigureCanvasTkAgg(self.f3, master=self.root)
        self.canvas3.draw()
        self.canvas3.get_tk_widget().place(x=1000, y=35)
        #---------------------------------------------------------------------------------
        a, b = 550, 20
        self.mm1 = Checkbutton(self.root,
                               text="Euler's",
                               variable=self.m1,
                               command=self._update_callback)
        self.mm1.place(x=950, y=a - b + 5)
        self.mm2 = Checkbutton(self.root,
                               text="Improved Euler's",
                               variable=self.m2,
                               command=self._update_callback)
        self.mm2.place(x=1050, y=a - b + 5)
        self.mm3 = Checkbutton(self.root,
                               text="Runge Kutte",
                               variable=self.m3,
                               command=self._update_callback)
        self.mm3.place(x=1200, y=a - b + 5)
        #---------------------------------------------------------------------------------

        aa, bb, cc = 50, 10, 55
        self.label = Label(self.root, text="y(x0)")
        self.label.place(x=aa - 10, y=a)
        self.b2 = Entry(self.root, textvariable=self.y0, width=5)
        self.b2.place(x=aa - bb, y=a + b)
        aa += cc
        self.label = Label(self.root, text="x0", font=("Helvetica", 8))
        self.label.place(x=aa, y=a)
        self.b1 = Entry(self.root, textvariable=self.x0, width=5)
        self.b1.place(x=aa - bb, y=a + b)
        aa += cc
        self.label = Label(self.root, text="X")
        self.label.place(x=aa, y=a)
        self.b4 = Entry(self.root, textvariable=self.X, width=5)
        self.b4.place(x=aa - bb, y=a + b)
        aa += cc
        self.label = Label(self.root, text="n")
        self.label.place(x=aa, y=a)
        self.b3 = Entry(self.root, textvariable=self.n, width=5)
        self.b3.place(x=aa - bb, y=a + b)
        aa += cc
        self.label = Label(self.root, text="N")
        self.label.place(x=aa, y=a)
        self.b5 = Entry(self.root, textvariable=self.N, width=5)
        self.b5.place(x=aa - bb, y=a + b)
        aa += 100
        #----------------------------------------------------------------
        self.p1 = Label(self.root, text="Function")
        self.p1.place(x=aa + 80, y=a - 15)
        img = ImageTk.PhotoImage(Image.open("function.jpg"))
        panel = Label(root, image=img)
        panel.image = img
        panel.place(x=aa + 40, y=a + 5)
        #----------------------------------------------------------------
        aa += 100
        self.p2 = Label(self.root, text="General solution")
        self.p2.place(x=aa + 260, y=a - 37)
        img = ImageTk.PhotoImage(Image.open("general.jpg"))
        panel = Label(root, image=img)
        panel.image = img
        panel.place(x=aa + 210, y=a - 15)
        #----------------------------------------------------------------
        self.close_button = Button(self.root,
                                   text="Update",
                                   command=self._update_callback)
        self.close_button.place(x=1350, y=a + 15)
        self.close_button = Button(self.root, text="Close", command=self._quit)
        self.close_button.place(x=1430, y=a + 15)
    def __init__(self, master, controller):
        #Font
        LARGE_FONT = ("Verdana", 12)
        self.x_max_lim = 20

        #Set root component
        self.master = master
        self.master.title("Live Plot of Power bands")

        #Set label
        self.label1 = Label(self.master,
                            text="Workload detector",
                            font=LARGE_FONT,
                            width=30,
                            height=5)
        self.label1.pack(pady=10, padx=10)
        self.label1.config(bg="#fff000000")

        # #Set init button
        # self.button1 = Button(self.master, text="Start Animation", command=self.stop_start_animation)
        # self.button1.pack()

        #Create matplotlib graph
        self.figure = plt.Figure(figsize=(6, 5), dpi=100)
        self.ax = self.figure.add_subplot(111)

        self.graph = FigureCanvasTkAgg(self.figure, self.master)
        self.graph.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH)
        self.ax.set_title('Live Plot')
        self.ax.set_ylim(-0.3, 1.3)
        self.ax.set_xlim(0, self.x_max_lim)

        #Create data line
        self.line = Line2D([0, 1, 2, 3, 4, 5], [1, 2, 4, 5, 6, 8])
        self.line.set_linestyle('--')
        self.line.set_marker('*')
        self.line.set_markersize(2)
        self.line.set_color('red')

        self.line2 = Line2D([0, 1, 2, 3, 4, 5], [1, 2, 4, 5, 6, 8])
        self.line2.set_linestyle('--')
        self.line2.set_marker('*')
        self.line2.set_markersize(2.0)
        self.line2.set_color('blue')

        self.ax.add_line(self.line)
        self.ax.add_line(self.line2)

        #Create animation logic and animation
        self.logic = LivePlotLogic(controller,
                                   axe=self.ax,
                                   line=[self.line, self.line2],
                                   maxt=self.x_max_lim,
                                   workload_label=self.label1)

        self.ani = animation.FuncAnimation(self.figure,
                                           func=self.logic.update_animation,
                                           frames=self.logic.check_data_queue,
                                           init_func=self.logic.init_animation,
                                           interval=10,
                                           blit=True)

        self.animationRunning = True
Ejemplo n.º 8
0
root.title('YU - Live Pollution Monitoring')
root.geometry('1050x500')

graph_frame = tkinter.Frame(root, height=500, width=600)
graph_frame.pack(side=tkinter.LEFT, padx=10)
control_frame = tkinter.Frame(root, bg='#CCCCFF')
control_frame.pack(side=tkinter.RIGHT, fill='both', expand=True)

fig = Figure()
ax = fig.add_subplot(111)
ax.set_xlabel("Time")
ax.set_ylabel("PPM")

ax.grid()

graph = FigureCanvasTkAgg(fig, master=graph_frame)
graph.get_tk_widget().pack(side="bottom", fill='both', expand=True)

#Labels Here
gas_ppm = tkinter.Label(control_frame,
                        text='Carbon dioxide(CO2): ' + gas_data + ' PPM',
                        font=("Courier", 14, 'bold'))
gas_ppm.pack(pady=(30, 5))

analog_data_label = tkinter.Label(control_frame,
                                  text='Analog Values: ' + analog_data,
                                  font=("Courier", 16, 'bold'))
analog_data_label.pack(pady=(5, 15))

port_in_use = tkinter.Label(control_frame,
                            text='Port: ' + serial_port,
Ejemplo n.º 9
0
seconds_label = Label(root, text='How many seconds?')
seconds_label.grid(row=0, column=0)
seconds_field = Entry(root)
seconds_field.grid(row=1, column=0)

samples_label = Label(root, text='How many samples / seconds?')
samples_label.grid(row=2, column=0)
samples_field = Entry(root)
samples_field.grid(row=3, column=0)

# sensor_label = Label(root, text='What sensor(s) would you like to use?')
# sensor_label.pack()
# sensor_field = Entry(root)
# sensor_field.pack()

# sensor_list = []
# for choice in sensor_field.get():
#     num = choice.split(' ')
#     sensor_list.append(num)
gdx.select_sensors([2, 3])

start_button = Button(root, text='Start Sensing', command=start_reading)
start_button.grid(row=4, column=0)

fig, ax = plt.subplots(1, 1)
plt.ion()
chart = FigureCanvasTkAgg(fig, root)
chart.get_tk_widget().grid(row=0, column=1, rowspan=20)

root.mainloop()
    def plot_univ_on_GUI(self):
        
        if not self.current_simulation or not self.current_simulation.results:
            return
        if len(self.current_simulation.results) == self.last_results_plotted:
                return
        self.last_results_plotted = len(self.current_simulation.results)
        
        current_var = self.current_simulation.vars_to_change[0]
        results = pd.concat(self.current_simulation.results).sort_index()
        fig_list =[]
        var_fig = Figure(figsize = (3,3), facecolor=[240/255,240/255,237/255], tight_layout=True)
        a = var_fig.add_subplot(111)
        num_bins = 15
        _, bins, _ = a.hist(self.simulation_dist[current_var], num_bins, facecolor='blue', alpha=0.1)
        a.hist(results[current_var], bins=bins, facecolor='blue', alpha=0.7)
        a.set_title(current_var)
        fig_list.append(var_fig)
        
        mfsp_fig = Figure(figsize = (3,3), facecolor=[240/255,240/255,237/255], tight_layout=True)
        b = mfsp_fig.add_subplot(111)
        b.hist(results['MFSP'], num_bins, facecolor='blue', alpha=0.85)
        b.set_title('MFSP - ' + current_var)
        fig_list.append(mfsp_fig)
        
        figs_to_plot = self.finished_figures[:] + fig_list
        if len(self.current_simulation.results) == self.current_simulation.tot_sim:
            self.finished_figures += fig_list
        
        if self.univar_row_num != 0:
            row_num = 17
        else:
            row_num = 10
        
        frame_canvas = ttk.Frame(self.current_tab)
        frame_canvas.grid(row=row_num, column=1, columnspan = 3,pady=(5, 0))
        frame_canvas.grid_rowconfigure(0, weight=1)
        frame_canvas.grid_columnconfigure(0, weight=1)
        frame_canvas.config(height = '10c', width='12c')
        
        main_canvas = Canvas(frame_canvas)
        main_canvas.grid(row=0, column=0, sticky="news")
        main_canvas.config(height = '10c', width='12c')
        
        vsb = ttk.Scrollbar(frame_canvas, orient="vertical", command=main_canvas.yview)
        vsb.grid(row=0, column=1,sticky = 'ns')
        main_canvas.configure(yscrollcommand=vsb.set)
        
        figure_frame = ttk.Frame(main_canvas)
        main_canvas.create_window((0, 0), window=figure_frame, anchor='nw')
        figure_frame.config(height = '10c', width='12c')
    
        row_num = 0
        column = False
        for figs in figs_to_plot:
            figure_canvas = FigureCanvasTkAgg(figs, master=figure_frame)
            if column:
                col = 4
            else:
                col = 1
            #figure_canvas.draw()
            figure_canvas.get_tk_widget().grid(
                    row=row_num, column=col,columnspan=2, rowspan = 5, pady = 5,padx = 8, sticky=E)
            #figure_canvas._tkcanvas.grid(row=row_num, column = 0,columnspan = 10, rowspan = 10, sticky= W+E+N+S, pady = 5,padx = 5)
            if column:
                row_num += 5
            column = not column
        

        figure_frame.update_idletasks()
        frame_canvas.config(width='12c', height='10c')
        
        # Set the canvas scrolling region
        main_canvas.config(scrollregion=figure_frame.bbox("all"))
Ejemplo n.º 11
0
    def tester(self, root, df_x_test, df_y_test):
        print('long :', self.long)

        self.df_x_test2 = df_x_test[0:self.long - 1]
        self.df_y_test2 = df_y_test[0:self.long - 1]

        print(self.df_x_test2)
        print(self.df_x_train)

        self.x_test2 = self.cv.transform(
            self.df_x_test2.apply(lambda x: np.str_(x)))

        pred = self.mb.predict(self.x_test2)

        actual = np.array(self.df_y_test2)
        pcount = 0
        ncount = 0
        zero = 0
        un = 0

        # Plot

        for i in range(len(pred)):
            if pred[i] == str(actual[i]):
                if pred[i] == '0':
                    ncount += 1
                if pred[i] == '1':

                    pcount += 1
            else:

                if pred[i] == '0':
                    zero += 1
                if pred[i] == '1':
                    un += 1
###############################################################
        fig = Figure(figsize=(2.5, 2.5))
        plt = fig.add_subplot(111)
        labels = '   vrai\n positive', 'faux \n positive'
        sizes = [pcount, un]
        colors = ['lightcoral', 'lightskyblue']
        explode = (0.1, 0)  # explode 1st slice

        # Plot
        plt.pie(sizes,
                explode=explode,
                labels=labels,
                colors=colors,
                autopct='%1.1f%%',
                shadow=True,
                startangle=140)

        plt.axis('equal')
        centre_frame1 = Frame(root, bg='white', width=630, height=700)
        centre_frame1.grid(row=3, column=0, sticky=N)
        centre_frame1.grid_propagate(0)

        f1 = Frame(centre_frame1, bg='white', width=315, height=700)
        f1.grid(row=0, column=0)
        f1.grid_propagate(0)

        f2 = Frame(centre_frame1, bg='white', width=315, height=700)
        f2.grid(row=0, column=1)
        f2.grid_propagate(0)

        canvas = FigureCanvasTkAgg(fig, master=f1)
        canvas.get_tk_widget().grid(row=3, column=1)
        canvas.draw()

        fig2 = Figure(figsize=(2.5, 2.5))
        plt = fig2.add_subplot(111)
        labels = ' vrai \n negative', '  faux \n negative'
        sizes = [ncount, zero]
        colors = ['gold', 'yellowgreen']
        explode = (0.1, 0)  # explode 1st slice

        # Plot
        plt.pie(sizes,
                explode=explode,
                labels=labels,
                colors=colors,
                autopct='%1.1f%%',
                shadow=True,
                startangle=140)

        plt.axis('equal')

        canvas = FigureCanvasTkAgg(fig2, master=f2)
        canvas.get_tk_widget().grid(row=3, column=1)
        canvas.draw()

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

        #+'%\n'+'faux neg :'+str(round(zero*100/ len(pred),2))+'%\n'+'faux pos'+str(round(un*100/ len(pred),2))
        self.button_color = 'white'
        self.button_colorf = 'black'
        img = Image.open('mira/pos.png')
        self.bimage100 = ImageTk.PhotoImage(img)

        lscore = Label(f1,
                       text="",
                       bg=self.button_color,
                       width=self.x // 5.5,
                       fg=self.button_colorf,
                       image=self.bimage100,
                       compound="right",
                       font=('arial', 10),
                       borderwidth=2,
                       relief="ridge")

        img = Image.open('mira/neg.png')
        self.bimage101 = ImageTk.PhotoImage(img)

        lscore2 = Label(f2,
                        text="",
                        bg=self.button_color,
                        width=self.x // 5.5,
                        fg=self.button_colorf,
                        image=self.bimage101,
                        compound="right",
                        font=('arial', 10),
                        borderwidth=2,
                        relief="ridge")

        img = Image.open('mira/false.jpg')
        self.bimage102 = ImageTk.PhotoImage(img)

        lscore3 = Label(f1,
                        text="",
                        bg=self.button_color,
                        width=self.x // 5.5,
                        fg=self.button_colorf,
                        image=self.bimage102,
                        compound="right",
                        font=('arial', 10),
                        borderwidth=2,
                        relief="ridge")

        img = Image.open('mira/false.jpg')
        self.bimage103 = ImageTk.PhotoImage(img)

        lscore4 = Label(f2,
                        text="",
                        bg=self.button_color,
                        width=self.x // 5.5,
                        fg=self.button_colorf,
                        image=self.bimage103,
                        compound="right",
                        font=('arial', 10),
                        borderwidth=2,
                        relief="ridge")
        img = Image.open('mira/vrai.jpg')
        self.bimage99 = ImageTk.PhotoImage(img)
        lscore5 = Label(f1,
                        text="",
                        bg=self.button_color,
                        width=self.x // 5.5,
                        fg=self.button_colorf,
                        image=self.bimage99,
                        compound="right",
                        font=('arial', 10),
                        borderwidth=2,
                        relief="ridge")

        lscore6 = Label(f2,
                        text="",
                        bg=self.button_color,
                        width=self.x // 5.5,
                        fg=self.button_colorf,
                        image=self.bimage99,
                        compound="right",
                        font=('arial', 10),
                        borderwidth=2,
                        relief="ridge")
        lscore.grid(row=0, column=1)
        lscore2.grid(row=0, column=1)
        lscore3.grid(row=1, column=1)
        lscore4.grid(row=1, column=1)
        lscore5.grid(row=2, column=1)
        lscore6.grid(row=2, column=1)

        lscore['text'] = 'total des sentiment \n positive:' + str(pcount + un)

        lscore2['text'] = 'total des sentiment \n negative:' + str(ncount +
                                                                   zero)

        lscore3['text'] = '  faux positive : ' + str(un)

        lscore4['text'] = '  faux  negative   : ' + str(zero)

        lscore5['text'] = '  vrai positive  : ' + str(pcount)
        lscore6['text'] = '  vrai negative   : ' + str(ncount)
Ejemplo n.º 12
0
def runaniA():
    #Reset dados para repetição
    e8.delete(0, 'end'); e9.delete(0, 'end') ; e10.delete(0, 'end') ;e11.delete(0, 'end') ; e12.delete(0, 'end')  ; e13.delete(0, 'end'); e14.delete(0, 'end'); e15.delete(0, 'end'); txt.delete(1.0,END)  
    l8.config(fg="gray");l9.config(fg="gray"); l10.config(fg="gray"); l11.config(fg="gray"); l12.config(fg="gray"); l13.config(fg="gray"); l14.config(fg="gray"); l15.config(fg="gray")
    k=IntVar(); k.set(0); w=IntVar(); w.set(0) #Contadores de execução única
    j=IntVar(); j.set(0) #Contador de execução final
    
    #Listas de valores para aquisição dos dados
    DadosArray=[] #Dados do sensor 
    T1=[]; T2=[]; T3=[]#Dados separados por sensor e convertidos para float 
    t=[]; _POPt=[]; t1=[]; tmlist=[] #Dados de tempo
    tm=IntVar(); tm_=StringVar(); tPS=IntVar(); tPE=StringVar(); Ts=StringVar(); Tp=StringVar(); Te=StringVar(); Q=StringVar(); pat=StringVar(); par=StringVar(); Vrs=StringVar() ; nteste=StringVar();
    _POPdados1=[]; _POPdados2=[]; _POPdados3=[]; _POPit=[]; _POPmedia1=[] #Dados para gráfico simultâneo
    flag_=[] #Resposta binária: flag (0 para valores de MEDIA abaixo do erro e 1 para valores de MEDIA acima do erro)
    
    #Valores instantâneos de temperatura, tempo, inhomogeneidade e média de inclinação 
    it_=[]; t_1=[]; t_2=[]; T1_1=[]; T1_2=[]; T2_1=[]; T2_2=[]; T3_1=[]; T3_2=[]; 
    T1incli1_=[]; T2incli1_=[]; T3incli1_=[]; media1_=[]
    
    #Parâmetros iniciais
    Erro= float(e5.get()) ; #Erro de temperatura para determinação do tPS:
    Pulsoduracao= float(e1.get()); #Duração do pulso do traçador (s)
    Vre = float(e2.get()); #Volume do reator (total) (m3)
    Vpulso = float(e3.get()); #Volume do traçador (m3)
    DeltaTemp = float(e4.get()); #Diferença de temperatura entre reator e traçador (°C)
    Nsensor = 3; #N° de sensores
    itmin=float(e6.get()) #Mínimo para função de inhomogeneidade
    tm_.set(0);    tm.set(2592000);    tPS.set(2592000);    dalayf=5
    
    #Gráfico
    fig=Figure(figsize=(10,4), dpi=100) #Tamanho e qualidade da figura
    plot=fig.add_subplot(1,1,1) #Figura = Gráfico em subplot do Matlib
    ax2 = plot.twinx() #Eixo secundário ao plot
    line1, = plot.plot(_POPt,_POPdados1, 'k-', label="T1") #Dados no gráfico
    line2, = plot.plot(_POPt,_POPdados2, 'k-', label="T2") 
    line3, = plot.plot(_POPt,_POPdados3, 'k-', label="T3")
    
    #Configurar radiobuttons
    if(v2.get()==0): s2r2.configure(state = DISABLED); s2r3.configure(state = DISABLED)
    if(v2.get()==1): s2r1.configure(state = DISABLED); s2r3.configure(state = DISABLED)
    if(v2.get()==2): s2r1.configure(state = DISABLED); s2r2.configure(state = DISABLED)
    
    #Linha horizontal e eixo secundário
    if(v1.get()==0):
        line4, = ax2.plot(_POPt,_POPit, 'c:', label="i(t)") 
        ax2.set_ylabel('i(t) (.%)', color='k') # Legenda de eixo y
        ax2.plot(_POPt,_POPit, 'c:', label="i(t)") 
        s1r1.configure(state = DISABLED)
    else: 
        line4, = ax2.plot(_POPt,_POPmedia1, 'c:', label="Inclinação") 
        ax2.set_ylabel('Inclinação', color='k') # Legenda de eixo y
        ax2.plot(_POPt,_POPmedia1, 'c:', label="i(t)") 
        s1r2.configure(state = DISABLED)
        
    #Eixos
    plot.set_xlabel('Tempo (s)', color='k') #Legenda de eixo x
    plot.set_ylabel('Temperatura (°C)', color='k') # Legenda de eixo y
    
    #Início da corrida
    l16.config(text='Conectando...')
    ser=serial.Serial(encon_arduino(), 9600) #Local e taxa de atualização
    
    def tmlabel(): #Função que retorna os valores de tempo de mistura na janela dependendo do tipo de teste
        if(j.get()==0 and v2.get()==0): txt.insert(INSERT,'     Tempo de mistura \n  (Teste único)= ' + str(round(float(tm_.get()), 2)) + ' s')
        if(j.get()==0 and v2.get()!=0): txt.insert(INSERT,'     Tempo de mistura \n   (Ensaio 1)= ' + str(round(float(tm_.get()), 2)) + ' s\n')
        if(j.get()==1 and v2.get()==1): txt.insert(INSERT,'\n     Tempo de mistura \n   (Ensaio 2)= ' + str(round(float(tm_.get()), 2)) + ' s \n\n       (Duplicata)\n      Média= ' + str(round((sum(tmlist)/len(tmlist)),2)) + ' s \n\n  Desvio Padrão= ' + str(round(statistics.stdev(tmlist),2)) + ' s')
        if(j.get()==1 and v2.get()!=1): txt.insert(INSERT,'\n     Tempo de mistura \n   (Ensaio 2)= ' + str(round(float(tm_.get()), 2)) + ' s')
        if(j.get()==2 and v2.get()==2): txt.insert(INSERT,'\n\n     Tempo de mistura \n  (Ensaio 3)= ' + str(round(float(tm_.get()), 2)) + ' s \n\n       (Triplicata)\n      Média= ' + str(round((sum(tmlist)/len(tmlist)),2)) + ' s \n\n  Desvio Padrão= ' + str(round(statistics.stdev(tmlist),2)) + ' s')       
        
    if encon_arduino() is not None: 
        ser.reset_input_buffer() #Reset buffer
        now = datetime.datetime.now()
        
        #Criar Pasta com resultados dependendo do
        if(v2.get()==0): caminho="Simples_Tempo_de_mistura_" + str(now.day) + "_" + str(now.month) + "_ " + str(now.year)
        if(v2.get()==1): caminho="Duplicata_Tempo_de_mistura_" + str(now.day) + "_" + str(now.month) + "_ " + str(now.year)
        if(v2.get()==2): caminho="Triplicata_Tempo_de_mistura_" + str(now.day) + "_" + str(now.month) + "_ " + str(now.year) 
        if os.path.exists(os.path.join(e8.get(), caminho)): pass #Pasta pré-existente (não criar pasta)
        else: os.mkdir(os.path.join(e8.get(), caminho)) #Criação da pasta no local(caminho) definido anteriormente dependendo do tipo de teste
        
        #Salvar dados no excel
        def salvar_dados_excel():
            now = datetime.datetime.now() #Aquisição dos valores de horário local
            if(v1.get()==0):
                df = pd.DataFrame(list(zip(t, T1, T2, T3, it_)), columns =['tempo (s)', 'T1 (°C)', 'T2 (°C)', 'T3 (°C)', 'i(t)']) #Definição do dataframe com os resultados 
            else:
                df = pd.DataFrame(list(zip(t, T1, T2, T3, media1_)), columns =['tempo (s)', 'T1 (°C)', 'T2 (°C)', 'T3 (°C)', 'MédiaInc']) #Definição do dataframe com os resultados 
            if(v1.get()==0): nteste.set("Corrida_Agua" + " - " + str(now.hour) + "h_"  + str(now.minute) + "min_" + str(now.second) + "s.xlsx") #Nome do arquivo a ser criado
            else: nteste.set("Corrida_Óleo" + " - " + str(now.hour) + "h_"  + str(now.minute) + "min_" + str(now.second) + "s.xlsx") #Nome do arquivo a ser criado
            path = os.path.join(e16.get(), caminho, nteste.get()) #Caminho do arquivo]
            writer=pd.ExcelWriter(path, engine='xlsxwriter') #Criação do arquivo
            df.to_excel(writer, sheet_name='Corrida_1', startrow=1) #Local na planilha
            #Geração do gráfico com os dados do sensor: Local, estilo e tamanho do gráfico
            workbook  = writer.book
            workbook.set_size(3600, 2400)
            chart = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth_with_markers'})
            chart.add_series({'name': '=Corrida_1!$C$2','categories': '=Corrida_1!$B$3:$B$5000','values': '=Corrida_1!$C$3:$C$5000', 'marker':{'type': 'circle','size': 5}})
            chart.add_series({'name': '=Corrida_1!$D$2','categories': '=Corrida_1!$B$3:$B$5000','values': '=Corrida_1!$D$3:$D$5000', 'marker':{'type': 'circle','size': 5}})
            chart.add_series({'name': '=Corrida_1!$E$2','categories': '=Corrida_1!$B$3:$B$5000','values': '=Corrida_1!$E$3:$E$5000', 'marker':{'type': 'circle','size': 5}})
            chart.add_series({'name': '=Corrida_1!$F$2','categories': '=Corrida_1!$B$3:$B$5000','values': '=Corrida_1!$F$3:$F$5000', 'y2_axis': 1, 'marker': {'type': 'none', 'color': 'black', 'size': 5}, 'line': {'dash_type': 'dash'}})
            chart.set_title({'name': 'Dados de temperatura'})
            chart.set_x_axis({'name': 'Tempo(s)'})
            chart.set_y_axis({'name': 'Temperatura (°C)'})
            chart.set_y2_axis({'name': 'i(t)'})
            chart.set_plotarea({'layout': {'x':0.14,'y':0.26,'width':0.55,'height': 0.6,}})
            chart.set_style(2)
            sheet = writer.sheets['Corrida_1']
            if(v1.get==0): sheet.insert_chart('I2', chart, {'x_offset': 10, 'y_offset': 10}) 
            else: sheet.insert_chart('L2', chart, {'x_offset': 10, 'y_offset': 10}) 
            writer.save() # Salvar planilha
        #Chamar gif
        Imagem2()
        
    #Iniciar contadores de tempo e flag
    start=time.time(); t.append(0); flag_.append(0);
    def Tmistura(i):
        if encon_arduino() is None: #Quando não for encontrado arduino
            #Imagem de Erro
            root.original7 = Image.open('error.PNG') #Nome da imagem - Local da imagem > pasta do arquivo
            resized7 = root.original7.resize((60, 60),Image.ANTIALIAS) #Mudança de escala
            root.image7 = ImageTk.PhotoImage(resized7) 
            root.display7 = Label(root, image = root.image7)
            root.display7.grid(row=2, column=3, rowspan=3, columnspan=13) #Local na janela
            root.display7.configure(background='white')
            #Legenda do Erro
            l30=Label (root, text="ERRO: Sensor \nnão encontrado\n Conecte o sensor", bd=5, relief="flat",
                  font= "Times 11",width=25, height=4, bg='gray9', fg='white')
            l30.grid (row=3, column=3, rowspan=5,columnspan=13)
            l16.config(text='Desconectado')
            ani.event_source.stop() #Parar animação
        else:
            #Garantir que a comunicação está ativa
            if(ser.isOpen() == False): ser.open()
            #Configurar entradas
            l16.config(fg="black"); l16.config(text='Conectado');
            root.protocol("WM_DELETE_WINDOW", disable_event) #Bloquear fechamento da janela
            if(int(t[-1])<tm.get()+dalayf):
                arduinoData=ser.readline().decode('utf8') #Decodificação dos dados do arduino
                end=time.time()
                DadosArray=arduinoData.split(' , ')
                T1.append(float(DadosArray[0])) #Dados de cada sensor separados 
                T2.append(float(DadosArray[1])) #(Objetivo: Salvar lista de temperaturas e 
                T3.append(float(DadosArray[2])) #possibilitar a atualização automática dos valores no gráfico ao vivo)
                t.append(end-start)
                #Mudar legenda 
                l18.config(text='T1='+str(T1[-1])); l19.config(text='T2='+str(T2[-1])); l20.config(text='T3='+str(T3[-1]))
                if(w.get()==0):
                    Ts.set((T1[-1]+T2[-1]+T3[-1])/3);
                    w.set(1)
                if(t[-2]<tPS.get()): #Início do tempo de mistura (Método das diferenças)
                    if(i>=1): #Valores instantâneos de temperatura e tempo 
                        media=(((T1[-2]+T2[-2]+T3[-2])/3))
                        if(v1.get()==0):it_.append(0)
                        else: media1_.append(0)
                        if(abs((T1[-1]-media)>Erro or abs(T2[-1]-media)>Erro or abs(T3[-1]-media)>Erro) 
                           and (T1[-1]>=T1[-2]+Erro or T2[-1]>=T2[-2]+Erro or T3[-1]>=T3[-2]+Erro)): #Flag
                            flag=1
                            flag_.append(flag)
                        else:
                            flag=0
                            flag_.append(flag)
                            
                        #Correção do flag para variação local de temperatura 
                        #Seleção de flag
                        if(T1[-1]>=T1[-2] or T2[-1]>=T2[-2] or T3[-1]>=T3[-2]):
                            if((flag_[-2]==1 and flag_[-1]==0) or (flag_[-2]==0 and flag_[-1]==0) or (flag_[-2]==0 and flag_[-1]==1)):
                                pass
                            else:
                                tPS.set(int(t[-2])) #Tempo de início do pulso tPS (s) 
                                e10.configure(state='normal'); e10.delete(0, 'end'); e10.insert(END, tPS.get()); l10.config(fg="black")
                                if(v1.get()==0): 
                                    tPE.set(tPS.get() + Pulsoduracao) #Tempo de fim do pulso tPE (s)
                                    e11.configure(state='normal'); e11.delete(0, 'end'); e11.insert(END, tPE.get()); l11.config(fg="black")
                                    Tp.set(float(Ts.get()) + DeltaTemp) #Temperatura do traçador (Tp) (°C)
                                    e8.configure(state='normal'); e8.delete(0, 'end'); e8.insert(END, round(float(Ts.get()),2)); l8.config(fg="black")
                                    e9.configure(state='normal'); e9.delete(0, 'end'); e9.insert(END, round(float(Tp.get()),2)); l9.config(fg="black")
                                    Vrs.set(Vre - Vpulso) #Volume do reator antes do pulso (m3)
                                    Q.set(Vpulso / Pulsoduracao) #Vazão do pulso (F) ( m3/s)
                                    e12.configure(state='normal'); e12.delete(0, 'end'); e12.insert(END, round(float(Q.get())*1000,3)); l12.config(fg="black")
                                    pat.set(((999.83952)+(16.945179*float(Tp.get()))-((7.9870401*10**-3)*(float(Tp.get())**2))-((46.170561*10**-6)*(float(Tp.get())**3))+((105.56302*10**-9)*(float(Tp.get())**4))-((280.54253*10**-12)*(float(Tp.get())**5)))/(1+((16.87985*10**-3)*float(Tp.get())))) #Densidade da água (Traçador)
                                    e14.configure(state='normal'); e14.delete(0, 'end'); e14.insert(END, round(float(pat.get()))); l14.config(fg="black")
                                    par.set(((999.83952)+(16.945179*float(Ts.get()))-((7.9870401*10**-3)*(float(Ts.get())**2))-((46.170561*10**-6)*(float(Ts.get())**3))+((105.56302*10**-9)*(float(Ts.get())**4))-((280.54253*10**-12)*(float(Ts.get())**5)))/(1+((16.87985*10**-3)*float(Ts.get())))) #Densidade da água (Reator)
                                    e15.configure(state='normal'); e15.delete(0, 'end');  e15.insert(END, round(float(par.get()))); l15.config(fg="black")
                                    Te.set(((float(pat.get())*Vpulso*float(Tp.get()))+(float(par.get())*float(Vrs.get())*float(Ts.get())))/((float(pat.get())*Vpulso)+(float(par.get())*float(Vrs.get())))) #Temperatura do meio após pulso (Te) (°C) - por balanço de energia
                                    e13.configure(state='normal'); e13.delete(0, 'end'); e13.insert(END, round(float(Te.get()),2)); l13.config(fg="black")
                                else: pass
                        #Atualizar lista de dados do gráfico
                        _POPdados1.append(T1[-2]);_POPdados2.append(T2[-2]);_POPdados3.append(T3[-2]);_POPt.append(t[-2]);
                        t1.append(t[-1]) 
                        if(v1.get()==0):_POPit.append(it_[-1])
                        else: _POPmedia1.append(media1_[-1])
                if(int(t[-2])>=tPS.get()):
                    if(v1.get()==0): #Método (MAYR et al., 1992) descrito para água
                        media=((T1[-2]+T2[-2]+T3[-2])/3)
                        #Valores da Curva de resposta ideal (M(t))
                        if (t[-2]<=float(tPE.get())): M=float(Tp.get())-((float(Tp.get())-float(Ts.get())))/(1+((float(Q.get())/float(Vrs.get()))*t[-2]))**(float(pat.get())/float(par.get()))
                        else:
                            M=float(Te.get())
                        #Cálculo do grau de heterogeneidade (i(t))  
                        st=(1/Nsensor)*abs((T1[-2]-M)+(T2[-2]-M)+(T3[-2]-M))
                        st2=(1/Nsensor)*abs((T1[-1]-M)+(T2[-1]-M)+(T3[-1]-M)) #Comparação entre dois valores (1) e (2) para garantia de flag
                        it=(st/(float(Te.get())-float(Ts.get())))
                        it2=(st2/(float(Te.get())-float(Ts.get()))) #Lista para comparação de i(t)
                        it_.append(it) # Lista dos valores para o gráfico
                        if(it<=itmin and k.get()==0 and it2<it):
                            tm.set(t[-2]) #Valor para linha vertical no gráfico
                            tm_.set((t[-2])-tPS.get()) #Cálculo do tempo de mistura
                            k.set(1) #Contador de execução única
                            print("\nTempo de Mistura =", float(tm_.get()),"s") 
                            tmlist.append(float(tm_.get()))  #Lista para exportação para excel
                            tmlabel() #Legendas dos resultados na janela
                        #Atualizar lista de dados do gráfico
                        _POPdados1.append(T1[-2]);_POPdados2.append(T2[-2]);_POPdados3.append(T3[-2]);_POPt.append(t[-2]);_POPit.append(it_[-1]); #Dados da lsta POP p/ gráfico
                        t1.append(t[-1]) 
                    else:
                        #Lista de valores de tempo utilizados na inclinação
                        t_1=[[t[-5],t[-4],t[-3],t[-2]]] 
                        t_2=[[t[-4],t[-3],t[-2],t[-1]]]
                        #Lista dos valores de temperatura utilizados na inclinação
                        T1_1=[T1[-5],T1[-4],T1[-3],T1[-2]];T2_1=[T2[-5],T2[-4],T2[-3],T2[-2]];T3_1=[T3[-5],T3[-4],T3[-3],T1[-2]] 
                        T1_2=[T1[-4],T1[-3],T1[-2],T1[-1]];T2_2=[T2[-4],T2[-3],T2[-2],T2[-1]];T3_2=[T3[-4],T3[-3],T3[-2],T1[-1]]
                        #Cálculo das inclinações (lineregress[0])
                        incli1_1=linregress(T1_1,t_1);incli2_1=linregress(T2_1,t_1);incli3_1=linregress(T3_1,t_1)
                        incli1_2=linregress(T1_2,t_2);incli2_2=linregress(T2_2,t_2);incli3_2=linregress(T3_2,t_2)
                        T1incli1=(incli1_1[0]);T2incli1=(incli2_1[0]);T3incli1=(incli3_1[0])
                        T1incli2=(incli1_2[0]);T2incli2=(incli2_2[0]);T3incli2=(incli3_2[0])
                        T1incli1_.append(T1incli1); T2incli1_.append(T2incli1); T3incli1_.append(T3incli1)
                        #Cálculo da média das inclinações
                        media1=(abs(T1incli1)+abs(T2incli1)+abs(T3incli1))/3
                        media2=(abs(T1incli2)+abs(T2incli2)+abs(T3incli2))/3
                        #Lista para construção do gráfico
                        media1_.append((abs(T1incli1)+abs(T2incli1)+abs(T3incli1))/3)
                        #Flag de média da inclinação em comparação com o erro indicado por e7.get())
                        if(abs((T1incli1-media1))>float(e7.get()) and abs((T1incli2-media2))>float(e7.get()) 
                           and abs((abs(T2incli1)-media1))>float(e7.get()) and abs((abs(T2incli2)-media2))>float(e7.get())
                           and abs((abs(T3incli1)-media1))>float(e7.get()) and abs((abs(T3incli2)-media2))>float(e7.get())): 
                            flag=0
                            flag_.append(flag)
                        else:
                            flag=1
                            flag_.append(flag)
                            if(k.get()==0):
                                tm.set(t[-2])
                                tm_.set((t[-2])-tPS.get())
                                print("\nTempo de Mistura =", float(tm_.get()),"s") 
                                k.set(1)
                                tmlist.append(float(tm_.get()))
                                tmlabel()    
                        _POPdados1.append(T1[-2]);_POPdados2.append(T2[-2]);_POPdados3.append(T3[-2]);_POPt.append(t[-1]);_POPmedia1.append(media1_[-2]) #Dados da lsta POP p/ gráfico
                        t1.append(t[-1]) 
                if(i>25): 
                    _POPdados1.pop(0);_POPdados2.pop(0);_POPdados3.pop(0);_POPt.pop(0); #Deletar dados p/ gráfico
                    if(v1.get()==0): _POPit.pop(0)
                    else: _POPmedia1.pop(0)
            else: #Fim do teste
                if(j.get()==v2.get()): salvar_dados_excel()
                k.set(0); w.set(0); j.set(j.get()+1); tm_.set(0); tm.set(2592000); tPS.set(2592000)
                if(j.get()>v2.get()):
                    ani.event_source.stop(); Imagem1() #Parar animação
                    ser.close() #Fechar porta serial
                    root.protocol("WM_DELETE_WINDOW", close_program)
                    #Configurar entradas
                    s1r1.configure(state = NORMAL); s1r2.configure(state = NORMAL); s2r1.configure(state = NORMAL); s2r2.configure(state = NORMAL); s2r3.configure(state = NORMAL)
                    l16.config(fg="gray"); l16.config(text='Desconectado')
            if(i>=1):
                media=(((T1[-2]+T2[-2]+T3[-2])/3))
                
                #Plot Gráfico
                #POP de dados e limite de de eixo
                if(int(t[-1])>25):
                    plot.set_xlim(_POPt[0], _POPt[-1]+5)
                else:
                    plot.set_xlim(_POPt[0], 30)
                plot.set_ylim(media-5,media+5)
                #Cores
                if(t[-1]>tm.get()):
                    line1.set_color('blue') 
                    line2.set_color('blue') 
                    line3.set_color('blue') 
                else:
                    if(t[-1]>=tPS.get()):   
                        line1.set_color('green') # Cor da linha
                        line2.set_color('green') # Cor da linha
                        line3.set_color('green') # Cor da linha
                    else:
                        line1.set_color('black') 
                        line2.set_color('black') 
                        line3.set_color('black') 
                line1.set_data(_POPt,_POPdados1) #Dados do gráfico
                line2.set_data(_POPt,_POPdados2) #Dados do gráfico
                line3.set_data(_POPt,_POPdados3) #Dados do gráfico
                plot.axvline(tPS.get(), color='b',linestyle='--') #Linha vertical de início da mistura
                plot.axvline(tm.get(), color='b',linestyle='--') #Linha vertical de fim da mistura
                if(v1.get()==0):
                    ax2.set_ylim(0, (max(_POPit)+(itmin*3)))
                    ax2.hlines(float(e6.get()), 0, 1000, color='r',linestyle=':')
                    line4.set_data(_POPt,_POPit) 
                else:
                    ax2.set_ylim(0, (max(media1_)+float(e7.get())*3))
                    line4.set_data(_POPt,_POPmedia1) 
    plotcanvas = FigureCanvasTkAgg(fig, root) #Gráfico
    plotcanvas.get_tk_widget().grid(column=0, row=0, columnspan=21, rowspan=10)
    ani = animation.FuncAnimation(fig, Tmistura, interval=785) #Animação da função Teste único
    
    #Definir botão de parada do teste
    def parar():
        ani.event_source.stop(); Imagem1() #Parar animação
        ser.close() #Fechar porta serial
        root.protocol("WM_DELETE_WINDOW", close_program)
        #Garantir que não haja perda de dados
        salvar_dados_excel()
        #Configurar entradas
        l16.config(fg="gray", text='Desconectado')
        s1r1.configure(state = NORMAL); s1r2.configure(state = NORMAL); s2r1.configure(state = NORMAL); s2r2.configure(state = NORMAL); s2r3.configure(state = NORMAL)
    #Botão de parada
    btn2 = Button(root, text="Desconectar", command=parar, bg='gray95', fg='black', width=15, height=2, justify=RIGHT, font="bold 8", bd=2)
    btn2.grid(column=16, row=10, rowspan=18, columnspan=4)
Ejemplo n.º 13
0
#Interface
spacer=Label(root); spacer.grid(row=10, column=1)
spacer=Label(root); spacer.grid(row=15, column=15)

#Imagem de fundo
root.original = Image.open('bg.png') #Nome da imagem - Local da imagem > pasta do arquivo
resized = root.original.resize((1250, 675),Image.ANTIALIAS) #Mudança de escala
root.image = ImageTk.PhotoImage(resized) 
root.display = Label(root, image = root.image)
root.display.grid(row=0, column=0, columnspan=40, rowspan=35) #Local na janela
root.display.configure(background='white')

#Gráfico 
fig=Figure(figsize=(10,4), dpi=100) #Tamanho e qualidade da figura
plot=fig.add_subplot(1,1,1) #Figura = Gráfico em subplot do Matlib
plotcanvas = FigureCanvasTkAgg(fig, root) #Gráfico
plotcanvas.get_tk_widget().grid(column=0, row=0, columnspan=21, rowspan=10)
plot.set_xlabel('Tempo (s)', color='k') #Legenda de eixo x
plot.set_ylabel('Temperatura (°C)', color='k') # Legenda de eixo y

#Legendas e entrada das variáveis
#Parâmetros iniciais
#Entrada e Legenda 1: Duração do pulso
text1=StringVar()#Nome da variável
e1=Entry(root,textvariable=text1, width=10, justify=RIGHT, font="bold 10", relief="groove", bd=2)#Entrada do usuário
e1.grid(row=11, column=3)#Local da entrada na janela
e1.insert(END, '1.5')#Valor padrão da célula
l1=Label(root, text="Duração do pulso (s)", relief="flat", font= "Arial 9", width=20, anchor=E, justify=RIGHT, bg='white') #Legenda
l1.grid (row=11, column=2)#Local da legenda na janela
#Entrada e Legenda 2: Volume total (m3)
text2=StringVar()
Ejemplo n.º 14
0
    def shannon_diversity_all_samples(self, working_samples, samples_list,
                                      tax_level):
        from skbio.diversity.alpha import shannon
        self.create_window()
        self.top.title('Shannon diversity')

        self.top.title('overview of Shannon index of all samples on ' +
                       tax_level + ' level')
        self.inner_frame = Frame(self.frame)
        self.inner_frame.grid(row=1, column=0, columnspan=4)

        top_space = 20
        width = 600
        if len(samples_list) > 20:
            width = 1000

        #shannon index (alpha diversity)
        if self.abundance_df.groupAbsoluteSamples() is not None:
            absolut_working_samples = self.abundance_df.groupAbsoluteSamples()
            absolut_working_samples = absolut_working_samples[
                samples_list].astype('int')
            shannon0 = absolut_working_samples.loc[[
                tax + '_' for tax in list(working_samples[tax_level])
            ]].apply(shannon)
        else:
            shannon0 = []
            for sample in samples_list:
                shannon0.append(
                    shannon_index(working_samples[sample].as_matrix()))
            shannon0 = pd.Series(shannon0, index=samples_list)

        fig = Figure(figsize=(4, 6), dpi=120)  #, tight_layout=True)
        ax = fig.add_subplot(211)
        bp = ax.boxplot(shannon0)
        for val, in zip(shannon0):
            x = x = np.random.normal(1, 0.04, 1)
            ax.scatter(x, val, c='grey', marker='.', alpha=0.4)
        ax.set_xticklabels(['Shannon diversity'])
        #ax.set_ylabel('number of species')

        ax = fig.add_subplot(212)
        for i, val in enumerate(shannon0):
            ax.scatter(shannon0.index[i], val, marker='.')
        ax.set_xticklabels(shannon0.index, fontsize=8, rotation='vertical')
        ax.set_xlabel('samples')
        ax.set_ylabel('Shannon diversity index')
        fig.subplots_adjust(left=0.1,
                            right=0.98,
                            bottom=0.2,
                            top=0.95,
                            hspace=0.3,
                            wspace=0.3)

        matplotlib_frame = Frame(self.frame)
        matplotlib_frame.grid(row=2, column=0, rowspan=2, columnspan=2)
        canvas = FigureCanvasTkAgg(fig, matplotlib_frame)
        canvas.draw()
        canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)

        save_button = Button(
            self.inner_frame,
            text="Save (high resolution)",
            command=lambda fig=fig, title='Shannon diversity', initialfile=
            'shannon_all_samples': self.save_high_resolution_figure(
                fig, title, initialfile))
        save_button.grid(row=1, column=0)
Ejemplo n.º 15
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
Ejemplo n.º 16
0
    def on_trace_change(self, _name, _index, _mode):
        """Updates the number of plans with options dependent on number of benefits input."""
        for group in self.groups:
            group.grid_forget()
            group.destroy()
        self.groups = []
        rad_labels = [
            "Exact", "Gaussian", "Triangular", "Rectangular", "Discrete"
        ]
        figs = [
            none_dist(),
            gauss_dist(),
            tri_dist(),
            rect_dist(),
            disc_dist()
        ]
        self.choices = [[tk.StringVar() for ben in plan.bens.indiv]
                        for plan in self.data_cont.plan_list]
        rads = []
        self.ranges = []
        self.labels = []
        for plan in self.data_cont.plan_list:
            r_idx = 0
            self.groups.append(ttk.LabelFrame(self, text=plan.name))
            self.groups[-1].grid(row=4 + plan.num,
                                 sticky="ew",
                                 padx=FIELDX_PADDING,
                                 pady=FIELDY_PADDING)
            rads.append([])
            self.ranges.append([])
            self.labels.append([])
            for ben in plan.bens.indiv:
                choice = plan.bens.indiv.index(ben)
                self.choices[plan.num][choice].set(ben.dist)
                titles = ttk.Label(self.groups[-1],
                                   text=ben.title + " - $" +
                                   '{:,.2f}'.format(ben.amount),
                                   font=SMALL_FONT)
                titles.grid(row=r_idx,
                            column=0,
                            sticky="w",
                            padx=FIELDX_PADDING,
                            pady=FIELDY_PADDING)
                var = self.choices[plan.num][choice]
                rads[plan.num].append([
                    tk.Radiobutton(self.groups[-1], variable=var,
                                   value="none"),
                    tk.Radiobutton(self.groups[-1],
                                   variable=var,
                                   value="gauss"),
                    tk.Radiobutton(self.groups[-1], variable=var, value="tri"),
                    tk.Radiobutton(self.groups[-1], variable=var,
                                   value="rect"),
                    tk.Radiobutton(self.groups[-1],
                                   variable=var,
                                   value="discrete")
                ])
                self.ranges[plan.num].append([
                    tk.Entry(self.groups[-1],
                             width=int(ENTRY_WIDTH / 2),
                             font=SMALL_FONT) for i in range(6)
                ])
                self.labels[plan.num].append([])
                for col in range(5):
                    fig_label = ttk.Label(self.groups[-1])
                    fig_label.grid(row=r_idx + 1, column=col)
                    fig = figs[col]
                    canvas = FigureCanvasTkAgg(fig, master=fig_label)
                    canvas.get_tk_widget().grid(row=1, column=col + 1)
                    canvas.show()
                    rads[plan.num][choice][col].grid(row=r_idx + 3, column=col)
                    rad_label = ttk.Label(self.groups[-1],
                                          text=rad_labels[col],
                                          font=SMALL_FONT)
                    rad_label.grid(row=r_idx + 2, column=col)

                if self.choices[plan.num][choice].get() == "none":
                    r_idx += 4
                    for entry in self.ranges[plan.num][choice]:
                        entry.grid_remove()
                elif self.choices[plan.num][choice].get() == "gauss":
                    self.labels[plan.num][choice] = [
                        tk.Label(self.groups[-1],
                                 text="Standard Deviation ($)")
                    ]
                    self.labels[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=0)
                    for entry in self.ranges[plan.num][choice]:
                        entry.grid_remove()
                    self.ranges[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=1)
                    r_idx += 5
                elif self.choices[plan.num][choice].get() == "discrete":
                    self.labels[plan.num][choice] = [
                        tk.Label(self.groups[-1], text="Lowest Amount ($)"),
                        tk.Label(self.groups[-1], text="Middle Amount ($)"),
                        tk.Label(self.groups[-1], text="Highest Amount ($)"),
                        tk.Label(self.groups[-1],
                                 text="Likelihood of Lowest Amount (%)"),
                        tk.Label(self.groups[-1],
                                 text="Likelihood of Middle Amount (%)"),
                        tk.Label(self.groups[-1],
                                 text="Likelihood of Highest Amount (%)")
                    ]
                    for label in self.labels[plan.num][choice][0:3]:
                        label.grid(row=r_idx +
                                   self.labels[plan.num][choice].index(label) +
                                   5,
                                   column=0)
                    for label in self.labels[plan.num][choice][3:6]:
                        label.grid(row=r_idx +
                                   self.labels[plan.num][choice].index(label) +
                                   2,
                                   column=2)
                    for entry in self.ranges[plan.num][choice][0:3]:
                        entry.grid(row=r_idx +
                                   self.ranges[plan.num][choice].index(entry) +
                                   5,
                                   column=1,
                                   padx=FIELDX_PADDING,
                                   pady=FIELDY_PADDING)
                    for entry in self.ranges[plan.num][choice][3:6]:
                        entry.grid(row=r_idx +
                                   self.ranges[plan.num][choice].index(entry) +
                                   2,
                                   column=3,
                                   padx=FIELDX_PADDING,
                                   pady=FIELDY_PADDING)
                    r_idx += 8
                else:
                    self.labels[plan.num][choice] = [
                        tk.Label(self.groups[-1], text="Lower Bound ($)"),
                        tk.Label(self.groups[-1], text="Upper Bound ($)")
                    ]
                    self.labels[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=0)
                    self.labels[plan.num][choice][1].grid(row=r_idx + 4,
                                                          column=2)
                    for entry in self.ranges[plan.num][choice]:
                        entry.grid_remove()
                    self.ranges[plan.num][choice][0].grid(row=r_idx + 4,
                                                          column=1)
                    self.ranges[plan.num][choice][1].grid(row=r_idx + 4,
                                                          column=3)
                    r_idx += 5
                for entry in self.ranges[plan.num][choice]:
                    try:
                        text = ben.range[self.ranges[plan.num][choice].index(
                            entry)]
                        text = '{:,.2f}'.format(float(text))
                    except ValueError:
                        text = ben.range[self.ranges[plan.num][choice].index(
                            entry)]
                    entry.insert(tk.END, text)
    def __init__(self,parent,*args, **kwargs):
        super().__init__(parent,*args, **kwargs)
    
# =============================================================================
#        1    
# =============================================================================
        self.f1 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a1 = self.f1.add_subplot(111)  
        
        self.canvas1 = FigureCanvasTkAgg(self.f1,self)
        self.canvas1.draw()
        self.canvas1.get_tk_widget().grid(row =0,rowspan=2,column = 0,sticky = 'nswe')      
        
# =============================================================================
#         2
# =============================================================================
        self.f2 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a2 = self.f2.add_subplot(111)       
        
        self.canvas2 = FigureCanvasTkAgg(self.f2,self)
        self.canvas2.draw()
        self.canvas2.get_tk_widget().grid(row =0,rowspan=2,column = 1,sticky = 'nswe')
# =============================================================================
#         3
# =============================================================================
        self.f3 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a3 = self.f3.add_subplot(111)
      
        self.canvas3 = FigureCanvasTkAgg(self.f3,self)
        self.canvas3.draw()
        self.canvas3.get_tk_widget().grid(row =0,rowspan=2,column = 2,sticky = 'nswe')        
# =============================================================================
#         4
# =============================================================================
        self.f4 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a4 = self.f4.add_subplot(111)      
        
        self.canvas4 = FigureCanvasTkAgg(self.f4,self)
        self.canvas4.draw()
        self.canvas4.get_tk_widget().grid(row =0,rowspan=2,column = 3,sticky = 'nswe')         
        
# =============================================================================
#         5
# =============================================================================
        self.f5 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a5 = self.f5.add_subplot(111)

        self.canvas5 = FigureCanvasTkAgg(self.f5,self)
        self.canvas5.draw()
        self.canvas5.get_tk_widget().grid(row =0,rowspan=2,column = 4,sticky = 'nswe') 
        
# =============================================================================
#       6          
# =============================================================================
        self.f6 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a6 = self.f6.add_subplot(111)   
        
        self.canvas6 = FigureCanvasTkAgg(self.f6,self)
        self.canvas6.draw()
        self.canvas6.get_tk_widget().grid(rowspan=3,row=2,column = 0,sticky = 'nse') 
        
# =============================================================================
#         7
# =============================================================================
        self.f7 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a7 = self.f7.add_subplot(111)

        self.canvas7 = FigureCanvasTkAgg(self.f7,self)
        self.canvas7.draw()
        self.canvas7.get_tk_widget().grid(rowspan=3,row=2,column = 1,sticky = 'nswe')       
        
# =============================================================================
#         8
# =============================================================================   
        self.f8 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a8 = self.f8.add_subplot(111)
          
        self.canvas8 = FigureCanvasTkAgg(self.f8,self)
        self.canvas8.draw()
        self.canvas8.get_tk_widget().grid(rowspan=3,row=2,column = 2,sticky = 'nswe')      
        
# =============================================================================
#         9
# =============================================================================
        self.f9 = Figure(figsize = (1,1.7), dpi =100,tight_layout=True)
        self.a9 = self.f9.add_subplot(111)

        self.canvas9 = FigureCanvasTkAgg(self.f9,self)
        self.canvas9.draw()
        self.canvas9.get_tk_widget().grid(rowspan=3,row=2,column = 3,sticky = 'nswe')   
 

# =============================================================================
# Create sub frame to contins all buttons
# =============================================================================
#        self.subframe = Frame(self)
#        self.subframe.grid(row =1,columnspan = 2,column = 4,sticky = 'nwes')
  
# =============================================================================
#         status label status
# =============================================================================
        self.status_var = StringVar()
        self.status_label = Label(self,textvariable = self.status_var,font =('Times 10 bold'),
                            bg='white')
        self.status_var.set('Start')
        self.status_label.grid(row =0,column = 6,sticky = 's')
                         
# =============================================================================
#        botton status       
# =============================================================================
        self.botton = Button(self,text = "Change Update", command = lambda : onClick_status(parent))
        self.botton.grid(row =1,column = 6,sticky = 'n')
    

# =============================================================================
# entry1 
# =============================================================================
        self.entry1_var = StringVar()
        self.entry1 = Entry(self, textvariable = self.entry1_var,relief = 'sunken', bd = 2,font =('Times 14 bold'))
        self.entry1_var.set(parent.select_date)
        self.entry1.grid(row =2,column = 6,sticky = 's')
    
# =============================================================================
# entry2
# =============================================================================
        self.entry2_var = StringVar()
        self.entry2 = Entry(self, textvariable = self.entry2_var,relief = 'sunken', bd = 2,font =('Times 14 bold'))
        self.entry2_var.set(parent.select_end_date)
        self.entry2.grid(row =3,column = 6)
        
# =============================================================================
#        botton date      
# =============================================================================
        self.botton = Button(self,text = "Change date", command = lambda : onClick_date(parent))
        self.botton.grid(row =4,column = 6,sticky = 'n')        
Ejemplo n.º 18
0
    def do_plot(self):
        if self.plate != int(self.e1.get()) or self.mjd != int(self.e2.get()):
            self.plate = int(self.e1.get())
            self.mjd = int(self.e2.get())
            self.fiber = int(self.e3.get())
            self.znum = int(self.e5.get())
            self.platepath = join(environ['BOSS_SPECTRO_REDUX'],
                                  environ['RUN2D'], '%s' % self.plate,
                                  'spPlate-%s-%s.fits' % (self.plate, self.mjd))
            hdu = fits.open(self.platepath)
            self.specs = hdu[0].data
            self.wave = 10**(hdu[0].header['COEFF0'] +
                             n.arange(hdu[0].header['NAXIS1']) *
                             hdu[0].header['COEFF1'])
            self.models = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[2].data
            self.fiberid = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                          environ['RUN2D'], '%s' % self.plate,
                                          environ['RUN1D'],
                                          'redmonster-%s-%s.fits' %
                                          (self.plate,
                                           self.mjd)))[1].data.FIBERID
            self.type1 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS1
            self.type2 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS2
            self.type3 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS3
            self.type4 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS4
            self.type5 = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                        environ['RUN2D'], '%s' % self.plate,
                                        environ['RUN1D'],
                                        'redmonster-%s-%s.fits' %
                                        (self.plate, self.mjd)))[1].data.CLASS5
            self.z = n.zeros((self.fiberid.shape[0],5))
            self.z[:,0] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z1
            self.z[:,1] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z2
            self.z[:,2] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z3
            self.z[:,3] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z4
            self.z[:,4] = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                         environ['RUN2D'], '%s' % self.plate,
                                         environ['RUN1D'],
                                         'redmonster-%s-%s.fits' %
                                         (self.plate, self.mjd)))[1].data.Z5
            self.zwarning = fits.open(join(environ['REDMONSTER_SPECTRO_REDUX'],
                                           environ['RUN2D'], '%s' % self.plate,
                                           environ['RUN1D'],
                                           'redmonster-%s-%s.fits' %
                                           (self.plate,
                                            self.mjd)))[1].data.ZWARNING
        else:
            self.fiber = int(self.e3.get())
        f = Figure(figsize=(10,6), dpi=100)
        a = f.add_subplot(111)
        loc = n.where(self.fiberid == self.fiber)[0]
        if self.znum == 1:
            z = self.z[loc[0],0]
            thistype = self.type1[loc[0]]
        elif self.znum == 2:
            z = self.z[loc[0],1]
            thistype = self.type2[loc[0]]
        elif self.znum == 3:
            z = self.z[loc[0],2]
            thistype = self.type3[loc[0]]
        elif self.znum == 4:
            z = self.z[loc[0],3]
            thistype = self.type4[loc[0]]
        elif self.znum == 5:
            z = self.z[loc[0],4]
            thistype = self.type5[loc[0]]
        if self.var.get() == 0:
            if self.restframe.get() == 0:
                a.plot(self.wave, self.specs[self.fiber], color='black')
            elif self.restframe.get() == 1:
                a.plot(self.wave/(1+self.z[loc][0]), self.specs[self.fiber],
                       color='black')
        elif self.var.get() == 1:
            smooth = self.e4.get()
            if smooth is '':
                if self.restframe.get() == 0:
                    a.plot(self.wave, self.specs[self.fiber], color='black')
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), self.specs[self.fiber],
                           color='black')
            else:
                if self.restframe.get() == 0:
                    a.plot(self.wave, convolve(self.specs[self.fiber],
                                               Box1DKernel(int(smooth))),
                           color='black')
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), convolve(self.specs[self.fiber],
                                                     Box1DKernel(int(smooth))),
                           color='black')
            # Overplot model
            if len(loc) is not 0:
                if self.restframe.get() == 0:
                    #a.plot(self.wave, self.models[loc[0]], color='black')
                    # This for when multiple models are in redmonster file
                    a.plot(self.wave, self.models[loc[0],self.znum-1],
                           color='cyan')
                    if self.ablines.get() == 1:
                        for i, line in enumerate(self.ablinelist):
                            if ((line*(1+z) > self.wave[0]) &
                                    (line*(1+z) < self.wave[-1])):
                                a.axvline(line*(1+z), color='blue',
                                          linestyle='--',
                                          label=self.ablinenames[i])
                    if self.emlines.get() == 1:
                        for i, line in enumerate(self.emlinelist):
                            if (line*(1+z) > self.wave[0]) & (line*(1+z) < \
                                                              self.wave[-1]):
                                a.axvline(line*(1+z), color='red',
                                          linestyle='--',
                                          label=self.emlinenames[i])
                    if self.ablines.get() == 1 or self.emlines.get() == 1:
                        a.legend(prop={'size':10})
                elif self.restframe.get() == 1:
                    a.plot(self.wave/(1+z), self.models[loc[0],self.znum-1],
                           color='cyan')
                    if self.ablines.get() == 1:
                        for i, line in enumerate(self.ablinelist):
                            if (line > self.wave[0]) & (line < self.wave[-1]):
                                a.axvline(line, color='blue', linestyle='--',
                                          label=self.ablinenames[i])
                    if self.emlines.get() == 1:
                        for i, line in enumerate(self.emlinelist):
                            if (line > self.wave[0]) & (line < self.wave[-1]):
                                a.axvline(line, color='red', linestyle='--',
                                          label=self.emlinenames[i])
                    if self.ablines.get() == 1 or self.emlines.get() == 1:
                        a.legend(prop={'size':10})
                a.set_title('Plate %s Fiber %s: z=%s class=%s zwarning=%s' %
                            (self.plate, self.fiber, z, thistype,
                             self.zwarning[loc[0]]))
            else:
                print('Fiber %s is not in redmonster-%s-%s.fits' % \
                        (self.fiber, self.plate, self.mjd))
                a.set_title('Plate %s Fiber %s' % (self.plate, self.fiber))

        if self.restframe.get() == 1:
            lower_data, upper_data = self.set_limits()
            a.axis([self.wave[0]/(1+z)-100,self.wave[-1]/(1+z)+100,
                    lower_data,upper_data])
        elif self.restframe.get() == 0:
            lower_data, upper_data = self.set_limits()
            a.axis([self.wave[0]-100,self.wave[-1]+100,lower_data,upper_data])
        a.set_xlabel('Wavelength ($\AA$)')
        a.set_ylabel('Flux ($10^{-17} erg\ cm^2 s^{-1} \AA^{-1}$)')
        canvas = FigureCanvasTkAgg(f, master=self.root)
        canvas.get_tk_widget().grid(row=0, column=5, rowspan=20)
        toolbar_frame = Frame(self.root)
        toolbar_frame.grid(row=20,column=5)
        toolbar = NavigationToolbar2TkAgg( canvas, toolbar_frame )
        canvas.show()
Ejemplo n.º 19
0
yOut = []

# Values/lists for evaluation the read/write frequency
startTime = 0
stopTime = 0
count = 0
timeList = []
logVals = True

# Generate some start/example data
X = 0
Y = 0
# Setup the graph
fig = Figure(figsize=(5, 3), dpi=100)
ax = fig.add_subplot(1, 1, 1)
line1, = ax.plot(X, Y)
ax.set_title("Input Signal")
canvas = FigureCanvasTkAgg(fig, root)
canvas.get_tk_widget().grid(row=0, column=2)

with nidaqmx.Task() as inputTask, nidaqmx.Task() as outputTask, nidaqmx.Task(
) as digitalInputTask:
    device = "Dev1"
    digitalInputTask.di_channels.add_di_chan(device + "/port0/line0")
    inputTask.ai_channels.add_ai_voltage_chan(device + "/ai0")
    outputTask.ao_channels.add_ao_voltage_chan(
        device + "/ao0", min_val=0, max_val=5)  # bei usb 6001 max_val = 10
    inputTask.start()
    outputTask.start()
    root.mainloop()
Ejemplo n.º 20
0
    def __init__(self):
        rospy.init_node('para_tune', anonymous=True)
        self.state_changer = rospy.Publisher('/AUVmanage/state',
                                             Int32,
                                             queue_size=1)
        self.call_param_dump = rospy.Publisher('/AUVmanage/dumpparam',
                                               Int32,
                                               queue_size=1)
        win = tk.Tk()
        win.title('Dummy motor')
        win.wm_geometry("3000x2000")
        scale_frame = tk.Frame(win)
        scale_frame.grid(row=1, column=1)
        graph = tk.Frame(win)
        graph.grid(row=1, column=2)
        start_frame = tk.Frame(win)
        start_frame.grid(row=1, column=3)
        ################################################################################
        #                               depth PID                                      #
        ################################################################################
        depth_PID = rospy.get_param('/PIDpara/depth')
        depth_PID_digit = []
        depth_PID_num = []
        for i in depth_PID:
            a, b = get_digit(i)
            depth_PID_digit.append(a)
            depth_PID_num.append(b)
        combox_num = range(-5, 5, 1)
        tk.Label(scale_frame, text='depth_P').grid(row=1, column=0)
        self.s_d_P = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_d_P.set(depth_PID_num[0])
        self.s_d_P.grid(row=1, column=1)
        self.combo_d_P = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_d_P.current(depth_PID_digit[0] + 5)
        self.combo_d_P.grid(row=1, column=2)
        tk.Label(scale_frame, text='depth_I').grid(row=2, column=0)
        self.s_d_I = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_d_I.set(depth_PID_num[1])
        self.s_d_I.grid(row=2, column=1)
        self.combo_d_I = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_d_I.current(depth_PID_digit[1] + 5)
        self.combo_d_I.grid(row=2, column=2)
        tk.Label(scale_frame, text='depth_D').grid(row=3, column=0)
        self.s_d_D = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_d_D.set(depth_PID_num[2])
        self.s_d_D.grid(row=3, column=1)
        self.combo_d_D = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_d_D.current(depth_PID_digit[2] + 5)
        self.combo_d_D.grid(row=3, column=2)
        tk.Button(scale_frame, text='set depth param',
                  command=self.set_depth).grid(row=1, column=5)
        tk.Button(scale_frame,
                  text='dump depth param',
                  command=self.dump_depth).grid(row=2, column=5)

        ################################################################################
        #                               altitude PID                                   #
        ################################################################################
        altitude_PID = rospy.get_param('/PIDpara/altitude')
        altitude_PID_digit = []
        altitude_PID_num = []
        for i in altitude_PID:
            a, b = get_digit(i)
            altitude_PID_digit.append(a)
            altitude_PID_num.append(b)
        combox_num = range(-5, 5, 1)
        tk.Label(scale_frame, text='altitude_P').grid(row=4, column=0)
        self.s_a_P = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_a_P.set(altitude_PID_num[0])
        self.s_a_P.grid(row=4, column=1)
        self.combo_a_P = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_a_P.current(altitude_PID_digit[0] + 5)
        self.combo_a_P.grid(row=4, column=2)
        tk.Label(scale_frame, text='altitude_I').grid(row=5, column=0)
        self.s_a_I = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_a_I.set(altitude_PID_num[1])
        self.s_a_I.grid(row=5, column=1)
        self.combo_a_I = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_a_I.current(altitude_PID_digit[1] + 5)
        self.combo_a_I.grid(row=5, column=2)
        tk.Label(scale_frame, text='altitude_D').grid(row=6, column=0)
        self.s_a_D = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_a_D.set(altitude_PID_num[2])
        self.s_a_D.grid(row=6, column=1)
        self.combo_a_D = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_a_D.current(altitude_PID_digit[2] + 5)
        self.combo_a_D.grid(row=6, column=2)
        tk.Button(scale_frame,
                  text='set altitude param',
                  command=self.set_altitude).grid(row=4, column=5)
        tk.Button(scale_frame,
                  text='dump altitude param',
                  command=self.dump_altitude).grid(row=5, column=5)

        ################################################################################
        #                               yaw tune                                   #
        ################################################################################
        yaw = rospy.get_param('/PIDpara/yaw')
        if yaw[0] >= 0:
            yaw_digit, yaw_num = get_digit(yaw[0])
        else:
            yaw_digit, yaw_num = get_digit(-yaw[0])
            yaw_num = -yaw_num
        yaw_PID_digit = []
        yaw_PID_num = []
        for i in yaw[1:]:
            a, b = get_digit(i)
            yaw_PID_digit.append(a)
            yaw_PID_num.append(b)
        combox_num = range(-5, 5, 1)
        tk.Label(scale_frame, text='yaw tune').grid(row=7, column=0)
        self.s_y = tk.Scale(scale_frame,
                            from_=-10,
                            to=10,
                            orient=tk.HORIZONTAL,
                            length=200,
                            showvalue=1,
                            tickinterval=5,
                            resolution=0.01,
                            command=print_selec_value)
        self.s_y.set(yaw_num)
        self.s_y.grid(row=7, column=1)
        self.combo_y = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y.current(yaw_digit + 5)
        self.combo_y.grid(row=7, column=2)

        tk.Label(scale_frame, text='yaw_P').grid(row=8, column=0)
        self.s_y_P = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_y_P.set(yaw_PID_num[0])
        self.s_y_P.grid(row=8, column=1)
        self.combo_y_P = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y_P.current(yaw_PID_digit[0] + 5)
        self.combo_y_P.grid(row=8, column=2)
        tk.Label(scale_frame, text='yaw_I').grid(row=9, column=0)
        self.s_y_I = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_y_I.set(yaw_PID_num[1])
        self.s_y_I.grid(row=9, column=1)
        self.combo_y_I = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y_I.current(altitude_PID_digit[1] + 5)
        self.combo_y_I.grid(row=9, column=2)
        tk.Label(scale_frame, text='yaw_D').grid(row=10, column=0)
        self.s_y_D = tk.Scale(scale_frame,
                              from_=0,
                              to=9.99,
                              orient=tk.HORIZONTAL,
                              length=200,
                              showvalue=1,
                              tickinterval=3,
                              resolution=0.01,
                              command=print_selec_value)
        self.s_y_D.set(altitude_PID_num[2])
        self.s_y_D.grid(row=10, column=1)
        self.combo_y_D = ttk.Combobox(scale_frame, values=combox_num, width=5)
        self.combo_y_D.current(altitude_PID_digit[2] + 5)
        self.combo_y_D.grid(row=10, column=2)

        tk.Button(scale_frame, text='set yaw tune param',
                  command=self.set_yaw).grid(row=7, column=5)
        tk.Button(scale_frame,
                  text='dump yaw tune param',
                  command=self.dump_yaw).grid(row=8, column=5)
        ################################################################################
        #                               matplotlib graph                               #
        ################################################################################
        #===============      for depth  ====================#
        self.x_count = 0
        self.depth_x = np.arange(0, 100)
        self.ddata = np.zeros(100)
        self.depth_fig = Figure(figsize=(5, 3), dpi=100)
        self.depth_ax = self.depth_fig.add_subplot(111)
        self.depth_ax.set_ylim((0, 2))
        self.depth_ax.invert_yaxis()
        self.depth_ax.set_title("depth")
        self.canvas_d = FigureCanvasTkAgg(self.depth_fig, master=graph)
        self.canvas_d.show()
        self.canvas_d.get_tk_widget().pack(side=tk.TOP, fill="both")
        rospy.Subscriber("/depth", Float32, self.depth_back, queue_size=1)
        ################################################################################
        #                               kill bottom                                    #
        ################################################################################
        self.countdowner = rospy.Publisher('/AUVmanage/countdowner',
                                           Int32MultiArray,
                                           queue_size=1)
        self.e = tk.Entry(start_frame)
        self.e.grid(row=1, column=1)
        self.cd_remaining = 0
        self.countdown_label = tk.Label(start_frame, text="", width=10)
        self.countdown_label.grid(row=1, column=2)
        self.coutdown_var = 0
        self.start_button = tk.Button(start_frame,
                                      text='Press to start',
                                      command=self.state2one).grid(row=2,
                                                                   column=1)
        self.stop_button = tk.Button(start_frame,
                                     text='Press to stop',
                                     command=self.state2zero).grid(row=2,
                                                                   column=2)
        self.stop_button = tk.Button(start_frame,
                                     text='stop but count',
                                     command=self.state2two).grid(row=2,
                                                                  column=3)
        self.stop_button = tk.Button(start_frame,
                                     text='go forward',
                                     command=self.state2three).grid(row=2,
                                                                    column=4)
        win.mainloop()
Ejemplo n.º 21
0
PlotFrame = Frame(root, width=512, height=512)
PlotFrame.pack(side=TOP, fill=BOTH, expand=True)

f = Figure(figsize=(5, 5), dpi=100)
velocities = np.linspace(0, 500000, 500000)
Plots = f.add_subplot(111)
Plots.plot(velocities,
           MBDistribution(velocities, Temperature.get()),
           label='Maxwell-Boltzmann')
Plots.plot(velocities,
           FDDistribution(velocities, Temperature.get(), 1000),
           label='Fermi-Dirac')
Plots.legend()

canvas = FigureCanvasTkAgg(f, PlotFrame)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)

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

Slider = Scale(root,
               length=512,
               sliderlength=15,
               from_=10,
               to=1000,
               orient=HORIZONTAL,
               variable=Temperature,
               label='Temperature',
Ejemplo n.º 22
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.configure(background='black')
        label = tk.Label(self,
                         text="Demo Page",
                         font=HEADER1,
                         background='black',
                         foreground='#c5d0e2')
        label.pack(pady=10, padx=10)

        photo1 = tk.PhotoImage(file='backk.png')

        button1 = tk.Button(self,
                            compound=tk.TOP,
                            width=143,
                            height=48,
                            command=lambda: controller.show_frame(PageOne),
                            image=photo1,
                            relief=FLAT,
                            bd=0,
                            highlightthickness=0,
                            bg='black',
                            activebackground='black',
                            padx=0,
                            pady=0)
        button1.pack()
        #button1.pack()
        button1.image = photo1

        LeftFrame = tk.Frame(self)
        LeftFrame.configure(background='black')
        LeftFrame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1, anchor=tk.N)

        f = Figure(figsize=(5, 5), dpi=100)
        ax1 = f.add_subplot(421)
        ax2 = f.add_subplot(422)
        ax3 = f.add_subplot(423)
        ax4 = f.add_subplot(424)
        ax5 = f.add_subplot(425)
        ax6 = f.add_subplot(426)
        ax7 = f.add_subplot(427)
        ax8 = f.add_subplot(428)

        #ax1 = fig.add_pyplot()
        canvas = FigureCanvasTkAgg(f, LeftFrame)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        RightFrame = tk.Frame(self)
        RightFrame.configure(background='black')
        RightFrame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=1, anchor=tk.N)

        heading = tk.Label(RightFrame,
                           text='Readings : ',
                           font=HEADER2,
                           background='black',
                           foreground='#42f4e2')
        heading.pack()

        v = StringVar(RightFrame, value='No Connection')

        entry_1 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)
        entry_2 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)
        entry_3 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)
        entry_4 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)
        entry_5 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)
        entry_6 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)
        entry_7 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)
        entry_8 = tk.Entry(RightFrame,
                           width=10,
                           background='black',
                           foreground='#42f4e2',
                           relief=FLAT,
                           highlightthickness=0,
                           bd=15)

        entry_1.pack()
        entry_2.pack()
        entry_3.pack()
        entry_4.pack()
        entry_5.pack()
        entry_6.pack()
        entry_7.pack()
        entry_8.pack()

        demo_thread_controller = demo_thread(entry_1, entry_2, entry_3,
                                             entry_4, entry_5, entry_6,
                                             entry_7, entry_8, ax1, ax2, ax3,
                                             ax4, ax5, ax6, ax7, ax8, canvas)
        demo_thread_controller.start()
Ejemplo n.º 23
0
 def setup_matplotlib_figure(self):
     self.fig = Figure(figsize=(5, 3), dpi=120)
     self.canvas = FigureCanvasTkAgg(self.fig, master=self.graph_frame)  # A tk.DrawingArea.
     self.canvas.draw()
     self.canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
Ejemplo n.º 24
0
root1 = Tk()
root1.geometry("800x450")
root1.title("STATEWISE-DATA")
root1.configure(background='white')
f1 = ("poppins", 7, "bold")
mainLabel1 = Label(root1, text="COVID-19 CASES STATE WISE").pack()
mainLabel1 = Label(root1, text=printtable(), font=f1, bg='pink').pack()
root1.mainloop()
#THIS IS THE GRAPH OF COVI-19 STATE WISE
root2 = Tk()
root2.geometry("800x450")
root2.title("STATEWISE GRAPH")
root2.configure(background='white')
figure1 = plt.Figure(figsize=(10, 5), dpi=100)
ax1 = figure1.add_subplot(111)
bar1 = FigureCanvasTkAgg(figure1, root2)
bar1.get_tk_widget().pack()
df1 = df1[['states', 'confirmed']].groupby('states').sum()
df1.plot(kind='barh', legend=True, ax=ax1)
ax1.set_xlabel('Confirmed Cases in States')
ax1.set_title('State vs Confirmed Cases')
root2.mainloop()
# IT IS THE FUNCTION TO CALLING THE NOTIFICATION
if __name__ == "__main__":
    print(get_corona_detail())
    print(printtable())
    myHtmlData = getData('https://www.mohfw.gov.in/')
    soup = BeautifulSoup(myHtmlData, 'html.parser')
    myDatastr = ""
    for tr in soup.find_all('tbody')[0].find_all('tr'):
        myDatastr = tr.get_text()
Ejemplo n.º 25
0
data3 = {
    'Interest_Rate': [5, 5.5, 6, 5.5, 5.25, 6.5, 7, 8, 7.5, 8.5],
    'Stock_Index_Price':
    [1500, 1520, 1525, 1523, 1515, 1540, 1545, 1560, 1555, 1565]
}
df3 = DataFrame(data3, columns=['Interest_Rate', 'Stock_Index_Price'])

root = tk.Tk()

import matplotlib.backends.backend_tkagg as tkagg

# canvas is your canvas, and root is your parent (Frame, TopLevel, Tk instance etc.)

figure1 = plt.Figure(figsize=(6, 5), dpi=100)
ax1 = figure1.add_subplot(111)
bar1 = FigureCanvasTkAgg(figure1, root)

tkagg.NavigationToolbar2Tk(bar1, root)

bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
df1 = df1[['Country', 'GDP_Per_Capita']].groupby('Country').sum()
df1.plot(kind='bar', legend=True, ax=ax1)
ax1.set_title('Country Vs. GDP Per Capita')

figure2 = plt.Figure(figsize=(5, 4), dpi=100)
ax2 = figure2.add_subplot(111)
line2 = FigureCanvasTkAgg(figure2, root)
line2.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
df2 = df2[['Year', 'Unemployment_Rate']].groupby('Year').sum()
df2.plot(kind='line', legend=True, ax=ax2, color='r', marker='o', fontsize=10)
ax2.set_title('Year Vs. Unemployment Rate')
Ejemplo n.º 26
0
                 width=150,
                 height=1,
                 pady=5,
                 padx=0,
                 relief="flat",
                 anchor=CENTER,
                 font=("arial 10"),
                 bg=col3,
                 fg=col2)
app_name.pack()

#########################################################################################3
fig = Figure(figsize=(7, 2), dpi=100)
fig.add_subplot(111).plot(x, y)

canvas = FigureCanvasTkAgg(fig, master=app)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().place(x=100, y=220)

b1 = Button(app,
            text="REFRESH",
            width=120,
            height=3,
            bg=col4,
            fg=col1,
            command=app.update,
            font=('newspaper', 10))
b1.place(x=70, y=500)

b2 = Button(app,
            text="EXIT",
Ejemplo n.º 27
0
numy = None
x0 = None
y0 = None
beta = None
betas = None
T = None
aU = None
bU = None
cU = None
dU = None
C1s = None
C2s = None
Cs = None

fig = plt.figure(1, figsize=(20, 6))
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()

isok = StringVar()
isok.set('')
lab0 = Label(textvariable=isok, bg="white", fg="red")
lab0.place(relx=0.4, rely=0.05)

lab1 = Label(
    text=
    'Введите параметры a, b функции z(t)=at+bcos(t),\nа также T (через пробел):',
    bg="white",
    fg="black")
lab1.place(relx=0.1, rely=0.1)

ent1 = Entry()
Ejemplo n.º 28
0
g.UserPlot = plt
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)

# ax1(211窗口)
plt.sca(ax1)
#添加标题
ax_K(ax1, df3, stockn)
plt.suptitle(stockn + ' ' + g.stock_names[stockn] + '  KDJ回测结果')

# ax2(212窗口)
plt.sca(ax2)
df3.HL.plot(color='orange', grid=True, label="获利")
df3.B1.plot(color='red', label="$B$")
df3.S3.plot(color='blue', label="$S$")

plt.legend()  # 显示图中右上角的提示信息。
ax2.grid(True)
ax2.axhline(0, color='blue')
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
ax2.xaxis.set_major_locator(mticker.MaxNLocator(8))  #x轴分成几等分
ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=3, prune='upper'))
plt.close()
canvas = FigureCanvasTkAgg(fig, master=g.UserFrame)
#toolbar =NavigationToolbar2TkAgg(canvas, g.UserFrame)
#toolbar.update()

canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
g.UserCanvas = canvas
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
Ejemplo n.º 29
0
 def plot_pie_chart(self, data):
     fig = Figure(figsize=(2,2), dpi=100)
     ax1 = fig.add_subplot()
     ax1.plot(data1)
     canvas = FigureCanvasTkAgg(fig, self)
     canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
Ejemplo n.º 30
0
    def __init__(self, m, n):
        self.w = tk.Tk()
        self.w.title('AR drone Controller')
        self.w.geometry('610x600')

        self.arm_var = tk.BooleanVar()
        c1 = tk.Checkbutton(self.w,
                            text='arming',
                            variable=self.arm_var,
                            width=7,
                            height=2,
                            font=("Arial", 20))

        self.mode_var = tk.StringVar()
        self.mode_var.set('waiting...')

        r1 = self._add_Radiobutton(6, 2, self.mode_var, 'TakeOff')
        r2 = self._add_Radiobutton(6, 2, self.mode_var, 'Land')
        r3 = self._add_Radiobutton(6, 2, self.mode_var, 'KB')
        r4 = self._add_Radiobutton(6, 2, self.mode_var, 'IBVS')
        r0 = self._add_Radiobutton(6, 2, self.mode_var, 'Reset')

        self.key_var = tk.StringVar()
        self.key_var.set('KB waiting...')

        r5 = self._add_Radiobutton(4, 1, self.key_var, 'x+')
        r6 = self._add_Radiobutton(4, 1, self.key_var, 'x-')
        r7 = self._add_Radiobutton(4, 2, self.key_var, 'y+')
        r8 = self._add_Radiobutton(4, 2, self.key_var, 'y-')
        r9 = self._add_Radiobutton(4, 1, self.key_var, 'up')
        r10 = self._add_Radiobutton(4, 1, self.key_var, 'down')
        r11 = self._add_Radiobutton(4, 2, self.key_var, 'stop')

        r12 = self._add_Radiobutton(4, 1, self.key_var, 'left')
        r13 = self._add_Radiobutton(4, 1, self.key_var, 'right')

        b1 = tk.Button(self.w,
                       width=10,
                       height=1,
                       font=("Arial", 20),
                       text='ResetPlot',
                       command=self.clean_plot)
        b2 = tk.Button(self.w,
                       width=10,
                       height=1,
                       font=("Arial", 20),
                       text='Quit',
                       command=quit)

        c1.place(x=0, y=0)

        r1.place(x=0, y=50)
        r2.place(x=100, y=50)
        r3.place(x=200, y=50)
        r4.place(x=300, y=50)
        r0.place(x=400, y=50)

        r5.place(x=100, y=120)
        r6.place(x=100, y=230)
        r7.place(x=0, y=160)
        r8.place(x=200, y=160)
        r9.place(x=320, y=160)
        r10.place(x=320, y=198)
        r11.place(x=100, y=160)

        r12.place(x=0, y=120)
        r13.place(x=200, y=120)

        b1.place(x=200, y=0)
        b2.place(x=400, y=0)

        self.m = m
        self.n = n
        self.x = []
        self.ax = []
        fig = plt.figure()

        for i in range(self.m):
            self.x.append([])
            self.ax.append(fig.add_subplot(111 + m * 100 + i))
            for j in range(self.n):
                self.x[i].append([])
        self.canvas = FigureCanvasTkAgg(fig, master=self.w)
        self.canvas.get_tk_widget().place(x=-20, y=270)