def prior(self): priorheader = headersmall(self.frame, text="Hyperprior Settings:") f = Frame(self.frame) f.config(padx=20, bg=Styles.colours["grey"]) Message(f, text="Horseshoe Prior sn:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=0, column=0, columnspan=2, sticky=W) epriorsnscale = smallentry(f, self.params["priorsnscale"], 15) mpriorsnscale = Message(f, text="scale:", width=32, bg=Styles.colours["grey"]) mpriorsnscale.grid(row=1, column=0, columnspan=1, sticky=E) epriorsnscale.grid(row=1, column=1, columnspan=1, sticky=W) smallentryframetext(f, 1, 2, self.params["priorsnmin"], 15, "min:") Message(f, text="Log Normal Prior sf:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=2, column=0, columnspan=2, sticky=W) f3 = Frame(f) smallentryframetext(f3, 0, 0, self.params["priorsfmu"], 10, "mu:") smallentryframetext(f3, 0, 2, self.params["priorsfsigma"], 10, "sigma:") smallentryframetext(f3, 0, 4, self.params["priorsfmin"], 10, "min:") f3.grid(row=3, column=0, columnspan=4) Message(f, text="Uniform Prior ell:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=4, column=0, columnspan=2, sticky=W) smallentryframetext(f, 5, 0, self.params["priorella"], 15, "a:") smallentryframetext(f, 5, 2, self.params["priorellb"], 15, "b:") Message(f, text="Gaussian Prior mu:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=6, column=0, columnspan=2, sticky=W) smallentryframetext(f, 7, 0, self.params["priormumu"], 15, "mu:") smallentryframetext(f, 7, 2, self.params["priormuvar"], 15, "var:") priorheader.grid(row=6, column=4, sticky=W, columnspan=1) Message(self.frame, text="You can set following parameters based on the variables defined in the GP section.", width=400, font=Styles.fonts["entry"], bg=Styles.colours["grey"]).grid(row=7, column=4, columnspan=2) f.grid(row=8, column=4, sticky=E + W, columnspan=2, rowspan=10)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Color chooser") self.pack(fill=BOTH, expand=1) self.btn = Button(self, text="Choose Color", command=self.onChoose) self.btn.place(x=30, y=30) self.frame = Frame(self, border=1, relief=SUNKEN, width=100, height=100) self.frame.place(x=160, y=30) def onChoose(self): (rgb, hx) = tkColorChooser.askcolor() self.frame.config(bg=hx)
def concolefooter(self): footerframe = Frame(self.master) footerframe.config(padx=5, pady=5, bg=Styles.colours["darkGrey"]) title = Message(footerframe, text="Console:", justify=CENTER, bg=Styles.colours["darkGrey"], foreground=Styles.colours["yellow"], width=100, font=Styles.fonts["entry"]) consoletext = Text(footerframe, height=5, width=80, bg=Styles.colours["darkGrey"], foreground=Styles.colours["grey"], state=NORMAL, relief=FLAT, font=Styles.fonts["console"]) consoletext.insert(END, "Welcome to Project Bi") consoletext.config(state=DISABLED) self.console.setconsolefield(consoletext) scroll = Scrollbar(footerframe, command=consoletext.yview, relief=FLAT) consoletext.configure(yscrollcommand=scroll.set) self.boptimize = yellowbutton(footerframe, "Optimize", 20, lambda e: self.observerstage()) deactivatebutton(self.boptimize) self.boptimize.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) self.boptimize.configure(font=Styles.fonts["h1Button"]) title.pack(side=LEFT, fill=BOTH) scroll.pack(side=LEFT, fill=BOTH) consoletext.pack(side=LEFT, fill=BOTH) footerframe.grid(row=2, column=0, sticky=W + E + N + S, columnspan=2) return footerframe
def show(text, background="#fff", timeout_ms=DEFAULT_TIMEOUT, font_size=100): root = Tk() root.attributes("-topmost", True) root.lift() # Set Timeout root.after(timeout_ms, root.destroy) # Create Frame frame = Frame(root) frame.pack(side=TOP, fill=BOTH, expand=YES) # Set frame size and position screen_width = frame.master.winfo_screenwidth() screen_heigh = frame.master.winfo_screenheight() w = screen_width * 0.8 h = screen_heigh * 0.6 # Center the window x = (screen_width/2) - (w/2) y = (screen_heigh/2) - (h/2) frame.master.geometry('%dx%d+%d+%d' % (w, h, x, y)) # Adjust frame properties frame.master.overrideredirect(True) # Set no border or title frame.config(bg=background) # Create text label label = Label(frame, text=text, wraplength=screen_width * 0.8) label.pack(side=TOP, expand=YES) label.config(bg=background, justify=CENTER, font=("calibri", font_size)) # Set transparency root.wait_visibility(root) # Needed for linux (and must come after overrideredirect) root.attributes('-alpha', 0.6) # Run Event loop root.mainloop()
def outputdir(self): iframe = Frame(self.frame) iframe.config(padx=5, pady=5, bg=Styles.colours["grey"]) iframe.grid(row=10, column=0, sticky=W + E + N + S, columnspan=3, rowspan=2) objheader = headersmall(iframe, text="Model Output Directory (Optional):") boutfile = yellowbutton(iframe, "Select Directory", 14, click=None) eoutfiledir = entry(iframe, self.params["outputdir"], 32, fileCheck=False, dir=True, button=boutfile) objheader.grid(row=0, column=0, sticky=W, columnspan=2) boutfile.grid(row=1, column=2, pady=5) eoutfiledir.grid(row=1, column=0, columnspan=2)
def dimscheduler(self): mischeader = headersmall(self.frame, text="Dimension Scheduler") f = Frame(self.frame) f.config(bg=Styles.colours["grey"]) smallentryframetext(f, 0, 0, self.params["dims"], 7, "Set Size:") checkdimschel = Checkbutton(self.frame, text="Enable", variable=self.params["dimscheudler"], bg=Styles.colours["grey"]) mischeader.grid(row=18, column=0, sticky=W, columnspan=2) checkdimschel.grid(row=19, column=0, sticky=W, columnspan=1, padx=15) f.grid(row=19, column=1, sticky=W + E, columnspan=1)
def initnumber(self): f = Frame(self.frame) f.config(bg=Styles.colours["grey"]) minitnumber = Message(f, text="Numbers of samples to sample:", width=300, bg=Styles.colours["grey"]) einitnumber = smallentry(f, self.params["initializernum"], 10) minitnumber.grid(row=0, column=0, sticky=W, columnspan=1) einitnumber.grid(row=0, column=1, sticky=W, columnspan=1, padx=10) f.grid(row=9, column=0, sticky=W, columnspan=2)
def policyset(self): mischeader = headersmall(self.frame, text="Policy Parameters") fp = Frame(self.frame) fp.config(bg=Styles.colours["grey"]) smallentryframetextv(fp, 0, 0, self.params["eixi"], 10, "EI xi:") smallentryframetextv(fp, 2, 0, self.params["pixi"], 10, "PI xi:") smallentryframetextv(fp, 0, 1, self.params["ucbdelta"], 10, "UCB delta:") smallentryframetextv(fp, 2, 1, self.params["ucbxi"], 10, "UCB xi:") smallentryframetextv(fp, 0, 2, self.params["thompsonn"], 10, "Thompson N:") smallentryframetextv(fp, 2, 2, self.params["thompsonrng"], 10, "Thompson RNG:") mischeader.grid(row=13, column=0, sticky=W, columnspan=2) fp.grid(row=14, column=0, rowspan=4, columnspan=2, sticky=W, padx=10)
def advheader(self): headerframe = Frame(self.toplevel) headerframe.config(bg=Styles.colours["darkGrey"]) advancedsettingsheader = Message(headerframe, text="Advanced Settings", bg=Styles.colours["darkGrey"], justify=CENTER, foreground=Styles.colours["yellow"], pady=5, width=200, font=Styles.fonts["h1"]) qb = qbutton(headerframe) babout = camobutton(headerframe, "About", 10) advancedsettingsheader.pack(side=LEFT, fill=BOTH, padx=5, pady=5) qb.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) babout.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) headerframe.pack(fill=BOTH, pady=0)
def basicgp(self): gpheader = headersmall(self.frame, text="Basic GP Settings:") f = Frame(self.frame) f.config(padx=20, bg=Styles.colours["grey"]) gpsf, _ = smallentryframetext(f, 0, 0, self.params["gpsf"], 20, "sf:") gpmu, _ = smallentryframetext(f, 1, 0, self.params["gpmu"], 20, "mu:") Label(f, text=" ", bg=Styles.colours["grey"]).grid(row=0, column=2, sticky=W, rowspan=2) gpell, _ = smallentryframetext(f, 0, 3, self.params["gpell"], 20, "ell:") gpsn, _ = smallentryframetext(f, 1, 3, self.params["gpsn"], 20, "sn:") gpheader.grid(row=1, column=4, sticky=W, columnspan=1) Message(self.frame, text="You can use numpy and python syntax to set the parameters from the data where" " X is the initial and random data, and y is the corresponding output", width=400, font=Styles.fonts["entry"], bg=Styles.colours["grey"]).grid(row=2, column=4, columnspan=2, sticky=W) f.grid(row=3, column=4, sticky=W, columnspan=2, rowspan=3)
class mainheader(): def __init__(self, master, console,params,maingui): self.frame = Frame(master) self.frame.config(padx=5, pady=5, bg=Styles.colours["darkGrey"]) self.frame.grid(row=0, column=0, sticky=W + E + N + S,columnspan=2) self.title = Message(self.frame, text="ProjectB: Selection", justify=CENTER, bg=Styles.colours["darkGrey"], foreground=Styles.colours["yellow"], width=300, font=Styles.fonts["h1"]) def importsettings(event): f = tkFileDialog.askopenfilename(parent=master, title='Choose a file') parsemodifycustomvar(params,parsein(f,parseintosimple(params),console)) maingui.ready("model") maingui.ready("bayes") def exportfile(event): f = tkFileDialog.asksaveasfilename(parent=master, title='Choose a file') parseout(f,parseintosimple(params),console) self.bimport = camobutton(self.frame, "Import Settings", 15,importsettings) self.bexport = camobutton(self.frame, "Export Settings", 15,exportfile) self.badvset = yellowbutton(self.frame, "Advanced Settings", 20) self.badvset.bind("<Button-1>", lambda a: AdvancedSettings(console,params)) self.qb = qbutton(self.frame) self.title.pack(side=LEFT, fill=BOTH, padx=5, pady=5) self.qb.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) self.badvset.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) self.bexport.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) self.bimport.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) def destroy(self): self.frame.destroy() def observationstage(self): self.bimport.destroy() self.bexport.destroy() self.badvset.destroy() self.title.config(text="ProjectB: Observation") def evaluationstage(self): self.title.config(text="ProjectB: Evaluation")
def __init__(self, notification_manager, builder, index, x, y, h, v, padx, pady, background=None, on_hide=None): Toplevel.__init__(self) self._notification_manager = notification_manager self.index = index self.on_hide = on_hide # Removes the native window boarder. self.overrideredirect(True) # Disables resizing of the widget. self.resizable(False, False) # Places window above all other windows in the window stack. self.wm_attributes("-topmost", True) notification_frame = Frame(self) notification_frame.pack(expand=True, fill=BOTH, padx=padx, pady=pady) top_row = Frame(notification_frame) top_row.pack(fill=X) if not hasattr(notification_manager, "_close_icon"): notification_manager._close_icon = PhotoImage(data="R0lGODlhEAAQAPeQAIsAAI0AAI4AAI8AAJIAAJUAAJQCApkAAJoAAJ4AAJkJCaAAAKYAAKcAAKcCAKcDA6cGAKgAAKsAAKsCAKwAAK0AAK8AAK4CAK8DAqUJAKULAKwLALAAALEAALIAALMAALMDALQAALUAALYAALcEALoAALsAALsCALwAAL8AALkJAL4NAL8NAKoTAKwbAbEQALMVAL0QAL0RAKsREaodHbkQELMsALg2ALk3ALs+ALE2FbgpKbA1Nbc1Nb44N8AAAMIWAMsvAMUgDMcxAKVABb9NBbVJErFYEq1iMrtoMr5kP8BKAMFLAMxKANBBANFCANJFANFEB9JKAMFcANFZANZcANpfAMJUEMZVEc5hAM5pAMluBdRsANR8AM9YOrdERMpIQs1UVMR5WNt8X8VgYMdlZcxtYtx4YNF/btp9eraNf9qXXNCCZsyLeNSLd8SSecySf82kd9qqc9uBgdyBgd+EhN6JgtSIiNuJieGHhOGLg+GKhOKamty1ste4sNO+ueenp+inp+HHrebGrefKuOPTzejWzera1O7b1vLb2/bl4vTu7fbw7ffx7vnz8f///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJAALAAAAAAQABAAAAjUACEJHEiwYEEABniQKfNFgQCDkATQwAMokEU+PQgUFDAjjR09e/LUmUNnh8aBCcCgUeRmzBkzie6EeQBAoAAMXuA8ciRGCaJHfXzUMCAQgYooWN48anTokR8dQk4sELggBhQrU9Q8evSHiJQgLCIIfMDCSZUjhbYuQkLFCRAMAiOQGGLE0CNBcZYmaRIDLqQFGF60eTRoSxc5jwjhACFWIAgMLtgUocJFy5orL0IQRHAiQgsbRZYswbEhBIiCCH6EiJAhAwQMKU5DjHCi9gnZEHMTDAgAOw==") close_button = Button(top_row, image=notification_manager._close_icon, highlightthickness=0, borderwidth=0, command=self.close) close_button.pack(side=RIGHT, anchor=E) self.interior = Frame(notification_frame) self.interior.pack(expand=True, fill=BOTH) if builder: builder(self.interior) if background is not None: top_row.config(background=background) notification_frame.config(background=background) self.config(background=background) self.interior.config(background=background) close_button.config(background=background) self.place(x,y, h, v)
def submitadvancedsettings(self): def destroywindow(event): self.toplevel.destroy() def canceladvc(event): for k, v in self.paramsdefaults.items(): self.params[k].set(v) destroywindow(event) def submitadvc(event): self.paramsdefaults = dict((k, self.params[k].get()) for k in self.advsettingslist) destroywindow(event) f = Frame(self.toplevel) f.config(padx=15, pady=15, bg=Styles.colours["darkGrey"]) submitadv = yellowbutton(f, "Submit", 30, submitadvc) canceladv = yellowbutton(f, "Cancel", 20, canceladvc) submitadv.pack(side=RIGHT) canceladv.pack(side=RIGHT, padx=20) f.pack(fill=X)
def startgraph(self): #Older versions of matplot do not support style command try: pl.style.use('ggplot') except: pass root = Frame(self.frame) self.graphframem = root root.config(padx=20, pady=20, bg=Styles.colours["grey"]) self.graphtype = StringVar(root) self.graphtype.set("Graph: Running Best (Overview)") # initial value self.option = OptionMenu(root, self.graphtype, "Graph: Objective Value", "Graph: Running Best (Zoom)", "Graph: Running Best (Overview)", "Graph: Variance", "Graph: Variance (Last 25)", "Graph: Objective Value (Last 25)", "Graph: Running Best (Last 25)", "Graph: Time (seconds)") self.option.config(padx=5, pady=5,state=DISABLED, justify=LEFT, font=Styles.fonts["h1"], relief=FLAT, highlightbackground=Styles.colours["yellow"], highlightthickness=1, bg=Styles.colours["grey"]) self.option.pack(fill=BOTH) def callback(*args): if not self.lockgraph: self.updategraph() self.graphtype.trace("w", callback) self.graphfigure = Figure(figsize=(6, 6), dpi=70, facecolor=Styles.colours["grey"]) self.graphframe = self.graphfigure.add_subplot(111, axisbg=Styles.colours["darkGrey"]) self.graphframe.set_xlabel('Iteration') self.graphframe.set_ylabel('Objective Value') canvas = FigureCanvasTkAgg(self.graphfigure, master=root) canvas.show() canvas.get_tk_widget().configure(background=Styles.colours["grey"], highlightcolor=Styles.colours["grey"], highlightbackground=Styles.colours["grey"]) canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) root.grid(row=0, column=0) canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=0)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0) self.hex_color = '#0000ff' self.color_list = ["red","blue","green","orange","purple"] self.parent = parent print "Loading model..." self.lux = Lux() fp = open(curdir+"/gauss_model.pkl"); self.gm = pickle.load(fp); fp.close() fp = open(curdir+"/memoized_binomial_data.pkl"); self.curve_data = pickle.load(fp); fp.close() fp = open(curdir+"/sampling_normalizer.pkl"); self.normalizer = pickle.load(fp); fp.close() print "Creating UI" self.initUI() self.update_output() self.replot() def update_output(self): (h, s, v) = self.hsv_color self.hsv_var.set("Hue: \t %2.1f \nSat:\t %2.1f \nValue:\t %2.1f" % (h*360,s*100,v*100)) items = self.lux.full_posterior((h * 360, s * 100, v * 100)) self.current_post = items desc = [ '{:<25} ({:.3f})\n'.format(items[i][0], items[i][1]) for i in range(25) ] self.display.config(state=NORMAL) self.display.delete(0, END) for i in range(25): self.display.insert(END, '{:<20} ({:.3f})'.format(items[i][0], items[i][1])) self.display.select_set(0, 0) def plot_lux_model(self, params,ax1,label,support,dim): cur_color='black' mu1,sh1,sc1,mu2,sh2,sc2 = params left_stach=gam_dist(sh1,scale=sc1); lbounds=left_stach.interval(0.99) right_stach=gam_dist(sh2,scale=sc2); rbounds=right_stach.interval(0.99) lx=np.linspace(mu1,-180); rx=np.linspace(mu2,360) s=3; ax1.plot(rx, [right_stach.sf(abs(y-mu2)) for y in rx],linewidth=s,c=cur_color); ax1.plot([1.01*mu1,0.99*mu2], [1.,1.], linewidth=s,c=cur_color) return ax1.plot(lx,[left_stach.sf(abs(y-mu1)) for y in lx],c=cur_color, linewidth=s); def plot_gm_model(self, params, ax, label, support): s=3 x = np.linspace(support[0],support[1],360) return ax.plot(x,norm.pdf(x,params[0],params[1]),c='red', linewidth=s), norm.pdf([params[0]],params[0],[params[1]])[0] def initUI(self): self.parent.title("Interactive LUX visualization") self.pack(fill=BOTH, expand=1) self.color_frame = Frame(self, border=1) self.color_frame.pack(side=LEFT) probe_title_var = StringVar(); probe_title_label = Label(self.color_frame, textvariable=probe_title_var, justify=CENTER, font = "Helvetica 16 bold italic") probe_title_var.set("Color Probe X"); probe_title_label.pack(side=TOP) self.hsv_var = StringVar() self.hsv_label = Label(self.color_frame, textvariable=self.hsv_var,justify=LEFT) h,s,v = self.hsv_color self.hsv_var.set("Hue: %2.1f \nSaturation: %2.1f \nValue: %2.1f" % (h*360,s*100,v*100)) self.hsv_label.pack(side=TOP) self.frame = Frame(self.color_frame, border=1, relief=SUNKEN, width=200, height=200) self.frame.pack(side=TOP) self.frame.config(bg=self.hex_color) self.frame.bind("<Button-1>",self.onChoose) self.btn = Button(self.color_frame, text="Select Color", command=self.onChoose) self.btn.pack(side=TOP) posterior_title_var = StringVar(); posterior_title_label = Label(self.color_frame, textvariable=posterior_title_var, justify=CENTER, font = "Helvetica 16 bold italic") posterior_title_var.set("\n\nLUX's Posterior"); posterior_title_label.pack(side=TOP) Label(self.color_frame, text="Double click to show details \n(Wait time dependent on computer)").pack(side=TOP) my_font = tkFont.Font(family="Courier", size=10) self.display = Listbox(self.color_frame, border=1, relief=SUNKEN, width=30, height=25, font=my_font) self.display.pack(side=TOP,fill=Y,expand=1) self.display.bind("<Double-Button-1>",self.onSelect) self.display_btn = Button(self.color_frame, text="Show details", command=self.onSelect) self.display_btn.pack(side=TOP) self.update_output() self.fig = Figure(figsize=(10,4), dpi=100) self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1) self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) def replot(self): def gb(x,i,t): #t is max value, i in number of bins, x is the thing to be binned if x==t: return i-1 elif x==0.0: return 0 return int(floor(float(x)*i/t)) hsv_title = [] j=self.display.curselection()[0] name = self.current_post[j][0] mult = lambda x: reduce(operator.mul, x) g_labels = []; lux_labels=[]; all_g_params=[] for i in range(3): def align_yaxis(ax1, v1, ax2, v2): """adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1""" _, y1 = ax1.transData.transform((0, v1)) _, y2 = ax2.transData.transform((0, v2)) inv = ax2.transData.inverted() _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2)) miny, maxy = ax2.get_ylim() ax2.set_ylim(miny, maxy+dy) subplot = self.fig.add_subplot(4,1,i+1) dim_label = ["H", "S","V"][i] subplot.set_ylabel(r"$P(k^{true}_{%s}|x)$" % ["H", "S","V"][i] ) curve_data = self.curve_data[name][i] scale = lambda x,a=0.3,b=0.9: (b-a)*(x)+a p_x = lambda x: self.normalizer[i][gb(x,len(self.normalizer[i]),[360,100,100][i])] max_p_x = max(self.normalizer[i]) #1 is white, 0 is black. so we want highly probable thigns to be black.. if self.lux.get_adj(self.current_post[j][0]): support = [[-180,180], [0,100],[0,100]][i] pp = lambda x,i: x-360 if i==0 and x>180 else x hacky_solution = [360,100,100][i] w = 1.5 if i==0 else 1 conv = lambda x: x*support[1]/len(curve_data) bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))] bar1 = subplot.bar([pp(atan2(sin((x*hacky_solution/len(curve_data))*pi/180),cos((x*hacky_solution/len(curve_data))*pi/180))*180/pi,i) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % j,ec="black",width=w,linewidth=0,color=bar_colors) else: support = [[0,360], [0,100],[0,100]][i] w = 1.5 if i==0 else 1 conv = lambda x: x*support[1]/len(curve_data) bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))] bar1 = subplot.bar([x*support[1]/len(curve_data) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % name[0],ec="black",width=w,linewidth=0,color=bar_colors) pp = lambda x,*args: x point = pp(self.hsv_color[i]*[360,100,100][i],i) hsv_title.append(point) probeplot = subplot.plot([point,point], [0,1],linewidth=3,c='blue',label="Probe") #for j in range(5): lux_plot = self.plot_lux_model(self.lux.get_params(self.current_post[j][0])[i], subplot, self.current_post[j][0],support, i) subplot2 = subplot.twinx() gm_plot,gm_height = self.plot_gm_model([pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]], subplot2, self.current_post[j][0], support) extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0) subplot.legend([extra], [["Hue", "Saturation", "Value"][i]],loc=2,frameon=False) if i==0: legend_set=lux_plot+[extra,extra,extra]+gm_plot+[extra,extra,extra] lux_params = self.lux.get_params(self.current_post[j][0])[i] g_params = [pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]] all_g_params.append(g_params) g_labels.append(r"$\mu^{%s}=$%2.2f, $\sigma^{%s}$=%2.2f" % (dim_label, g_params[0],dim_label,g_params[1])) #lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, (lux_params[0]-lux_params[1]*lux_params[2]),dim_label,lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,(lux_params[3]+lux_params[4]*lux_params[5]),dim_label, lux_params[4],dim_label,lux_params[5])) lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f, $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,lux_params[4],dim_label,lux_params[5])) subplot.set_xlim(support[0],support[1]) subplot.set_ylim(0,1.05) subplot2.set_xlim(support[0],support[1]) subplot2.set_ylabel(r"$P(x|Gaussian_{%s})$" % ["H", "S","V"][i]) align_yaxis(subplot, 1., subplot2, gm_height) leg_loc =(0.9,0.2) datum = [x*[360,100,100][i] for i,x in enumerate(self.hsv_color)]; phi_value = self.lux.get_phi(datum,self.current_post[j][0]) #gauss_value = mult([norm.pdf(datum[i],all_g_params[i][0],all_g_params[i][1]) for i in range(3)]) leg=self.fig.legend(probeplot+legend_set, ["Probe X"]+ [r"$\mathbf{\phi}_{%s}(X)=\mathbf{%2.5f}$; $\mathbf{\alpha}=\mathbf{%2.4f}$" % (self.current_post[j][0],phi_value,self.lux.get_avail(self.current_post[j][0]))]+lux_labels+ [r"$Normal^{Hue}_{%s}$; $prior(%s)=%2.4f$" % (self.current_post[j][0],self.current_post[j][0], self.gm[self.current_post[j][0]][2])]+[g_labels[0]+"; "+g_labels[1]+"; "+g_labels[2]] , loc=8, handletextpad=4,labelspacing=0.1) self.fig.suptitle("%s" % name, size=30) print "done replotting" def onChoose(self, *args): try: ((red,green,blue), hx) = tkColorChooser.askcolor() except: print "I think you hit cancel" return self.hex_color = hx self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0) self.frame.config(bg=hx) self.update_output() self.fig.clear() self.replot() self.canvas.draw() def onSelect(self, *args): self.fig.clear() self.replot() self.canvas.draw()
class Notification(Toplevel): def __init__(self, notification_manager, builder, index, x, y, h, v, padx, pady, background=None, on_hide=None): Toplevel.__init__(self) self._notification_manager = notification_manager self.index = index self.on_hide = on_hide # Removes the native window boarder. self.overrideredirect(True) # Disables resizing of the widget. self.resizable(False, False) # Places window above all other windows in the window stack. self.wm_attributes("-topmost", True) notification_frame = Frame(self) notification_frame.pack(expand=True, fill=BOTH, padx=padx, pady=pady) top_row = Frame(notification_frame) top_row.pack(fill=X) if not hasattr(notification_manager, "_close_icon"): notification_manager._close_icon = PhotoImage(data="R0lGODlhEAAQAPeQAIsAAI0AAI4AAI8AAJIAAJUAAJQCApkAAJoAAJ4AAJkJCaAAAKYAAKcAAKcCAKcDA6cGAKgAAKsAAKsCAKwAAK0AAK8AAK4CAK8DAqUJAKULAKwLALAAALEAALIAALMAALMDALQAALUAALYAALcEALoAALsAALsCALwAAL8AALkJAL4NAL8NAKoTAKwbAbEQALMVAL0QAL0RAKsREaodHbkQELMsALg2ALk3ALs+ALE2FbgpKbA1Nbc1Nb44N8AAAMIWAMsvAMUgDMcxAKVABb9NBbVJErFYEq1iMrtoMr5kP8BKAMFLAMxKANBBANFCANJFANFEB9JKAMFcANFZANZcANpfAMJUEMZVEc5hAM5pAMluBdRsANR8AM9YOrdERMpIQs1UVMR5WNt8X8VgYMdlZcxtYtx4YNF/btp9eraNf9qXXNCCZsyLeNSLd8SSecySf82kd9qqc9uBgdyBgd+EhN6JgtSIiNuJieGHhOGLg+GKhOKamty1ste4sNO+ueenp+inp+HHrebGrefKuOPTzejWzera1O7b1vLb2/bl4vTu7fbw7ffx7vnz8f///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJAALAAAAAAQABAAAAjUACEJHEiwYEEABniQKfNFgQCDkATQwAMokEU+PQgUFDAjjR09e/LUmUNnh8aBCcCgUeRmzBkzie6EeQBAoAAMXuA8ciRGCaJHfXzUMCAQgYooWN48anTokR8dQk4sELggBhQrU9Q8evSHiJQgLCIIfMDCSZUjhbYuQkLFCRAMAiOQGGLE0CNBcZYmaRIDLqQFGF60eTRoSxc5jwjhACFWIAgMLtgUocJFy5orL0IQRHAiQgsbRZYswbEhBIiCCH6EiJAhAwQMKU5DjHCi9gnZEHMTDAgAOw==") close_button = Button(top_row, image=notification_manager._close_icon, highlightthickness=0, borderwidth=0, command=self.close) close_button.pack(side=RIGHT, anchor=E) self.interior = Frame(notification_frame) self.interior.pack(expand=True, fill=BOTH) if builder: builder(self.interior) if background is not None: top_row.config(background=background) notification_frame.config(background=background) self.config(background=background) self.interior.config(background=background) close_button.config(background=background) self.place(x,y, h, v) @property def x(self): return self._offset_x @property def y(self): return self._offset_y @property def h(self): return self._h @property def v(self): return self._v def place(self, x, y, h, v): ''' The windows overall position on the screen ''' self.wm_geometry("{h}{x}{v}{y}".format(x=x,y=y, h=h, v=v)) self._offset_x = x self._offset_y = y self._h = h self._v = v def start_animation(self, easing_function, ticks, duration, start_time=0): self._tick = 0 self._total_ticks = float(ticks) self._easing_function = easing_function self._duration = duration self._interval_time = int(duration * 1000 / self._total_ticks) if start_time != 0: self.after(int(start_time*1000), self._animate) else: self._animate() def _animate(self): t = self._tick / self._total_ticks # This changes the alpha value (How transparent the window should be). # It ranges from 0.0 (completely transparent) to 1.0 (completely opaque). self.attributes("-alpha", self._easing_function(1-t)) self._tick += 1 if self._tick <= self._total_ticks: self.after(self._interval_time, self._animate) else: self.after(self._interval_time, self.close) def close(self): self._notification_manager.delete(self)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0) self.hex_color = '#0000ff' self.color_list = ["red","blue","green","orange","purple"] self.parent = parent print "Getting Model" self.lux = lux.LUX("lux.xml") print "Creating UI" self.initUI() self.update_output() def update_output(self): (h, s, v) = self.hsv_color items = self.lux.full_posterior((h * 360, s * 100, v * 100)) self.current_post = items desc = [ '{} ({:.3f})\n'.format(items[i][0], items[i][1]) for i in range(25) ] self.display.config(state=NORMAL) self.display.delete(1.0, END) self.display.insert(END, ''.join(desc)) self.display.config(state=DISABLED) def make_plotter(self, params,ax1,label,cur_color,support): mu1,sh1,sc1,mu2,sh2,sc2 = params left_stach=gam_dist(sh1,scale=sc1); lbounds=left_stach.interval(0.99) right_stach=gam_dist(sh2,scale=sc2); rbounds=right_stach.interval(0.99) lx=np.linspace(mu1,-180); rx=np.linspace(mu2,360) s=3; #cur_color='black' ax1.plot(rx, [1-right_stach.cdf(abs(y-mu2)) for y in rx],linewidth=s,c=cur_color); ax1.plot([1.01*mu1,0.99*mu2], [1,1], linewidth=s,c=cur_color) return ax1.plot(lx,[1-left_stach.cdf(abs(y-mu1)) for y in lx],c=cur_color, label=r"$\phi^{Hue}_{%s}$" % label,linewidth=s); def initUI(self): self.parent.title("Interactive LUX visualization") self.pack(fill=BOTH, expand=1) self.color_frame = Frame(self, border=1) self.color_frame.pack(side=LEFT) self.frame = Frame(self.color_frame, border=1, relief=SUNKEN, width=100, height=100) #self.frame.place(x=160, y=30) self.frame.pack(side=TOP) self.frame.config(bg=self.hex_color) self.btn = Button(self.color_frame, text="Select Color", command=self.onChoose) self.btn.pack(side=TOP) #self.btn.place(x=30, y=30) self.display = Text(self, border=1, relief=SUNKEN, width=30, height=5) #self.display.place(x=280, y=30) self.display.pack(side=LEFT,fill=Y,expand=1) self.update_output() self.fig = Figure(figsize=(10,4), dpi=100) self.replot() self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1) self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) def replot(self): hsv_title = [] for i in range(3): if self.lux.get_adj(self.current_post[0][0]): support = [[-180,180], [0,100],[0,100]][i] pp = lambda x,i: x-360 if i==0 and x>180 else x else: support = [[0,360], [0,100],[0,100]][i] pp = lambda x,*args: x subplot = self.fig.add_subplot(3,1,i+1) subplot.set_xlim(support[0],support[1]) subplot.set_ylabel("%s" % ["Hue", "Saturation","Value"][i]) point = pp(self.hsv_color[i]*[360,100,100][i],i) hsv_title.append(point) probeplot = subplot.plot([point,point], [0,1],linewidth=3,c='black',label="Probe") legend_set = [] for j in range(5): test = self.make_plotter(self.lux.get_params(self.current_post[j][0])[i], subplot, self.current_post[j][0],self.color_list[j],support) if type(test)==type([]): legend_set+=test else: legend_set.append(test) self.fig.legend(legend_set, [r"$\phi_{%s}$; $\alpha=%2.4f$" % (x[0],self.lux.get_avail(x[0])) for x in self.current_post[:5]], loc=1) self.fig.suptitle("HSV (%2.2f,%2.2f,%2.2f) top 5 Phi curves" % (hsv_title[0],hsv_title[1],hsv_title[2])) def onChoose(self): ((red,green,blue), hx) = tkColorChooser.askcolor() self.hex_color = hx self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0) self.frame.config(bg=hx) self.update_output() self.fig.clear() self.replot() self.canvas.draw()
class ModelFrame(): def __init__(self, master, console, params, row, col, maingui): self.frame = Frame(master) self.maingui = maingui self.frame.config(padx=20, pady=20, bg=Styles.colours["grey"]) self.frame.grid(row=row, column=col, sticky=NW) self.console = console self.params = params self.modelparamslist = ["command", "modelinput", "modeloutput", "bounds"] self.paramsdefaults = dict( (k, self.params[k].get if type(self.params[k]) is not list else []) for k in self.modelparamslist) self.headermodel() self.modelcmd() self.modelio() self.bounds() def destroy(self): self.frame.destroy() def headermodel(self): headermodel = header(self.frame, "Model Parameters") headermodel.grid(row=0, column=0, sticky=W, columnspan=2) def modelcmd(self): cmdheader = headersmall(self.frame, "Commandline command for the model:") ecmd = entry(self.frame, self.params["command"], 65, file=False, fileCheck=False, button=None) cmdheader.grid(row=1, column=0, sticky=W, columnspan=2) ecmd.grid(row=2, column=0, columnspan=3, pady=5, rowspan=2) self.isreadyE(ecmd) # Seperator Label(self.frame, text="", bg=Styles.colours["grey"]).grid(row=4, column=0, sticky=W, columnspan=2) def modelio(self): ioheader = header(self.frame, "Select your model I/O:") biuri = yellowbutton(self.frame, "Select Input File", 20, click=None) bouri = yellowbutton(self.frame, "Select Output File", 20, click=None) eiuri = entry(self.frame, self.params["modelinput"], 40, file=True, fileCheck=True, button=biuri) eouri = entry(self.frame, self.params["modeloutput"], 40, file=True, fileCheck=True, button=bouri) self.isreadyB(biuri) self.isreadyB(bouri) self.isreadyE(eiuri) self.isreadyE(eouri) ioheader.grid(row=5, column=0, sticky=W, columnspan=2) biuri.grid(row=6, column=2, pady=5) bouri.grid(row=7, column=2, pady=5) eiuri.grid(row=6, column=0, columnspan=2) eouri.grid(row=7, column=0, columnspan=2) # Seperator Label(self.frame, text="", bg=Styles.colours["grey"]).grid(row=8, column=0, sticky=W, columnspan=2) def bounds(self): def boundsfilepicker(event): f = tkFileDialog.askopenfilename(parent=self.frame, title='Choose bounds a file') if os.path.isfile(f): try: bounds = genfromtxt(f, delimiter=",") if ((bounds.shape[1] == 2 and (bounds[:, 0] < bounds[:, 1]).all())): self.params["bounds"] = bounds self.console.log("Bounds set to a file: " + str(f)) self.console.log("You can now view the bounds") bboundsf.bind("<Enter>", lambda event: "break") bboundsf.bind("<FocusIn>", lambda event: "break") bboundsf.bind("<Leave>", lambda event: "break") bboundsf.bind("<FocusOut>", lambda event: "break") else: texterror = "Bounds file has wrong dimensions, please check the file" self.console.log(texterror) popupwindow("Bounds File error", 2, texterror) except: texterror = "Bounds file has wrong format, please check the file" self.console.log(texterror) popupwindow("Bounds File error", 2, texterror) else: texterror = "Bounds file has not been selected, please select the file" self.console.log(texterror) popupwindow("Bounds File error", 2, texterror) def helpbounds(evemt): helpboundsw = Toplevel() helpboundsw.title("Help: Bounds") helpboundsw.config(bg=Styles.colours["grey"], padx=10, pady=10) boundswindowheader = header(helpboundsw, "How to set bounds?") t = Text(helpboundsw, width=30, height=20, relief=FLAT, bg=Styles.colours["grey"], wrap=WORD, font=Styles.fonts["entryFilled"]) t.insert(END, " The bounds give the model maximum and minimum for each input parameter value. You can set the bounds from a file in CSV file" "where first column is the minimum and second column is the maximum, or through the window presented prior.") boundswindowheader.grid(row=0, column=0) t.grid(row=1, column=0) def manualbounds(event): def checkbounds(event): try: b = minmaxT.get(1.0, END) bounds = array([fromstring(x, dtype=float, sep="-") for x in b.replace(" ", "").split()]) if (bounds.shape[1] == 2 and (bounds[:, 0] < bounds[:, 1]).all()): minmaxT.config(bg=Styles.colours["lightGreen"]) return True else: minmaxT.config(bg=Styles.colours["lightRed"]) return False except: minmaxT.config(bg=Styles.colours["lightRed"]) return False return False def submite(event): submit() def submit(): if checkbounds(""): b = minmaxT.get(1.0, END) bounds = array([fromstring(x, dtype=float, sep="-") for x in b.replace(" ", "").split()]) self.params["bounds"][:] = [] for bound in bounds: self.params["bounds"].append(bound.tolist()) boundswindow.destroy() if self.checkall(): self.maingui("model") self.console.log( "Bounds have been successfully set to following dimensions " + str(len(self.params["bounds"]))) else: popupwindow("You have not set correct bounds", 5, "The bounds you have set do not correspond to the format specified, please review the bounds you have entered.")( "") if self.checkall(): self.maingui("model") else: self.console.notready("model") def cancel(event): self.params["bounds"] = orginalbounds boundswindow.destroy() boundswindow = Toplevel() boundswindow.title("Bounds") boundswindow.config(pady=5, padx=5) boundswindow.protocol("WM_DELETE_WINDOW", submit) orginalbounds = None boundswindowheader = header(boundswindow, "Set model bounds:") qB = qbutton(boundswindow, l=popupwindow("How to set bounds?", 8, " The bounds give the model maximum and minimum for each input parameter value. You can set the bounds from a file in CSV file" "where first column is the minimum and second column is the maximum, or through the window presented prior.")) minmax = headersmall(boundswindow, "Minimum,Maximum") tut = Message(boundswindow, width=250, text="For each dimension set the minimum and maximum, seperated by a minus sign. Each dimension split by a newline (enter)") f = Frame(boundswindow) minmaxT = Text(f, width=20, height=10, relief=FLAT, padx=15, pady=15, font=Styles.fonts["bounds"]) minmaxT.bind("<KeyRelease>", checkbounds) if (self.params["bounds"] is not []): orginalbounds = list(self.params["bounds"]) for b in self.params["bounds"]: minmaxT.insert(END, str(b[0]) + " - " + str(b[1]) + "\n") checkbounds("") scroll = Scrollbar(f, command=minmaxT.yview, relief=FLAT) minmaxT.configure(yscrollcommand=scroll.set) minmaxT.grid(row=0, padx=3, column=0) scroll.grid(row=0, column=1) submitboundsbutton = yellowbutton(boundswindow, "Submit", 20, submite) self.isreadyB(submitboundsbutton, 1000) cancelboundsbutton = yellowbutton(boundswindow, "Cancel", 20, cancel) boundswindowheader.grid(row=0, column=0, sticky=W, columnspan=1) qB.grid(row=0, padx=3, column=1, sticky=E) tut.grid(row=1, column=0, columnspan=2) minmax.grid(row=2, padx=3, column=0) f.grid(row=3, column=0, columnspan=2) Label(boundswindow, text="").grid(row=4, column=0, sticky=W, columnspan=2) submitboundsbutton.grid(row=5, padx=3, column=0, columnspan=1) cancelboundsbutton.grid(row=5, padx=3, column=1, columnspan=1) boundsheader = header(self.frame, "Set model bounds:") bboundsm = yellowbutton(self.frame, "Set or View Bounds", 40, click=manualbounds) bboundsf = yellowbutton(self.frame, "From File", 20, click=boundsfilepicker) self.isreadyB(bboundsf) # Bounds boundsheader.grid(row=9, column=0, sticky=W, columnspan=2) bboundsm.grid(row=10, column=0, pady=5, padx=3, columnspan=2) bboundsf.grid(row=10, column=2, pady=5, padx=3) def isreadyB(self, b, t=3000): def timedcheck(): if self.checkall(): self.maingui.ready("model") else: self.console.notready("model") def check(event): b.after(t, timedcheck) b.bind("<ButtonRelease-1>", check) def isreadyE(self, e): def check(event): if self.checkall(): self.maingui.ready("model") else: self.maingui.notready("model") e.bind("<Tab>", check) def checkall(self): for k, v in self.paramsdefaults.items(): if k is "bounds": if self.params[k] is []: return False else: continue if self.params[k].get() == v: return False return True
class UIBidding(Notify): class CoincheException(Exception): def __init__(self, pid): self.pid = pid def __init__(self, root, x, y, size_x, size_y): Notify.__init__(self) # Memorise the frame self._root = root self._frame = Frame(width = size_x, height = size_y) # No resize self._frame.pack_propagate(0) # Style self._frame.config(borderwidth = 5) self._x = x self._y = y # Init the buttons self._init_buttons() # Will be used to notify the main thread when waiting for a call self.need_bid_event = Event() # Will be used to notify the main thread when waiting for a coinche self.coinche_event = Event() self.pid = 0 self._last_bid = None self.enable() def display(self): """ Display the widget on the table """ self._frame.place(in_ = self._root, x = self._x, y = self._y) def hide(self): """ Hide the pannel when the biddings are closed for example """ self._frame.place_forget() def _init_color_buttons(self): """ Init the buttons to select the color """ # Dedicated frame for buttons self._buttons_frame = Frame() # This dictionnary will contains all the color buttons self._buttons = dict() # Several colors are available colors = list(Bidding.colors) colors.pop() # The buttons need to have a fixed size h = 2 w = 2 for c in colors: self._buttons[c] = Button(self._buttons_frame, text=c, \ height=h, width=w, \ command=lambda c=c: self._click_color(c)) self._buttons[c].pack(side = LEFT) # Pack the dedicated frame into the main frame self._buttons_frame.pack(in_ = self._frame) self._selected_color = None def _init_value_box(self): """ Init the list box which select the value of the bid """ availableValue = Bidding.values # TODO: display "pass" instead of "0" #availableValue[0] = "pass" self._value_box = Combobox(self._frame, \ values = availableValue, \ # TODO # Only justify the selected value #justify = RIGHT, \ state = 'readonly') self._value_box.bind("<<ComboboxSelected>>", lambda x: self._update_bid_button()) self._value_box.set(availableValue[0]) self._value_box.pack(fill = X) @staticmethod def raise_(e): raise e def _init_bid_button(self): # To bid self._bid_button = Button(self._frame, text = "Pass", \ command = self._click_bidding) self._bid_button.pack(fill = X) # To coinche self._coinche_button = Button(self._frame, text = "Coinche", \ command = lambda: self._event[EVT_UI_COINCHE]()) self._coinche_button.pack(fill = X) def _init_buttons(self): """ Init the buttons """ # Put the value box on top of the buttons self._init_value_box() self._init_color_buttons() self._init_bid_button() def _click_color(self, color): self._selected_color = color self._update_bid_button() def _click_bidding(self): """ Callback function on bidding click """ if self._bid_button.config('text')[-1] == "Pass": self._last_bid = Bidding(self.pid) else: if self._selected_color is None: self._event[CONSOLE_RED]("Choose a color!") return c = self._selected_color v = int(self._value_box.get()) self._last_bid = Bidding(self.pid, v, c) # Notify the consumer (main thread) self.need_bid_event.set() # Reset the event self.need_bid_event.clear() def _click_coinche(self): # Notify the consumer self.coinche_event.set() # Reset the event self.coinche_event.clear() def _update_bid_button(self): value = self._value_box.get() color = self._selected_color if value == "0" and color is None: self._bid_button.config(text = "Pass") elif value == "0": self._bid_button.config(text = "Bid " + color) elif color is None: self._bid_button.config(text = "Bid " + value) else: self._bid_button.config(text = "Bid " + value + " " + color) @property def last_bid(self): return self._last_bid @last_bid.setter def last_bid(self, value): if value is None: self._bid_button.config(text = "Pass") self._last_bid = None else: raise Exception("Should not be called") def disable(self): """ Disable the bid button """ self._bid_button.config(state = DISABLED) def enable(self): """ Enable the bid button """ self._bid_button.config(state = NORMAL)
class view(Tk): def mkStringVar(self, s): R = StringVar() R.set(s) return R def mkLabel(self, f, T, r, c, rs=1, cs=1): if isinstance(T, type(StringVar())): R = Label(f, textvariable=T, relief=GROOVE, borderwidth=2) else: R = Label(f, text=T, relief=GROOVE, borderwidth=2) R.grid(row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens") return R def mkLabelList(self, f, SV, r): R = [] for i in range(len(SV)): R.append(self.mkLabel(f, SV[i], r, i + 1)) return R def mkButton(self, f, t, r, c, rs=1, cs=1): R = Button(f, text=t) R.grid(row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens") return R # ===== HALT et cetera ========================================================= def mkHaltArea(self, f): self.HALTframe = Frame(f) self.HALTframe.config(relief=GROOVE) self.HALTframe.config(borderwidth=2) self.HALTbutton = Button(self.HALTframe, text="HALT", width=10) self.READMEbutton = Button(self.HALTframe, text="README", width=10) self.HALTbutton.config(borderwidth=2, relief=GROOVE, fg="red") self.HALTbutton.config(command=self.quit) self.READMEbutton.config(borderwidth=2, relief=GROOVE, fg="red") self.HALTbutton.pack(side=LEFT, fill=BOTH) self.READMEbutton.pack(side=RIGHT, fill=BOTH) self.HALTframe.grid(row=0, column=9, rowspan=1, columnspan=4, sticky="wens") # ============================================================================== def mkProgramControl(self, f): self.PROGRAMCONTROLframe = Frame(f) self.PROGRAMCONTROLframe.config(relief=GROOVE) self.PROGRAMCONTROLframe.config(borderwidth=2) self.runButton = Button(self.PROGRAMCONTROLframe, text="RUN", width=10) self.runButton.grid(row=0, column=0, sticky="wens", padx=29, pady=7) self.stepButton = Button(self.PROGRAMCONTROLframe, text="STEP", width=10) self.stepButton.grid(row=1, column=0, sticky="wens", padx=29, pady=5) self.noStepButton = Button(self.PROGRAMCONTROLframe, text="NOSTEP", width=10) self.noStepButton.grid(row=2, column=0, sticky="wens", padx=29, pady=7) self.PROGRAMCONTROLframe.grid(row=17, column=11, rowspan=6, columnspan=2, sticky="wens") # ============================================================================== def getPGMfileName(self): options = {'filetypes': [('pgm files', '.pgm')]} f = askopenfilename(**options) g = f.split('/') self.filenameVar.set(g[len(g) - 1]) return f def mkProgramLoad(self, f): self.PROGRAMLOADframe = Frame(f) self.PROGRAMLOADframe.config(relief=GROOVE) self.PROGRAMLOADframe.config(borderwidth=2) self.loadPGMbutton = Button(self.PROGRAMLOADframe, text="Load PGM") self.loadPGMbutton.config(width=14) self.loadPGMbutton.pack(side=LEFT, fill=BOTH, padx=20, pady=5) self.filenameVar = StringVar() self.filenameVar.set("*****.pgm") self.fileNameLabel = Label(self.PROGRAMLOADframe, textvariable=self.filenameVar) self.fileNameLabel.config(relief=GROOVE, borderwidth=2, width=17) self.fileNameLabel.pack(side=RIGHT, fill=BOTH, padx=20, pady=5) self.PROGRAMLOADframe.grid(row=15, column=9, rowspan=2, columnspan=4, sticky="wens") # ============================================================================== def mkMemory(self, f): self.MEMORYframe = Frame(f) self.MEMORYframe.config(relief=GROOVE) self.MEMORYframe.config(borderwidth=2) E = Frame(self.MEMORYframe) self.CLEAR = self.mkButton(E, "ClearMem", 0, 0) self.RANDOM = self.mkButton(E, "RandomMem", 0, 1) self.READ = self.mkButton(E, "ReadMem", 1, 0) self.WRITE = self.mkButton(E, "WriteMem", 1, 1) self.BUSTOMEM = self.mkButton(E, "BusToMem", 2, 0, 1, 2) F = Frame(self.MEMORYframe) for i in Range8: L = Label(F, textvariable=self.MEMORY[i]) L.config(relief=GROOVE, borderwidth=2, bg="black", fg="yellow", height=1) L.grid(row=0, column=i, sticky="wens", ipadx=5) E.pack(side=TOP) F.pack(side=BOTTOM) self.MEMORYframe.grid(row=18, column=9, rowspan=5, columnspan=2, sticky="wens") # ============================================================================== def mkDataBus(self, f): self.DBframe = Frame(f) self.DBframe.config(relief=GROOVE) self.DBframe.config(borderwidth=2, bg="red") self.DBframe.grid(row=0, column=0, rowspan=1, \ columnspan=9, sticky="wens") self.databusLabel = Label(self.DBframe, text="Data\nBus", width=10) self.databusLabel.pack(side=LEFT) self.DATABUSbuttons = [] for i in Range8: b = Button(self.DBframe, textvariable=self.DATABUS[i]) b.pack(side=LEFT, fill=BOTH) self.DATABUSbuttons.append(b) def mkAddressBus(self, f): self.ABframe = Frame(f) self.ABframe.config(relief=GROOVE) self.ABframe.config(borderwidth=2, bg="red") self.ABframe.grid(row=26, column=0, rowspan=1, columnspan=13, sticky="wens") self.AddressBusLabel = Label(self.ABframe, text="Address\nBus", width=12) self.AddressBusLabel.pack(side=LEFT) self.ADDRESSBUSbuttons = [] for i in Range16: b = Button(self.ABframe, textvariable=self.ADDRESSBUS[i]) b.pack(side=LEFT, fill=BOTH, ipadx=2) self.ADDRESSBUSbuttons.append(b) # ============================================================================== def mkALU(self, f): self.ALUframe = Frame(f) self.ALUframe.config(relief=GROOVE) self.ALUframe.config(borderwidth=2) self.mkFunctionChoice(self.ALUframe) self.mkStates(self.ALUframe) self.ALUframe.grid(row=23, column=9, rowspan=3, columnspan=4, sticky="wens") def mkFunctionChoice(self, f): self.FUNCTIONframe = Frame(f) self.FUNCTIONframe.config(relief=GROOVE) self.FUNCTIONframe.config(borderwidth=2) self.F0label = Label(self.FUNCTIONframe, text="F0", borderwidth=2, relief=GROOVE) self.F0label.grid(row=0, column=0, sticky="wens", padx=5) self.F1label = Label(self.FUNCTIONframe, text="F1", borderwidth=2, relief=GROOVE) self.F1label.grid(row=0, column=1, sticky="wens", padx=8) self.F2label = Label(self.FUNCTIONframe, text="F2", borderwidth=2, relief=GROOVE) self.F2label.grid(row=0, column=2, sticky="wens", padx=5) self.FUNCTIONbuttons = [] self.F0button = Button(self.FUNCTIONframe) self.F0button.config(textvariable=self.FUNCTION[0], borderwidth=2, relief=GROOVE) self.F1button = Button(self.FUNCTIONframe) self.F1button.config(textvariable=self.FUNCTION[1], borderwidth=2, relief=GROOVE) self.F2button = Button(self.FUNCTIONframe) self.F2button.config(textvariable=self.FUNCTION[2], borderwidth=2, relief=GROOVE) self.FUNCTIONbuttons.append(self.F0button) self.FUNCTIONbuttons.append(self.F1button) self.FUNCTIONbuttons.append(self.F2button) for i in Range3: self.FUNCTIONbuttons[i].grid(row=1, column=i, sticky="wens", padx=5) self.FUNCTIONframe.pack(side=LEFT, padx=8, pady=3) def mkStates(self, f): self.STATESframe = Frame(f) self.STATESframe.config(relief=GROOVE) self.STATESframe.config(borderwidth=2) self.CARRYtag = Label(self.STATESframe, text=" carry ", borderwidth=2, relief=GROOVE) self.CARRYtag.grid(row=0, column=0, padx=5, pady=2, sticky="wens") self.ZEROtag = Label(self.STATESframe, text=" zero ", borderwidth=2, relief=GROOVE) self.ZEROtag.grid(row=0, column=1, padx=5, pady=1, sticky="wens") self.SIGNtag = Label(self.STATESframe, text=" sign ", borderwidth=2, relief=GROOVE) self.SIGNtag.grid(row=0, column=2, padx=5, pady=2, sticky="wens") self.CARRY = self.mkStringVar("0") self.ZERO = self.mkStringVar("0") self.SIGN = self.mkStringVar("0") self.CARRYlabel = Label(self.STATESframe, textvariable=self.CARRY, borderwidth=2, relief=GROOVE) self.CARRYlabel.grid(row=1, column=0, padx=5, pady=2, sticky="wens") self.ZEROlabel = Label(self.STATESframe, textvariable=self.ZERO, borderwidth=2, relief=GROOVE) self.ZEROlabel.grid(row=1, column=1, padx=5, pady=1, sticky="wens") self.SIGNlabel = Label(self.STATESframe, textvariable=self.SIGN, borderwidth=2, relief=GROOVE) self.SIGNlabel.grid(row=1, column=2, padx=5, pady=2, sticky="wens") self.STATESframe.pack(side=RIGHT, padx=8, pady=3) # ============================================================================== def mkTagLabels(self, f): self.ALabel = self.mkLabel(f, "A", 1, 0) self.BLabel = self.mkLabel(f, "B", 2, 0) self.BLabel.config(bg="black", fg="yellow") self.CLabel = self.mkLabel(f, "C", 3, 0) self.CLabel.config(bg="black", fg="yellow") self.DLabel = self.mkLabel(f, "D", 4, 0) self.M1Label = self.mkLabel(f, "M1", 5, 0) self.M2Label = self.mkLabel(f, "M2", 6, 0) self.XLabel = self.mkLabel(f, "X", 7, 0) self.YLabel = self.mkLabel(f, "Y", 8, 0) self.J1Label = self.mkLabel(f, "J1", 9, 0) self.J2Label = self.mkLabel(f, "J2", 10, 0) self.PC1Label = self.mkLabel(f, "PC1", 11, 0) self.PC2Label = self.mkLabel(f, "PC2", 12, 0) self.Inc1Label = self.mkLabel(f, "Inc1", 13, 0) self.Inc2Label = self.mkLabel(f, "Inc2", 14, 0) self.IncUnit1Label = self.mkLabel(f, "IncUnit1", 15, 0) self.IncUnit2Label = self.mkLabel(f, "IncUnit2", 16, 0) self.InstLabel = self.mkLabel(f, "Inst", 17, 0) self.addLabel = self.mkLabel(f, "ADD", 18, 0) self.incLabel = self.mkLabel(f, "INC", 19, 0) self.andLabel = self.mkLabel(f, "AND", 20, 0) self.orLabel = self.mkLabel(f, "OR", 21, 0) self.xorLabel = self.mkLabel(f, "XOR", 22, 0) self.notLabel = self.mkLabel(f, "NOT", 23, 0) self.shlLabel = self.mkLabel(f, "SHL", 24, 0) self.clrLabel = self.mkLabel(f, "CLR", 25, 0) self.functionTagLabelDictionary = { (0,0,0) : self.addLabel, \ (0,0,1) : self.incLabel, \ (0,1,0) : self.andLabel, \ (0,1,1) : self.orLabel, \ (1,0,0) : self.xorLabel, \ (1,0,1) : self.notLabel, \ (1,1,0) : self.shlLabel, \ (1,1,1) : self.clrLabel \ } for i in self.functionTagLabelDictionary.values(): i.config(bg="black", fg="yellow") # ============================================================================== def mkRegisterStringVars(self): self.FUNCTION = [self.mkStringVar("0") for unused_i in Range3] self.DATABUS = [self.mkStringVar("0") for unused_i in Range8] self.Inst = [self.mkStringVar("0") for unused_i in Range8] self.A = [self.mkStringVar("0") for unused_i in Range8] self.B = [self.mkStringVar("0") for unused_i in Range8] self.C = [self.mkStringVar("0") for unused_i in Range8] self.D = [self.mkStringVar("0") for unused_i in Range8] self.M1 = [self.mkStringVar("0") for unused_i in Range8] self.M2 = [self.mkStringVar("0") for unused_i in Range8] self.X = [self.mkStringVar("0") for unused_i in Range8] self.Y = [self.mkStringVar("0") for unused_i in Range8] self.J1 = [self.mkStringVar("0") for unused_i in Range8] self.J2 = [self.mkStringVar("0") for unused_i in Range8] self.PC1 = [self.mkStringVar("0") for unused_i in Range8] self.PC2 = [self.mkStringVar("0") for unused_i in Range8] self.Inc1 = [self.mkStringVar("0") for unused_i in Range8] self.Inc2 = [self.mkStringVar("0") for unused_i in Range8] self.IncUnit1 = [self.mkStringVar("0") for unused_i in Range8] self.IncUnit2 = [self.mkStringVar("0") for unused_i in Range8] self.Add = [self.mkStringVar("0") for unused_i in Range8] self.Inc = [self.mkStringVar("0") for unused_i in Range8] self.And = [self.mkStringVar("0") for unused_i in Range8] self.Or = [self.mkStringVar("0") for unused_i in Range8] self.Xor = [self.mkStringVar("0") for unused_i in Range8] self.Not = [self.mkStringVar("0") for unused_i in Range8] self.Shl = [self.mkStringVar("0") for unused_i in Range8] self.Clr = [self.mkStringVar("0") for unused_i in Range8] self.ADDRESSBUS = [self.mkStringVar("0") for unused_i in Range16] self.MEMORY = [self.mkStringVar("0") for unused_i in Range8] # ============================================================================== def setRegisterLabelColor(self, L, bc, fc="black"): for i in L: i.config(bg=bc, fg=fc) def mkRegisterLabels(self, f): self.Alabels = self.mkLabelList(f, self.A, 1) self.setRegisterLabelColor(self.Alabels, "gray90") self.Blabels = self.mkLabelList(f, self.B, 2) self.setRegisterLabelColor(self.Blabels, "black", "yellow") self.Clabels = self.mkLabelList(f, self.C, 3) self.setRegisterLabelColor(self.Clabels, "black", "yellow") self.Dlabels = self.mkLabelList(f, self.D, 4) self.setRegisterLabelColor(self.Dlabels, "gray90") self.M1labels = self.mkLabelList(f, self.M1, 5) self.setRegisterLabelColor(self.M1labels, "gray90") self.M2labels = self.mkLabelList(f, self.M2, 6) self.setRegisterLabelColor(self.M2labels, "gray90") self.Xlabels = self.mkLabelList(f, self.X, 7) self.setRegisterLabelColor(self.Xlabels, "gray90") self.Ylabels = self.mkLabelList(f, self.Y, 8) self.setRegisterLabelColor(self.Ylabels, "gray90") self.J1labels = self.mkLabelList(f, self.J1, 9) self.J2labels = self.mkLabelList(f, self.J2, 10) self.PC1labels = self.mkLabelList(f, self.PC1, 11) self.PC2labels = self.mkLabelList(f, self.PC2, 12) self.Inc1labels = self.mkLabelList(f, self.Inc1, 13) self.setRegisterLabelColor(self.Inc1labels, "gray95") self.Inc2labels = self.mkLabelList(f, self.Inc2, 14) self.setRegisterLabelColor(self.Inc2labels, "gray95") self.IncUnit1labels = self.mkLabelList(f, self.IncUnit1, 15) self.setRegisterLabelColor(self.IncUnit1labels, "gray95") self.IncUnit2labels = self.mkLabelList(f, self.IncUnit2, 16) self.setRegisterLabelColor(self.IncUnit2labels, "gray95") self.Instlabels = self.mkLabelList(f, self.Inst, 17) self.addlabels = self.mkLabelList(f, self.Add, 18) self.setRegisterLabelColor(self.addlabels, "black", "red") self.inclabels = self.mkLabelList(f, self.Inc, 19) self.setRegisterLabelColor(self.inclabels, "black", "yellow") self.andlabels = self.mkLabelList(f, self.And, 20) self.setRegisterLabelColor(self.andlabels, "black", "yellow") self.orlabels = self.mkLabelList(f, self.Or, 21) self.setRegisterLabelColor(self.orlabels, "black", "yellow") self.xorlabels = self.mkLabelList(f, self.Xor, 22) self.setRegisterLabelColor(self.xorlabels, "black", "yellow") self.notlabels = self.mkLabelList(f, self.Not, 23) self.setRegisterLabelColor(self.notlabels, "black", "yellow") self.shllabels = self.mkLabelList(f, self.Shl, 24) self.setRegisterLabelColor(self.shllabels, "black", "yellow") self.clrlabels = self.mkLabelList(f, self.Clr, 25) self.setRegisterLabelColor(self.clrlabels, "black", "yellow") self.functionLabelsDictionary = { (0,0,0) : self.addlabels, \ (0,0,1) : self.inclabels, \ (0,1,0) : self.andlabels, \ (0,1,1) : self.orlabels, \ (1,0,0) : self.xorlabels, \ (1,0,1) : self.notlabels, \ (1,1,0) : self.shllabels, \ (1,1,1) : self.clrlabels \ } # ===== Load & Select ========================================================== def mkLoad8Buttons(self, f): self.loadA = self.mkButton(f, "load A", 1, 9, 1, 2) self.loadB = self.mkButton(f, "load B", 2, 9, 1, 2) self.loadC = self.mkButton(f, "load C", 3, 9, 1, 2) self.loadD = self.mkButton(f, "load D", 4, 9, 1, 2) self.loadM1 = self.mkButton(f, "load M1", 5, 9, 1, 2) self.loadM2 = self.mkButton(f, "load M2", 6, 9, 1, 2) self.loadX = self.mkButton(f, "load X", 7, 9) self.loadY = self.mkButton(f, "load Y", 8, 9) self.loadJ1 = self.mkButton(f, "load J1", 9, 9, 1, 2) self.loadJ2 = self.mkButton(f, "load J2", 10, 9, 1, 2) self.loadInst = self.mkButton(f, "load Inst", 17, 9, 1, 2) def mkLoad16Buttons(self, f): self.loadXY = self.mkButton(f, "load XY", 7, 10, 2, 1) self.loadPC = self.mkButton(f, "load PC", 11, 9, 2, 2) self.loadINC = self.mkButton(f, "load INC", 13, 9, 2, 2) def mkSelect8Buttons(self, f): self.selectA = self.mkButton(f, "select A", 1, 11, 1, 2) self.selectB = self.mkButton(f, "select B", 2, 11, 1, 2) self.selectC = self.mkButton(f, "select C", 3, 11, 1, 2) self.selectD = self.mkButton(f, "select D", 4, 11, 1, 2) self.selectM1 = self.mkButton(f, "select M1", 5, 11) self.selectM2 = self.mkButton(f, "select M2", 6, 11) self.selectX = self.mkButton(f, "select X", 7, 11) self.selectY = self.mkButton(f, "select Y", 8, 11) def mkSelect16Buttons(self, f): self.selectM = self.mkButton(f, "select M", 5, 12, 2, 1) self.selectXY = self.mkButton(f, "select XY", 7, 12, 2, 1) self.selectJ = self.mkButton(f, "select J", 9, 11, 2, 2) self.selectPC = self.mkButton(f, "select PC", 11, 11, 2, 2) self.selectINC = self.mkButton(f, "select INC", 13, 11, 2, 2) # ===== System Messages ======================================================== def mkMessageArea(self, f): self.text = Text(f, height=36, width=64) self.text.configure(font=("Courier", 11, "bold"), bg="black", fg="green") self.scroll = Scrollbar(f, command=self.text.yview) self.text.configure(yscrollcommand=self.scroll.set) self.text.pack(side=LEFT, padx=3, pady=2) self.scroll.pack(side=RIGHT, fill=Y, padx=3, pady=2) def addText(self, text): self.text.insert(END, text + "\n") self.text.yview(END) # ===== Initialization ========================================================= def __init__(self): Tk.__init__(self) self.title("Virtual Machine") self.config(bg="blue") self.registers = LabelFrame(self, bg="blue") self.registers.config(relief=GROOVE) self.registers.config(borderwidth=2) self.registers.config(text="Virtual Machine: controls and states") self.registers.config(labelanchor="nw") self.registers.pack(side=LEFT, fill=BOTH) self.mkRegisterStringVars() self.mkTagLabels(self.registers) self.mkDataBus(self.registers) self.mkRegisterLabels(self.registers) self.mkLoad8Buttons(self.registers) self.mkLoad16Buttons(self.registers) self.mkSelect8Buttons(self.registers) self.mkSelect16Buttons(self.registers) self.mkAddressBus(self.registers) self.mkALU(self.registers) self.mkMemory(self.registers) self.mkProgramLoad(self.registers) self.mkProgramControl(self.registers) self.mkHaltArea(self.registers) self.messages = LabelFrame(self, bg="blue") self.messages.config(relief=GROOVE) self.messages.config(borderwidth=2) self.messages.config(text="Virtual Machine: system messages") self.messages.config(labelanchor="nw") self.messages.pack(side=RIGHT, fill=BOTH) self.mkMessageArea(self.messages)
class UIBelote(Notify): """ Initialise the belote widget """ def __init__(self, root, x, y, size_x, size_y): Notify.__init__(self) # Memorise the frame self._root = root self._frame = Frame(width = size_x, height = size_y) # No resize self._frame.pack_propagate(0) # Style self._frame.config(borderwidth = 5) self._x = x self._y = y # Init the buttons self._init_button() self.enable() self.clicked = False def set_position(self, x, y): self._x = x self._y = y def display(self): """ Display the widget on the table """ self._frame.place(in_ = self._root, x = self._x, y = self._y) def hide(self): """ Hide the pannel when the biddings are closed for example """ self._frame.place_forget() def _init_button(self): """ TODO """ h = 2 w = 2 self._button = Button(self._frame, text="Belote", \ height=h, width=w, \ command= self._click_belote) self._button.pack(fill=X) self._button_clicked = False def set_button_style(self, clicked): """ TODO """ fg = 'white' if clicked else 'black' bg = 'black' if clicked else 'white' self._button.config(foreground= fg, background= bg) def _click_belote(self): """ TODO """ self.clicked = not self.clicked def disable(self): """ Disable the bid button """ self._button.config(state = DISABLED) def enable(self): """ Enable the bid button """ self._button.config(state = NORMAL) def belote_ack(self): """ """ self._button.config(text = "Rebelote") def rebelote_ack(self): """ """ self.disable() def re_init(self): self._button.clicked = False self._button.config(text = "Belote") @property def clicked(self): return self._button_clicked @clicked.setter def clicked(self, c): self._button_clicked = c self.set_button_style(c)
class main_window(Frame): def __init__(self,master): #AQUI SE DESARROLLA LA APLICACION... #color= self.frame_left_up_right_in1 global var_phaser_level var_phaser_level=tk.DoubleVar() global var_phaser_order var_phaser_order=tk.DoubleVar() global var_phaser_gain var_phaser_gain=tk.DoubleVar() global var_distortion_level var_distortion_level=tk.DoubleVar() global var_distortion_mixer var_distortion_mixer=tk.DoubleVar() global var_distortion_gain var_distortion_gain=tk.DoubleVar() #new variables of equalizer global var_high_level var_high_level=tk.DoubleVar() global var_middle_level var_middle_level=tk.DoubleVar() global var_low_level var_low_level=tk.DoubleVar() Frame.__init__(self, master, background="white") self.master=master global p p = pyaudio.PyAudio() global stream stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True,frames_per_buffer=CHUNK) #print(wf.getframerate()) #input_device_index=2 get_phaser_level(None) #get_distortion_level(None) master.geometry('800x800+0+0') master.title('Control Principal') master.configure(background="yellow") #main frames frame_main_left=Frame(master,width=400, height=450,bg="red") frame_main_left.grid(row=0,column=0) frame_main_right=Frame(master,width=400, height=450,bg="white") frame_main_right.grid(row=0,column=1) #sub frames frame_left_up=Frame(frame_main_left,width=400, height=300,bg="blue") frame_left_up.pack(side=TOP) frame_left_down=Frame(frame_main_left,width=400, height=150,bg="brown") frame_left_down.pack(side=BOTTOM) phaser_frame=LabelFrame(frame_left_down,text="PHASER EFFECT",width=380, height=150,bg="white") phaser_frame.pack() #def change_led_phaser(event): path_phaser = '/home/tony/PycharmProjects/proyecto1/phasermodified.gif' #img_phaser = Image.open(path_phaser) img_phaser = PIL.Image.open(open('/home/tony/PycharmProjects/proyecto1/phasermodified.gif','rb')) #img_phaser.resize((300, 300), Image.ANTIALIAS) img_phaser.resize((300, 300), PIL.Image.ANTIALIAS) img_phaser=ImageTk.PhotoImage(img_phaser,width=380, height=150) button_phaser=Button(phaser_frame,text="PHASER EFFECT",width=380, height=150,bg="blue", image=img_phaser) button_phaser.bind('<Button-1>', lambda event:negar(flag,0)) button_phaser.pack() #button_phaser.bind('<Button-1>', lambda event:frame_left_up_right_in1.config(bg="black")) #button_phaser.bind('<Button-3>', lambda event:frame_left_up_right_in1.config(bg="white")) frame_right_up=Frame(frame_main_right,width=400, height=300,bg="red") frame_right_up.pack(side=TOP) frame_right_down=Frame(frame_main_right,width=400, height=150,bg="white") frame_right_down.pack(side=BOTTOM) distortion_frame=LabelFrame(frame_right_down,text="DISTORTION EFFECT",width=380, height=150,bg="white") distortion_frame.pack() path_distortion = '/home/tony/PycharmProjects/proyecto1/distortionmodified.gif' img_distortion = PIL.Image.open(path_distortion) img_distortion.resize((300, 300), PIL.Image.ANTIALIAS) img_distortion=ImageTk.PhotoImage(img_distortion,width=380, height=150) button_distortion=Button(distortion_frame,text="DISTORTION EFFECT",width=380, height=150,bg="blue",image=img_distortion) button_distortion.bind('<Button-1>', lambda event:negar(flag,1)) button_distortion.pack() #button_distortion.bind('<Button-1>', lambda event:frame_right_up_right_in1.config(bg="black")) #button_distortion.bind('<Button-3>', lambda event:frame_right_up_right_in1.config(bg="white")) #subsubframes left frame_left_up_left=Frame(frame_left_up,width=300, height=300,bg="blue") frame_left_up_left.pack(side=LEFT) frame_left_up_right=Frame(frame_left_up,width=100, height=300,bg="blue") frame_left_up_right.pack(side=RIGHT) #subsubframes right frame_right_up_left=Frame(frame_right_up,width=300, height=300,bg="blue") frame_right_up_left.pack(side=LEFT) frame_right_up_right=Frame(frame_right_up,width=100, height=300,bg="blue") frame_right_up_right.pack(side=RIGHT) #------------------------------------------------------------------------------------------------------- #subframes left widgtes IN FRAME LEFT UP label_left1=LabelFrame(frame_left_up_left,text="PHASE",width=280, height=70,bg="white") label_left1.pack() frame_left_up_left_in1=Frame(label_left1,width=280, height=70,bg="black") frame_left_up_left_in1.pack(fill="both", expand=True, padx=5, pady=5) #phaser level parameter slide1_left= Scale(frame_left_up_left_in1,variable=var_phaser_level, from_=0, to=6.28,resolution=0.01, orient=HORIZONTAL) slide1_left.pack() slide1_left.config(length=270,width=30) #------------------------------------------------------------------------------------------- label_left2=LabelFrame(frame_left_up_left,text="ORDER",width=280, height=70,bg="white") label_left2.pack() frame_left_up_left_in2=Frame(label_left2,width=280, height=70,bg="yellow") frame_left_up_left_in2.pack(fill="both", expand=True, padx=5, pady=5) #phaser order parameter slide2_left = Scale(frame_left_up_left_in2,variable=var_phaser_order, from_=0, to=4,tickinterval=1, orient=HORIZONTAL) slide2_left.pack() slide2_left.config(length=270,width=30) #-------------------------------------------------------------------------------------------- label_left3=LabelFrame(frame_left_up_left,text="GAIN",width=280, height=70,bg="white") label_left3.pack() frame_left_up_left_in3=Frame(label_left3,width=280, height=70,bg="red") frame_left_up_left_in3.pack(fill="both", expand=True, padx=5, pady=5) #phaser gain parameter slide3_left = Scale(frame_left_up_left_in3,variable=var_phaser_gain, from_=0, to=10, orient=HORIZONTAL) slide3_left.pack() slide3_left.config(length=270,width=30) #subframes right widgtes IN FRAME LEFT UP self.frame_left_up_right_in1=Frame(frame_left_up_right,width=80, height=250,bg="white") self.frame_left_up_right_in1.pack(fill="both", expand=True, padx=5, pady=5) #frame_left_up_right_in2=Frame(frame_left_up_right,width=80, height=250,bg="brown") #frame_left_up_right_in2.pack(fill="both", expand=True, padx=5, pady=5) #w = Entry(frame_left_up_left_in1, xscrollcommand) #------------------------------------------------------------------------------------------------ #subframes left widgtes IN FRAME RIGHT UP label_right1=LabelFrame(frame_right_up_left,text="MIX",width=280, height=70,bg="white") label_right1.pack() frame_right_up_left_in1=Frame(label_right1,width=280, height=120,bg="brown") frame_right_up_left_in1.pack(fill="both", expand=True, padx=5, pady=5) slide1_right = Scale(frame_right_up_left_in1,variable=var_distortion_mixer, from_=0, to=100, orient=HORIZONTAL) slide1_right.pack() slide1_right.config(length=270,width=30) #------------------------------------------------------------------------------------------------ label_right2=LabelFrame(frame_right_up_left,text="LEVEL",width=280, height=70,bg="white") label_right2.pack() frame_right_up_left_in2=Frame(label_right2,width=280, height=120,bg="yellow") frame_right_up_left_in2.pack(fill="both", expand=True, padx=5, pady=5) slide2_right = Scale(frame_right_up_left_in2, variable=var_distortion_level,from_=0, to=200, orient=HORIZONTAL) slide2_right.pack() slide2_right.config(length=270,width=30) #-------------------------------------------- """ label_right3=LabelFrame(frame_right_up_left,text="GAIN",width=280, height=70,bg="white") label_right3.pack() frame_right_up_left_in3=Frame(label_right3,width=280, height=120,bg="yellow") frame_right_up_left_in3.pack(fill="both", expand=True, padx=5, pady=5) slide3_right = Scale(frame_right_up_left_in3, variable=var_distortion_gain,from_=0, to=100, orient=HORIZONTAL) slide3_right.pack() slide3_right.config(length=270,width=30) """ #subframes right widgtes IN RIGHT LEFT UP self.frame_right_up_right_in1=Frame(frame_right_up_right,width=80, height=250,bg="white") self.frame_right_up_right_in1.pack(fill="both", expand=True, padx=5, pady=5) #new frames frame_equalizer=Frame(master,width=800, height=200,bg="black") frame_equalizer.grid(row=1,column=0,columnspan=2) high_label=LabelFrame(frame_equalizer,text="HIGH",width=800, height=72,bg="white") high_label.pack() middle_label=LabelFrame(frame_equalizer,text="MIDDLE",width=800, height=72,bg="white") middle_label.pack() low_label=LabelFrame(frame_equalizer,text="LOW",width=800, height=72,bg="white") low_label.pack() high_frame=Frame(high_label,width=780, height=70,bg="black") high_frame.pack(fill="both", expand=True, padx=5, pady=5) middle_frame=Frame(middle_label,width=780, height=70,bg="black") middle_frame.pack(fill="both", expand=True, padx=5, pady=5) low_frame=Frame(low_label,width=780, height=70,bg="black") low_frame.pack(fill="both", expand=True, padx=5, pady=5) high_scale = Scale(high_frame,variable=var_high_level, from_=0, to=20, orient=HORIZONTAL) high_scale.pack() high_scale.config(length=780,width=35) middle_scale = Scale(middle_frame,variable=var_middle_level, from_=0, to=20, orient=HORIZONTAL) middle_scale.pack() middle_scale.config(length=780,width=35) low_scale = Scale(low_frame,variable=var_low_level, from_=0, to=20, orient=HORIZONTAL) low_scale.pack() low_scale.config(length=780,width=35) def cambiar_color(self, i): if i == 0: if flag[i] == True: self.frame_left_up_right_in1.config(bg="black") if flag[i] == False: self.frame_left_up_right_in1.config(bg="white") if i == 1: if flag[i] == True: self.frame_right_up_right_in1.config(bg="black") if flag[i] == False: self.frame_right_up_right_in1.config(bg="white")
def evaluationUI(self): modeldetails = header(self.frame,"Model") fm = Frame(self.frame) fm.config(bg=Styles.colours["grey"]) resultdetails = header(self.frame,"Results") resultsframe = Frame(self.frame) resultsframe.config(bg=Styles.colours["grey"]) #Model details Message(fm, text="Command:", font=Styles.fonts["h2"], bg=Styles.colours["grey"],width=200).grid(row=0,column=0,sticky=E) Message(fm, text=self.params["command"].get(), font=Styles.fonts["h3"], bg=Styles.colours["grey"],width=415).grid(row=0,column=1,sticky=W) Message(fm, text="Model Input:", font=Styles.fonts["h2"], bg=Styles.colours["grey"],width=200).grid(row=1,column=0,sticky=E) Message(fm, text=self.params["modelinput"].get(), font=Styles.fonts["h3"], bg=Styles.colours["grey"],width=415).grid(row=1,column=1,sticky=W) Message(fm, text="Model Output:", font=Styles.fonts["h2"], bg=Styles.colours["grey"],width=200).grid(row=2,column=0,sticky=E) Message(fm, text=self.params["modeloutput"].get(), font=Styles.fonts["h3"], bg=Styles.colours["grey"],width=415).grid(row=2,column=1,sticky=W) #Table Headers Label(resultsframe,text=" # ", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=5).grid(row=0,column=0,sticky=E) Label(resultsframe,text="Kernel:", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=9).grid(row=0,column=1,sticky=E) Label(resultsframe,text="Policy:", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=9).grid(row=0,column=2,sticky=E) Label(resultsframe,text="Iterations:", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=14).grid(row=0,column=3,sticky=E) Label(resultsframe,text="Best Result:", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=14).grid(row=0,column=4,sticky=E) Label(resultsframe,text="Time (s):", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=14).grid(row=0,column=5,sticky=E) Label(resultsframe,text="", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=14).grid(row=0,column=6,sticky=E) #Table Data for i,e in enumerate(self.experiments): if e.has_key("iterfinish"): Label(resultsframe,text=str(i+1), font=Styles.fonts["entryFilled"],bg=Styles.colours["grey"],width=5).grid(row=i+1,column=0,sticky=E) Label(resultsframe,text=e["kernel"].upper(), font=Styles.fonts["entryFilled"],bg=Styles.colours["grey"],width=9).grid(row=i+1,column=1,sticky=E) Label(resultsframe,text=e["policy"][0].upper(), font=Styles.fonts["entryFilled"],bg=Styles.colours["grey"],width=9).grid(row=i+1,column=2,sticky=E) Label(resultsframe,text=e["iterfinish"], font=Styles.fonts["entryFilled"],bg=Styles.colours["grey"],width=14).grid(row=i+1,column=3,sticky=E) Label(resultsframe,text="{0:.5f}".format(e["best"]), font=Styles.fonts["entryFilled"],bg=Styles.colours["grey"],width=14).grid(row=i+1,column=4,sticky=E) Label(resultsframe,text="{0:.2f}".format(e["time"]), font=Styles.fonts["entryFilled"],bg=Styles.colours["grey"],width=14).grid(row=i+1,column=5,sticky=E) yellowbutton(resultsframe,"Query",10,lambda x: self.query(e["modelid"])).grid(row=i+1,column=6,sticky=E,pady=3) else: Label(resultsframe,text=str(i+1), font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=5).grid(row=i+1,column=0,sticky=E) Label(resultsframe,text=e["kernel"].upper(), font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=9).grid(row=i+1,column=1,sticky=E) Label(resultsframe,text=e["policy"][0].upper(), font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=9).grid(row=i+1,column=2,sticky=E) Label(resultsframe,text="Not Started", font=Styles.fonts["entry"],bg=Styles.colours["grey"],width=14).grid(row=i+1,column=3,sticky=W+E,columnspan=3) #Footer buttons y1 = camobutton(self.footer,"Save Console Logs",18,click=lambda x: self.saveconsole()) y1.config(font=Styles.fonts["h2"]) y1.pack(side=LEFT,fill=BOTH, padx=5, pady=5) y2 = camobutton(self.footer,"Output Directory",18,lambda x: self.opendir()) y2.config(font=Styles.fonts["h2"]) y2.pack(side=LEFT,fill=BOTH, padx=5, pady=5) y3 = yellowbutton(self.footer,"Exit",18,lambda x: self.closeall()) y3.config(font=Styles.fonts["h2"]) y3.pack(side=RIGHT,fill=BOTH, padx=5, pady=5) #Grid everything #Model Title and Frame modeldetails.grid(row=0,column=0,columnspan=3,sticky=W + E + N + S) fm.grid(row=1, column=0,columnspan=3,sticky=W + E + N + S) #Result Title and Frame resultdetails.grid(row=2, column=0,columnspan=3,sticky=W + E + N + S) resultsframe.grid(row=3, column=0,columnspan=3,sticky=W + E + N + S) #Footer self.footer.grid(row=3,column=0,sticky=W+E+N+S,columnspan=2)
def experimentdata(self): f = Frame(self.frame) self.experimentframe = f f.config(padx=20, pady=20, bg=Styles.colours["grey"]) modeldetails = header(f, "Model:") fm = Frame(f) fm.config(padx=20, pady=20, bg=Styles.colours["grey"]) infoh(fm, "Command:", self.params["command"].get(), 0, 0) infoh(fm, "Model Input:", self.params["modelinput"].get(), 1, 0) infoh(fm, "Model Output:", self.params["modeloutput"].get(), 2, 0) self.numexperitments = header(f, "Current Experiment: 0/0") _, self.iterinfo = infov(f, "Iteration:", "-", 5, 0) _, self.kernelinfo = infov(f, "Kernel:", "-", 5, 1) _, self.policyinfo = infov(f, "Policy:", "-", 5, 2) resultsframe = Frame(f) resultsframe.config(bg=Styles.colours["grey"]) headersmall(resultsframe, "Best Result: ").grid(row=0, column=0, sticky=W + E + N + S) Label(resultsframe, text="Current:", font=Styles.fonts["entry"], bg=Styles.colours["grey"], width=9).grid(row=0, column=1, sticky=E) self.curbestlabel = Label(resultsframe, bg=Styles.colours["grey"], text="-", width=20, font=Styles.fonts["h2"]) self.curbestlabel.grid(row=0, column=2, sticky=W) Label(resultsframe, text="Overall:", font=Styles.fonts["entry"], bg=Styles.colours["grey"], width=9).grid(row=1, column=1, sticky=E) self.totbestlabel = Label(resultsframe, text=self.iniparams["totbest"], bg=Styles.colours["grey"], width=20, font=Styles.fonts["h2"]) self.totbestlabel.grid(row=1, column=2, sticky=W) curresultsframe = Frame(f) curresultsframe.config(bg=Styles.colours["grey"]) headersmall(curresultsframe, "Latest Iteration: ").grid(row=0, column=0, sticky=W + E + N + S) Label(curresultsframe, text="y:", font=Styles.fonts["entry"], bg=Styles.colours["grey"], width=9).grid(row=0, column=1, sticky=E) self.cury = Label(curresultsframe, text="-", width=20, font=Styles.fonts["h2"], bg=Styles.colours["grey"]) self.cury.grid(row=0, column=2, sticky=W) Label(curresultsframe, text="mu:", font=Styles.fonts["entry"], bg=Styles.colours["grey"], width=9).grid(row=1, column=1, sticky=E) self.curmu = Label(curresultsframe, text=self.iniparams["totbest"], bg=Styles.colours["grey"], width=20, font=Styles.fonts["h2"]) self.curmu.grid(row=1, column=2, sticky=W) Label(curresultsframe, text="var:", font=Styles.fonts["entry"], bg=Styles.colours["grey"], width=9).grid(row=2, column=1, sticky=E) self.curvar = Label(curresultsframe, text=self.iniparams["totbest"], bg=Styles.colours["grey"], width=20, font=Styles.fonts["h2"]) self.curvar.grid(row=2, column=2, sticky=W) modeldetails.grid(row=0, column=0, columnspan=3, sticky=W + E + N + S) fm.grid(row=1, column=0, columnspan=3, sticky=W + E + N + S, padx=20) self.numexperitments.grid(row=4, column=0, columnspan=3, sticky=W + E + N + S) resultsframe.grid(row=7, column=0, columnspan=3, sticky=W + E + N + S) curresultsframe.grid(row=8, column=0, columnspan=3, sticky=W + E + N + S) f.grid(row=0, column=1, sticky=W + E + N + S)
class AdvancedSettings(): def __init__(self, console, params): self.console = console self.params = params self.advsettingslist = ["solver", "initializer", "recommender", "normalize", "data", "dims", "dimscheudler", "gpsf", "gpmu", "gpell", "gpsn", "priorsnscale", "priorsnmin", "priorsfmu", "priorsfsigma", "priorsfmin", "priorella", "priorellb", "priormumu", "priormuvar", "mcmcburn", "mcmcn", "eixi", "pixi", "ucbdelta", "ucbxi", "thompsonn", "thompsonrng"] self.paramsdefaults = dict((k, self.params[k].get()) for k in self.advsettingslist) self.toplevel = Toplevel() self.toplevel.title("Project B: Advanced Settings") self.advheader() self.frame = Frame(self.toplevel) self.frame.config(padx=20, pady=20, bg=Styles.colours["grey"]) self.frame.pack(fill=BOTH) self.solver() self.rec() self.initial() self.initnumber() self.mcmc() self.policyset() self.dimscheduler() Label(self.frame, text=" ", bg=Styles.colours["grey"]).grid(row=1, column=3, sticky=W, columnspan=1) self.basicgp() self.prior() self.data() self.submitadvancedsettings() def advheader(self): headerframe = Frame(self.toplevel) headerframe.config(bg=Styles.colours["darkGrey"]) advancedsettingsheader = Message(headerframe, text="Advanced Settings", bg=Styles.colours["darkGrey"], justify=CENTER, foreground=Styles.colours["yellow"], pady=5, width=200, font=Styles.fonts["h1"]) qb = qbutton(headerframe) babout = camobutton(headerframe, "About", 10) advancedsettingsheader.pack(side=LEFT, fill=BOTH, padx=5, pady=5) qb.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) babout.pack(side=RIGHT, fill=BOTH, padx=5, pady=5) headerframe.pack(fill=BOTH, pady=0) def solver(self): solverheader = headersmall(self.frame, text="Solvers:") direct = Radiobutton(self.frame, text="Direct", variable=self.params["solver"], value="direct", bg=Styles.colours["grey"]) lbfgs = Radiobutton(self.frame, text="LBFGS", variable=self.params["solver"], value="lbfgs", bg=Styles.colours["grey"]) message = Message(self.frame, text="Enable normalization if you use lbfgs", width=200) try: import nlopt except: self.params["solver"].set("lbfgs") self.params["normalize"].set(1) direct.config(state=DISABLED) message.config(text="You do not have nlopt library installed to use the Direct Solver", bg=Styles.colours["lightRed"]) normalize = Checkbutton(self.frame, text="Normalize Input", variable=self.params["normalize"], bg=Styles.colours["grey"]) solverheader.grid(row=1, column=0, sticky=W, columnspan=2) direct.grid(row=2, column=0, pady=0, sticky=W, padx=10) lbfgs.grid(row=3, column=0, pady=0, sticky=W, padx=10) message.grid(row=2, column=1, rowspan=1) normalize.grid(row=3, column=1) def rec(self): recheader = headersmall(self.frame, text="Recommender:") incumbent = Radiobutton(self.frame, text="Incumbent", variable=self.params["recommender"], value="incumbent", bg=Styles.colours["grey"]) latent = Radiobutton(self.frame, text="Latent", variable=self.params["recommender"], value="latent", bg=Styles.colours["grey"]) observed = Radiobutton(self.frame, text="Observed", variable=self.params["recommender"], value="observed", bg=Styles.colours["grey"]) recheader.grid(row=4, column=0, sticky=W, columnspan=1) incumbent.grid(row=5, column=0, pady=0, sticky=W, padx=10) latent.grid(row=6, column=0, pady=0, sticky=W, padx=10) observed.grid(row=7, column=0, pady=0, sticky=W, padx=10) def initial(self): iniheader = headersmall(self.frame, text="Initial points sampler:") latin = Radiobutton(self.frame, text="Latin", variable=self.params["initializer"], value="latin", bg=Styles.colours["grey"]) sobol = Radiobutton(self.frame, text="Sobol", variable=self.params["initializer"], value="sobol", bg=Styles.colours["grey"]) uniform = Radiobutton(self.frame, text="Uniform", variable=self.params["initializer"], value="uniform", bg=Styles.colours["grey"]) iniheader.grid(row=4, column=1, sticky=W, columnspan=1) latin.grid(row=5, column=1, pady=0, sticky=W, padx=10) sobol.grid(row=6, column=1, pady=0, sticky=W, padx=10) uniform.grid(row=7, column=1, pady=0, sticky=W, padx=10) def initnumber(self): f = Frame(self.frame) f.config(bg=Styles.colours["grey"]) minitnumber = Message(f, text="Numbers of samples to sample:", width=300, bg=Styles.colours["grey"]) einitnumber = smallentry(f, self.params["initializernum"], 10) minitnumber.grid(row=0, column=0, sticky=W, columnspan=1) einitnumber.grid(row=0, column=1, sticky=W, columnspan=1, padx=10) f.grid(row=9, column=0, sticky=W, columnspan=2) def mcmc(self): mcmcheader = headersmall(self.frame, text="Markov Chain Monte Carlo Settings:") mmcmcn = Message(self.frame, text="Number of GP models:", width=200, bg=Styles.colours["grey"]) emcmcn = smallentry(self.frame, self.params["mcmcn"], 10) mmcmcburn = Message(self.frame, text="Burn:", width=200, bg=Styles.colours["grey"]) emcmcburn = smallentry(self.frame, self.params["mcmcburn"], 10) mcmcheader.grid(row=10, column=0, sticky=W, columnspan=2) mmcmcn.grid(row=11, column=0, sticky=W, columnspan=1) emcmcn.grid(row=12, column=0, sticky=W, columnspan=1, padx=15) mmcmcburn.grid(row=11, column=1, sticky=W, columnspan=1) emcmcburn.grid(row=12, column=1, sticky=W, columnspan=1) def policyset(self): mischeader = headersmall(self.frame, text="Policy Parameters") fp = Frame(self.frame) fp.config(bg=Styles.colours["grey"]) smallentryframetextv(fp, 0, 0, self.params["eixi"], 10, "EI xi:") smallentryframetextv(fp, 2, 0, self.params["pixi"], 10, "PI xi:") smallentryframetextv(fp, 0, 1, self.params["ucbdelta"], 10, "UCB delta:") smallentryframetextv(fp, 2, 1, self.params["ucbxi"], 10, "UCB xi:") smallentryframetextv(fp, 0, 2, self.params["thompsonn"], 10, "Thompson N:") smallentryframetextv(fp, 2, 2, self.params["thompsonrng"], 10, "Thompson RNG:") mischeader.grid(row=13, column=0, sticky=W, columnspan=2) fp.grid(row=14, column=0, rowspan=4, columnspan=2, sticky=W, padx=10) def dimscheduler(self): mischeader = headersmall(self.frame, text="Dimension Scheduler") f = Frame(self.frame) f.config(bg=Styles.colours["grey"]) smallentryframetext(f, 0, 0, self.params["dims"], 7, "Set Size:") checkdimschel = Checkbutton(self.frame, text="Enable", variable=self.params["dimscheudler"], bg=Styles.colours["grey"]) mischeader.grid(row=18, column=0, sticky=W, columnspan=2) checkdimschel.grid(row=19, column=0, sticky=W, columnspan=1, padx=15) f.grid(row=19, column=1, sticky=W + E, columnspan=1) def basicgp(self): gpheader = headersmall(self.frame, text="Basic GP Settings:") f = Frame(self.frame) f.config(padx=20, bg=Styles.colours["grey"]) gpsf, _ = smallentryframetext(f, 0, 0, self.params["gpsf"], 20, "sf:") gpmu, _ = smallentryframetext(f, 1, 0, self.params["gpmu"], 20, "mu:") Label(f, text=" ", bg=Styles.colours["grey"]).grid(row=0, column=2, sticky=W, rowspan=2) gpell, _ = smallentryframetext(f, 0, 3, self.params["gpell"], 20, "ell:") gpsn, _ = smallentryframetext(f, 1, 3, self.params["gpsn"], 20, "sn:") gpheader.grid(row=1, column=4, sticky=W, columnspan=1) Message(self.frame, text="You can use numpy and python syntax to set the parameters from the data where" " X is the initial and random data, and y is the corresponding output", width=400, font=Styles.fonts["entry"], bg=Styles.colours["grey"]).grid(row=2, column=4, columnspan=2, sticky=W) f.grid(row=3, column=4, sticky=W, columnspan=2, rowspan=3) def prior(self): priorheader = headersmall(self.frame, text="Hyperprior Settings:") f = Frame(self.frame) f.config(padx=20, bg=Styles.colours["grey"]) Message(f, text="Horseshoe Prior sn:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=0, column=0, columnspan=2, sticky=W) epriorsnscale = smallentry(f, self.params["priorsnscale"], 15) mpriorsnscale = Message(f, text="scale:", width=32, bg=Styles.colours["grey"]) mpriorsnscale.grid(row=1, column=0, columnspan=1, sticky=E) epriorsnscale.grid(row=1, column=1, columnspan=1, sticky=W) smallentryframetext(f, 1, 2, self.params["priorsnmin"], 15, "min:") Message(f, text="Log Normal Prior sf:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=2, column=0, columnspan=2, sticky=W) f3 = Frame(f) smallentryframetext(f3, 0, 0, self.params["priorsfmu"], 10, "mu:") smallentryframetext(f3, 0, 2, self.params["priorsfsigma"], 10, "sigma:") smallentryframetext(f3, 0, 4, self.params["priorsfmin"], 10, "min:") f3.grid(row=3, column=0, columnspan=4) Message(f, text="Uniform Prior ell:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=4, column=0, columnspan=2, sticky=W) smallentryframetext(f, 5, 0, self.params["priorella"], 15, "a:") smallentryframetext(f, 5, 2, self.params["priorellb"], 15, "b:") Message(f, text="Gaussian Prior mu:", width=200, bg=Styles.colours["grey"], font=Styles.fonts["entry"]).grid( row=6, column=0, columnspan=2, sticky=W) smallentryframetext(f, 7, 0, self.params["priormumu"], 15, "mu:") smallentryframetext(f, 7, 2, self.params["priormuvar"], 15, "var:") priorheader.grid(row=6, column=4, sticky=W, columnspan=1) Message(self.frame, text="You can set following parameters based on the variables defined in the GP section.", width=400, font=Styles.fonts["entry"], bg=Styles.colours["grey"]).grid(row=7, column=4, columnspan=2) f.grid(row=8, column=4, sticky=E + W, columnspan=2, rowspan=10) def data(self): def datafilesector(e): f = tkFileDialog.askopenfilename(parent=self.frame, title='Choose data file') self.params["data"].set(self.params["data"]) dataheader = headersmall(self.frame, text="Add Data") if type(self.params["data"].get()) == str or self.params["data"] == [[], []]: bdata = yellowbutton(self.frame, "Select Data File", 20, click=None) edata = entry(self.frame, self.params["data"], 30, file=True, fileCheck=True, button=bdata) edata.grid(row=19, column=4, sticky=E, columnspan=1) bdata.grid(row=19, column=5, sticky=W, columnspan=1) else: bdata = yellowbutton(self.frame, "Data has already been selected", 50, click=None) deactivatebutton(bdata) bdata.config(state=DISABLED, bg=Styles.colours["deactivated"]) bdata.grid(row=19, column=4, sticky=W, columnspan=2) dataheader.grid(row=18, column=3, sticky=W, columnspan=2) def submitadvancedsettings(self): def destroywindow(event): self.toplevel.destroy() def canceladvc(event): for k, v in self.paramsdefaults.items(): self.params[k].set(v) destroywindow(event) def submitadvc(event): self.paramsdefaults = dict((k, self.params[k].get()) for k in self.advsettingslist) destroywindow(event) f = Frame(self.toplevel) f.config(padx=15, pady=15, bg=Styles.colours["darkGrey"]) submitadv = yellowbutton(f, "Submit", 30, submitadvc) canceladv = yellowbutton(f, "Cancel", 20, canceladvc) submitadv.pack(side=RIGHT) canceladv.pack(side=RIGHT, padx=20) f.pack(fill=X)
def initUI(self): self.parent.title("IAF CALC 0.01") self.pack(fill=BOTH, expand=1) self.configure(background='white') frameTOP = Frame(self) frameTOP.config(bg="white") frameTOP.pack(side=TOP) frameFILES = Frame(frameTOP) frameFILES.pack(side=LEFT, padx=10) # --- BUTTON FOR FILE 1 --- # frameF1 = LabelFrame(frameFILES, text="Eyes open file:", relief=FLAT, borderwidth=1, background="white") frameF1.pack(fill=X, expand=1) self.nameF1 = Entry(frameF1, width=50) self.nameF1.config(bg="lightgray") self.nameF1.pack(side=LEFT) self.nameF1.delete(0, END) self.nameF1.insert(0, "") self.buttonLoadFile1 = Button(frameF1, text="...", command=self.askOpenFile1) self.buttonLoadFile1.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE 2 --- # frameF2 = LabelFrame(frameFILES, text="Eyes closed file:", relief=FLAT, borderwidth=1, background="white") frameF2.pack(fill=X, expand=1) self.nameF2 = Entry(frameF2, width=50) self.nameF2.config(bg="lightgray") self.nameF2.pack(side=LEFT) self.nameF2.delete(0, END) self.nameF2.insert(0, "") self.buttonLoadFile2 = Button(frameF2, text="...", command=self.askOpenFile2) self.buttonLoadFile2.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE OUTPUT --- # frameO = LabelFrame(frameFILES, text="Output directory:", relief=FLAT, borderwidth=1, background="white") frameO.pack(fill=X, expand=1) self.nameO = Entry(frameO, width=50) self.nameO.config(bg="lightgray") self.nameO.pack(side=LEFT) self.nameO.delete(0, END) self.nameO.insert(0, "") self.buttonSelectOutput = Button(frameO, text="...", command=self.askOutputDirectory) self.buttonSelectOutput.pack(side=LEFT, padx=5, pady=5) # -------------------------------# # self.pack() # self.pack(fill=Y, expand=1) # ---------- PSD PARAMETER SELECTION ---------- # framePARAM = Frame(frameTOP) framePARAM.config(bg="white") framePARAM.pack(side=LEFT, fill=X) frame = LabelFrame(framePARAM, text="PSD Parameters", relief=RIDGE, borderwidth=1, background="white") frame.pack(fill=BOTH, expand=1, side=TOP) wFs = Label(frame, text="Fs:", bg="white") wFs.pack(side=LEFT) self.inputFs = Entry(frame, width=5) self.inputFs.pack(side=LEFT, padx=5) self.inputFs.delete(0, END) self.inputFs.insert(0, "500") wWS = Label(frame, text="Window size:", bg="white") wWS.pack(side=LEFT) self.inputWinSize = Entry(frame, width=5) self.inputWinSize.pack(side=LEFT, padx=5) self.inputWinSize.delete(0, END) self.inputWinSize.insert(0, "1024") wOL = Label(frame, text="Overlap:", bg="white") wOL.pack(side=LEFT) self.inputOverlap = Entry(frame, width=5) self.inputOverlap.pack(side=LEFT, padx=5) self.inputOverlap.delete(0, END) self.inputOverlap.insert(0, "512") wWT = Label(frame, text="Window function:", bg="white") wWT.pack(side=LEFT) variable = StringVar(frame) variable.set("Hamming") # default value self.inputWinType = OptionMenu(frame, variable, "Hamming", "Bartlett", "Blackman", "Hanning", "None") self.inputWinType.config(bg="white", width=10) self.inputWinType.pack(side=LEFT) buttonRun = Button(frame, text="GO!", command=self.goTime) buttonRun.pack(side=RIGHT) # Channel selector frameCh = LabelFrame(framePARAM, text="Channels", relief=RIDGE, borderwidth=1, background="white") frameCh.pack(fill=BOTH, expand=1, side=TOP) self.EOch1 = IntVar() self.inputEOch1 = Checkbutton(frameCh, text="1", variable=self.EOch1, bg="white") self.inputEOch1.pack(side=LEFT) self.EOch2 = IntVar() self.inputEOch2 = Checkbutton(frameCh, text="2", variable=self.EOch2, bg="white") self.inputEOch2.pack(side=LEFT) self.EOch3 = IntVar() self.inputEOch3 = Checkbutton(frameCh, text="3", variable=self.EOch3, bg="white") self.inputEOch3.pack(side=LEFT) self.EOch4 = IntVar() self.inputEOch4 = Checkbutton(frameCh, text="4", variable=self.EOch4, bg="white") self.inputEOch4.pack(side=LEFT) self.EOch5 = IntVar() self.inputEOch5 = Checkbutton(frameCh, text="5", variable=self.EOch5, bg="white") self.inputEOch5.pack(side=LEFT) self.EOch6 = IntVar() self.inputEOch6 = Checkbutton(frameCh, text="6", variable=self.EOch6, bg="white") self.inputEOch6.pack(side=LEFT) self.EOch7 = IntVar() self.inputEOch7 = Checkbutton(frameCh, text="7", variable=self.EOch7, bg="white") self.inputEOch7.pack(side=LEFT) self.EOch8 = IntVar() self.inputEOch8 = Checkbutton(frameCh, text="8", variable=self.EOch8, bg="white") self.inputEOch8.pack(side=LEFT) # IAF Calculation parameters frameIAF = LabelFrame(framePARAM, text="IAF Search Limits", relief=RIDGE, borderwidth=1, background="white") frameIAF.pack(fill=BOTH, expand=1, side=TOP) labelLowBound = Label(frameIAF, text="Lower limit (Hz):", bg="white") labelLowBound.pack(side=LEFT) self.inputLowBound = Entry(frameIAF, width=5) self.inputLowBound.pack(side=LEFT, padx=5) self.inputLowBound.delete(0, END) self.inputLowBound.insert(0, "7") labelUpBound = Label(frameIAF, text="Upper limit (Hz):", bg="white") labelUpBound.pack(side=LEFT) self.inputUpBound = Entry(frameIAF, width=5) self.inputUpBound.pack(side=LEFT, padx=5) self.inputUpBound.delete(0, END) self.inputUpBound.insert(0, "14") self.GaussVar = IntVar() self.inputGauss = Checkbutton(frameIAF, text="Gauss", variable=self.GaussVar, bg="white") self.inputGauss.pack(side=LEFT) buttonRun = Button(frameIAF, text="IAF!", command=self.calculateIAF) buttonRun.pack(side=RIGHT) self.pack() # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # END OF TOP FRAME # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # my variables self.chSelect = 0 self.chOther = 0 self.P1 = ndarray(1) self.f1 = ndarray(1) self.P2 = ndarray(1) self.f2 = ndarray(1) self.filename1 = "..." self.filename2 = "..." self.IAF = 10 self.doGauss = True # FIGURE STUFF !!! self.Pmax = 0 self.Pmin = 0 self.Dmax = 0 self.Dmin = 0 frameBOTTOM = Frame(self) frameBOTTOM.config(bg="white") frameBOTTOM.pack(side=BOTTOM, pady=10) frameFig = LabelFrame(frameBOTTOM, text="Spectrum", relief=RIDGE, borderwidth=1, background="white") frameFig.pack(fill=X, expand=1, side=LEFT, padx=10) self.fig1 = matplotlib.figure.Figure(figsize=(7, 3), dpi=100) #,frameon=False) self.fig1.set_facecolor('white') self.fig = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg( self.fig1, master=frameFig) self.a1 = self.fig1.add_subplot(121) self.a2 = self.fig1.add_subplot(122) self.fig.show() self.fig.get_tk_widget().pack(side=BOTTOM) frameConfig = LabelFrame(frameBOTTOM, text="Filter configuration", relief=RAISED, borderwidth=1, background="white") frameConfig.pack(fill=BOTH, expand=1, side=RIGHT, padx=10) frameIAF = LabelFrame(frameConfig, text="Individual Alpha Frequency (IAF)") frameIAF.config(bg="white") frameIAF.pack(expand=1, side=TOP, padx=10) self.inputIAF = Entry(frameIAF, width=5) self.inputIAF.pack(side=LEFT, padx=5) self.inputIAF.delete(0, END) self.inputIAF.insert(0, "0") self.buttonWriteDefault = Button(frameIAF, text="Update Filters", command=self.updateFilters) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) frameFilters = LabelFrame(frameConfig, text="Filters", relief=RAISED, borderwidth=1, background="white") frameFilters.pack(fill=X, expand=1, side=TOP) # THETA FRAME frameTheta = LabelFrame(frameFilters, text="Theta", relief=RAISED, borderwidth=1, background="white") frameTheta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputThetaLow = Entry(frameTheta, width=8) self.inputThetaLow.pack(side=LEFT, padx=5, pady=5) self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "0") self.inputThetaHigh = Entry(frameTheta, width=8) self.inputThetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "0") # BETA FRAME frameBeta = LabelFrame(frameFilters, text="Beta", relief=RAISED, borderwidth=1, background="white") frameBeta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputBetaLow = Entry(frameBeta, width=8) self.inputBetaLow.pack(side=LEFT, padx=5, pady=5) self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "0") self.inputBetaHigh = Entry(frameBeta, width=8) self.inputBetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, "0") # SMR FRAME frameSMR = LabelFrame(frameFilters, text="SMR", relief=RAISED, borderwidth=1, background="white") frameSMR.pack(expand=1, side=TOP, pady=5, padx=5) self.inputSMRLow = Entry(frameSMR, width=8) self.inputSMRLow.pack(side=LEFT, padx=5, pady=5) self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "0") self.inputSMRHigh = Entry(frameSMR, width=8) self.inputSMRHigh.pack(side=LEFT, padx=5, pady=5) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "0") frameButtons = LabelFrame(frameConfig, text="Commands", relief=RAISED, borderwidth=1, background="white") frameButtons.pack(expand=1, side=BOTTOM) self.buttonWriteConfig = Button(frameButtons, text="Write Filters", command=self.writeFilters) self.buttonWriteConfig.pack(side=LEFT, padx=5, pady=5) self.buttonWriteDefault = Button(frameButtons, text="Reset to Defaults", command=self.resetIAFtoDefault) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) # self.buttonVisualize = Button(frameButtons, text="VIS",command=self.resetIAFtoDefault) # self.buttonVisualize.pack(side=LEFT,padx=5,pady=5) self.buttonPrintFig = Button(frameButtons, text="Print Figure", command=self.printFigureToFile) self.buttonPrintFig.pack(side=LEFT, padx=5, pady=5)
class ToolsWindow(Toplevel): """ Other main portion of the program, the tools window is in charge of managing all tool and manipulation related buttons , and is created bound to root but is technically a standalone window. :param parent: the class that has this instance of ToolsWindow :param root: the root of the program """ def __init__(self, canvas, parent, root): Toplevel.__init__(self, root) # Images required by buttons self.edit_img = ImageTk.PhotoImage(file=PATH + '/ico/edit.png') self.prop_img = ImageTk.PhotoImage(file=PATH + '/ico/cog.png') self.plot_img = ImageTk.PhotoImage(file=PATH + '/ico/hide.png') self.outline_img = ImageTk.PhotoImage(file=PATH + '/ico/focus.png') self.paint_img = ImageTk.PhotoImage(file=PATH + '/ico/paint.png') self.erase_img = ImageTk.PhotoImage(file=PATH + '/ico/eraser.png') self.drag_img = ImageTk.PhotoImage(file=PATH + '/ico/cursorhand.png') self.plot_cursor_img = ImageTk.PhotoImage(file=PATH + '/ico/plotcursor.png') self.free_draw_img = ImageTk.PhotoImage(file=PATH + '/ico/freedraw.png') self.polygon_img = ImageTk.PhotoImage(file=PATH + '/ico/polygon.png') self.redo_img = ImageTk.PhotoImage(file=PATH + '/ico/forward.png') self.undo_img = ImageTk.PhotoImage(file=PATH + '/ico/back.png') self.magnify_draw_img = ImageTk.PhotoImage(file=PATH + '/ico/magnify.png') self.extract_img = ImageTk.PhotoImage(file=PATH + '/ico/extract.png') self.home_img = ImageTk.PhotoImage(file=PATH + '/ico/home.png') self.select_cursor = ImageTk.PhotoImage(file=PATH + '/ico/cursorhighlight.png') self.__parent = parent self.__root = root self.__canvas = canvas self.plot_type = IntVar() self.width = parent.width self.height = parent.height self.title('Tools') self.resizable(width=FALSE, height=FALSE) self.protocol('WM_DELETE_WINDOW', ToolsWindow.ignore) self.container = Frame(self) self.container.pack(side=TOP, fill=BOTH, expand=True) self.coordinate_frame = Frame(self.container, width=50, height=50) self.coordinate_frame.config(highlightthickness=1) self.coordinate_frame.config(highlightbackground='grey') self.coordinate_frame.pack(side=BOTTOM, fill=BOTH, expand=False) self.upper_button_frame = None self.upper_range_frame = None self.lower_button_frame = None self.begin_range_entry = None self.begin_alt_range_entry = None self.end_range_entry = None self.end_alt_range_entry = None @staticmethod def ignore(): """ Do nothing when the user presses the close button """ pass def setup_toolbar_buttons(self): """ Create tool bar buttons """ logger.info('Setting up toolbar') self.upper_button_frame = Frame(self.container) self.upper_button_frame.pack(side=TOP, fill=X) # Reset and render button reset_button = Button(self.upper_button_frame, text='Reset', width=12, command=self.__parent.reset) reset_button.grid(row=0, column=0, pady=2) create_tool_tip(reset_button, 'Reset the field of view and clear polygons') render_button = Button(self.upper_button_frame, text='Render', width=12, height=4, command=self.render) render_button.grid(row=0, column=1, rowspan=4, sticky='e') create_tool_tip(render_button, 'Render the loaded file\nto the screen') self.upper_range_frame = Frame(self.container) self.upper_range_frame.pack(side=TOP, fill=X) Label(self.upper_range_frame, text='Profiles').\ grid(row=3, column=0, pady=5, sticky='w') self.begin_range_entry = Entry(self.upper_range_frame, width=12) self.begin_range_entry.grid(row=3, column=1, pady=5, sticky='w') self.begin_range_entry.insert(END, '0') Label(self.upper_range_frame, text='to').\ grid(row=3, column=2, pady=5, sticky='w') self.end_range_entry = Entry(self.upper_range_frame, width=11) self.end_range_entry.grid(row=3, column=3, pady=5, sticky='w') self.end_range_entry.insert(END, '5000') Label(self.upper_range_frame, text='Alt').\ grid(row=4, column=0, pady=5, sticky='w') self.begin_alt_range_entry = Entry(self.upper_range_frame, width=12) self.begin_alt_range_entry.grid(row=4, column=1, pady=5, sticky='w') self.begin_alt_range_entry.insert(END, '0') Label(self.upper_range_frame, text='to').\ grid(row=4, column=2, pady=5, sticky='w') self.end_alt_range_entry = Entry(self.upper_range_frame, width=11) self.end_alt_range_entry.grid(row=4, column=3, pady=5, sticky='w') self.end_alt_range_entry.insert(END, '20') self.lower_button_frame = Frame(self.container) self.lower_button_frame.config(highlightthickness=1) self.lower_button_frame.config(highlightbackground='grey') self.lower_button_frame.pack(side=BOTTOM) Label(self.lower_button_frame, width=1).grid(row=0, column=0) Label(self.lower_button_frame, width=1).grid(row=0, column=5) # Pan plot left and right plot_cursor_button = \ ToggleableButton(self.__root, self.lower_button_frame, image=self.plot_cursor_img, width=30, height=30) plot_cursor_button.latch(target=self.__canvas, key='button_press_event', command=self.__parent.pan) plot_cursor_button.latch(target=self.__canvas, key='button_release_event', command=self.__parent.render_pan) plot_cursor_button.latch(cursor='hand1') plot_cursor_button.grid(row=0, column=1, padx=2, pady=5) create_tool_tip(plot_cursor_button, 'Move about plot') # Magnify icon logger.info('Creating toolbar buttons') zoom_button = ToolbarToggleableButton( self.__root, self.lower_button_frame, lambda: self.__parent.get_toolbar().zoom(True), image=self.magnify_draw_img, width=30, height=30) zoom_button.latch(cursor='tcross') zoom_button.grid(row=0, column=2, padx=2, pady=5) create_tool_tip(zoom_button, 'Zoom to rect') # Plot undo icon undo_button = Button( self.lower_button_frame, image=self.undo_img, width=30, height=30, command=lambda: self.__parent.get_toolbar().back(True)) undo_button.grid(row=0, column=3, padx=2, pady=5) create_tool_tip(undo_button, 'Previous View') # Plot redo icon redo_button = Button( self.lower_button_frame, image=self.redo_img, width=30, height=30, command=lambda: self.__parent.get_toolbar().forward(True)) redo_button.grid(row=0, column=4, padx=2, pady=5) create_tool_tip(redo_button, 'Next View') # Home button home_button = Button( self.lower_button_frame, image=self.home_img, command=lambda: self.__parent.get_toolbar().home(), width=30, height=30) home_button.grid(row=1, column=1, padx=2, pady=5) create_tool_tip(home_button, 'Home') # Retrieve shape properties.rst properties_button = \ ToggleableButton(self.__root, self.lower_button_frame, image=self.prop_img, width=30, height=30) properties_button.latch( target=self.__canvas, key='pick_event', command=self.__parent.get_shapemanager().properties) properties_button.grid(row=1, column=2, padx=2, pady=5) create_tool_tip(properties_button, 'Polygon Properties') # Edit shape attributes edit_button = ToggleableButton(self.__root, self.lower_button_frame, image=self.edit_img, width=30, height=30) edit_button.latch(target=self.__canvas, key='pick_event', command=self.__parent.attribute_dialog) edit_button.grid(row=1, column=3, padx=2, pady=5) create_tool_tip(edit_button, 'Edit Attributes') # Extract data extract_button = ToggleableButton(self.__root, self.lower_button_frame, image=self.extract_img, width=30, height=30) extract_button.latch(target=self.__canvas, key='pick_event', command=self.__parent.extract_dialog) extract_button.grid(row=1, column=4, padx=2, pady=5) create_tool_tip(extract_button, 'Extract data from shape') # Draw rectangle shape polygon_button = \ ToggleableButton(self.__root, self.lower_button_frame, image=self.polygon_img, width=30, height=30) polygon_button.latch( target=self.__canvas, key='button_press_event', command=self.__parent.get_shapemanager().anchor_rectangle, cursor='tcross') logger.info('Button pressed - ploygon') polygon_button.latch( target=self.__canvas, key='motion_notify_event', command=self.__parent.get_shapemanager().rubberband) polygon_button.latch( target=self.__canvas, key='button_release_event', command=self.__parent.get_shapemanager().fill_rectangle, cursor='tcross') polygon_button.grid(row=2, column=1, padx=2, pady=5) create_tool_tip(polygon_button, 'Draw Rect') # Free form shape creation free_draw_button = \ ToggleableButton(self.__root, self.lower_button_frame, image=self.free_draw_img, width=30, height=30) free_draw_button.latch( target=self.__canvas, key='button_press_event', command=self.__parent.get_shapemanager().plot_point, cursor='tcross', destructor=self.__parent.get_shapemanager().clear_lines) free_draw_button.latch( target=self.__canvas, key='motion_notify_event', command=self.__parent.get_shapemanager().sketch_line, cursor='tcross', destructor=self.__parent.get_shapemanager().clear_lines) free_draw_button.grid(row=2, column=2, padx=2, pady=5) create_tool_tip(free_draw_button, 'Free Draw') # Erase polygon drawings erase_button = ToggleableButton(self.__root, self.lower_button_frame, image=self.erase_img, width=30, height=30) erase_button.latch(target=self.__canvas, key='pick_event', command=self.__parent.get_shapemanager().delete, cursor='X_cursor') erase_button.grid(row=2, column=3, padx=2, pady=5) create_tool_tip(erase_button, 'Erase polygon') # Recolor shapes paint_button = ToggleableButton(self.__root, self.lower_button_frame, image=self.paint_img, width=30, height=30) paint_button.latch(target=self.__canvas, key='pick_event', command=self.__parent.paint, cursor='') paint_button.grid(row=2, column=4, padx=2, pady=5) create_tool_tip(paint_button, 'Paint') # Outline shapes outline_button = \ Button(self.lower_button_frame, image=self.outline_img, width=30, height=30, command=lambda: self.__parent.get_shapemanager().outline()) outline_button.grid(row=3, column=1, padx=2, pady=5) create_tool_tip(outline_button, 'Focus') # Hide shapes plot_button = \ Button(self.lower_button_frame, image=self.plot_img, width=30, height=30, command=lambda: self.__parent.get_shapemanager().hide()) plot_button.grid(row=3, column=2, padx=2, pady=5) create_tool_tip(plot_button, 'Hide polygons') select_button = \ ToggleableButton(self.__root, self.lower_button_frame, image=self.select_cursor, width=30, height=30) select_button.latch( target=self.__canvas, key='pick_event', command=self.__parent.get_shapemanager().select_from_event, cursor='') select_button.grid(row=3, column=3, padx=2, pady=5) create_tool_tip(select_button, 'Select shapes for action') @staticmethod def __check_range(beginning_range, ending_range, min_range, begin_range_entry, end_range_entry): # If entry has text if begin_range_entry.get(): # If entry is not ONLY numbers if not re.match( '[0-9]+', begin_range_entry.get()) or '.' in begin_range_entry.get(): logger.error('Beginning range invalid, not all numeric') tkMessageBox.showerror( 'toolswindow', 'Invalid beginning range, range must only contain digits') return None """ if float(begin_range_entry.get()) % 5 != 0: tkMessageBox.showerror('toolswindow', 'Invalid beginning range, must be multiple of 5') return None """ # Force range to multiple of 5 # Not sure why it's necessary though - CPampalone beginning_range = int(5 * round(int(begin_range_entry.get()) / 5)) # If entry has text if end_range_entry.get(): # If entry is not ONLY numbers if not re.match( '[0-9]+', end_range_entry.get()) or '.' in end_range_entry.get(): logger.error('Ending range invalid, not all numeric') tkMessageBox.showerror( 'toolswindow', 'Invalid ending range, range must only contain digits') return None """ if float(end_range_entry.get()) % 5 != 0: logger.error('Ending range invalid, must be multiple of 5') tkMessageBox.showerror('toolswindow', 'Ending range invalid, must be multiple of 5') return None ending_range = int(end_range_entry.get()) """ # Force range to multiple of 5 # Not sure why it's necessary though - CPampalone ending_range = int(5 * round(int(end_range_entry.get()) / 5)) if beginning_range > ending_range: logger.error('Beginning range larger than ending range %d > %d' % (beginning_range, ending_range)) tkMessageBox.showerror( 'toolswindow', 'Beginning range cannot be larger than ending range') return None # If any negative values or the step is too small if beginning_range < 0 or ending_range < 0 or ending_range - beginning_range < min_range: logger.error('Error, invalid range specifiers %d , %d' % (beginning_range, ending_range)) tkMessageBox.showerror( 'toolswindow', 'Range cannot be less than zero or smaller than 100 steps') return None if ending_range - beginning_range > 15000: logger.error('Error, specified range %d , %d is too large' % (beginning_range, ending_range)) tkMessageBox.showerror('toolswindow', 'Range cannot be greater than 15000 steps') return None return beginning_range, ending_range def rebind_tools_to_canvas(self, new_canvas): logger.debug('Changing from ' + str(self.__canvas) + ' to ' + str(new_canvas)) self.__canvas = new_canvas self.setup_toolbar_buttons() def render(self): """ Errors checks all user entered parameters and calls ``set_plot`` from *Calipso* """ ''' if self.plot_type.get() == 0: logger.error('No plot type set') tkMessageBox.showerror('toolswindow', 'No plot type specified') return ''' if not self.__parent.get_file(): logger.error('No file entered') tkMessageBox.showerror('toolswindow', 'No file loaded') return time_range = ToolsWindow.__check_range(0, 1000, 5, self.begin_range_entry, self.end_range_entry) alt_range = ToolsWindow.__check_range(0, 20, 5, self.begin_alt_range_entry, self.end_alt_range_entry) logger.info('Grabbing range and safe checking') if time_range is None or alt_range is None: return logger.info('Calling plot') self.__parent.set_plot(self.__parent.plot_type.get(), xrange_=time_range, yrange=alt_range)
class App: ### (1) def __init__(self, myParent): ### (1a) self.status = Tk.StringVar() self.status.set('Avaiting indicators from game session') self.statuswidg = Tk.Label(myParent, textvariable=self.status, fg=FG, bg=BG, font=labelfonts) try: if settings['STATUSBAR']==1: self.statuswidg.pack() except: pass self.frame = Frame(myParent) self.frame.pack() self.statusbar = Frame(myParent) self.statusbar.pack() self.frame.config(bg=BGG) self.ind = get_indicators() self.inds = {} self.t_m=time.time() self.frame.after(int(dt*1000), self.upd) def inds_to_disp(self, master): ind_d = {} for instr in NEEDED_INSTRUMENTS: if DRAW_ALL: ind_d[instr] = self.get_instr(instr, master) else: for available in self.ind.keys(): if instr in available: ind_d[available] = self.get_instr(available, master) try: if settings[instr+'_bind'] == available: ind_d[instr] = self.get_instr(instr, master, label=True) except: pass return ind_d def upd(self): d = get_indicators() ## print len(d), 'en d' try: ## print d['valid'], 'valid' if 'vario' not in d and len(d)>1: d['vario'] = (d['altitude_hour']-self.ind['altitude_hour'])/(time.time()-self.t_m) self.t_m=time.time() except Exception: try: if len(d)>1: d['vario'] = '--' except: pass self.ind = d if len(d) == 0: for child in self.frame.winfo_children(): child.destroy() self.inds={} self.ind ={} self.status.set('No response from game at: '+"HTTP://"+ADDRESS+":8111/indicators") elif d['valid'] and len(self.inds)>0: self.status.set('In game at: '+"HTTP://"+ADDRESS+":8111/indicators") for ind in self.inds.values(): try: ind.update(d[ind.name]) except: ind.update('--') elif d['valid']==False and len(self.inds)>0: for child in self.frame.winfo_children(): child.destroy() self.inds={} self.ind ={} elif d['valid']==True and len(self.inds)<1: ds = self.inds_to_disp(self.frame) self.inds = ds if len(d) != 0 and d['valid']==False: if len(self.frame.winfo_children())<1: self.status.set('Avaiting indicators from game session') self.frame.after(int(dt*1000), self.upd) def get_instr(self, instr, master, label=False): if 'water_temperature' in instr: return WaterTempInd(master, instr) elif label==True: return GenericLabel(master, instr) elif 'oil_temperature' in instr: return OilTempInd(master, instr) elif 'ammo' in instr: return AmmoInd(master, instr) elif 'vario' in instr: return VarioInd(master, instr) elif 'head_temperature' in instr: return HeadTempInd(master, instr) elif "flaps, %" == instr: return FlapsInd(master, instr) elif "gear, %" in instr: return GearInd(master, instr) elif "airbrake, %" in instr: ## print 'airbrake in instr' return AirbrakeInd(master, instr) else: return GenericInd(master, instr)
class view(Tk): def mkStringVar(self, s): R = StringVar() R.set(s) return R def mkLabel(self, f, T, r, c, rs=1, cs=1): if isinstance(T, type(StringVar())): R = Label(f, textvariable = T, relief=GROOVE, borderwidth=2) else: R = Label(f, text = T, relief=GROOVE, borderwidth=2) R.grid(row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens") return R def mkLabelList(self, f, SV, r): R = [] for i in range(len(SV)): R.append(self.mkLabel(f, SV[i], r, i+1)) return R def mkButton(self, f, t, r, c, rs=1, cs=1): R = Button(f, text=t) R.grid( row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens") return R # ===== HALT et cetera ========================================================= def mkHaltArea(self, f): self.HALTframe = Frame(f) self.HALTframe.config(relief=GROOVE) self.HALTframe.config(borderwidth=2) self.HALTbutton = Button(self.HALTframe, text = "HALT", width=10) self.READMEbutton = Button(self.HALTframe, text = "README", width=10) self.HALTbutton.config(borderwidth=2, relief=GROOVE, fg="red") self.HALTbutton.config(command = self.quit) self.READMEbutton.config(borderwidth=2, relief=GROOVE, fg="red") self.HALTbutton.pack(side=LEFT, fill=BOTH) self.READMEbutton.pack(side=RIGHT, fill=BOTH) self.HALTframe.grid(row=0, column=9, rowspan=1, columnspan=4, sticky="wens") # ============================================================================== def mkProgramControl(self, f): self.PROGRAMCONTROLframe = Frame(f) self.PROGRAMCONTROLframe.config(relief=GROOVE) self.PROGRAMCONTROLframe.config(borderwidth=2) self.runButton = Button(self.PROGRAMCONTROLframe, text="RUN", width=10) self.runButton.grid(row=0, column=0, sticky="wens", padx=29, pady=7) self.stepButton = Button(self.PROGRAMCONTROLframe, text="STEP", width=10) self.stepButton.grid(row=1, column=0, sticky="wens", padx=29, pady=5) self.noStepButton = Button(self.PROGRAMCONTROLframe, text="NOSTEP", width=10) self.noStepButton.grid(row=2, column=0, sticky="wens", padx=29, pady=7) self.PROGRAMCONTROLframe.grid(row=17, column=11, rowspan=6, columnspan=2, sticky="wens") # ============================================================================== def getPGMfileName(self): options = {'filetypes': [('pgm files', '.pgm')]} f = askopenfilename(**options) g = f.split('/') self.filenameVar.set(g[len(g) - 1]) return f def mkProgramLoad(self, f): self.PROGRAMLOADframe = Frame(f) self.PROGRAMLOADframe.config(relief=GROOVE) self.PROGRAMLOADframe.config(borderwidth=2) self.loadPGMbutton = Button(self.PROGRAMLOADframe, text="Load PGM") self.loadPGMbutton.config(width=14) self.loadPGMbutton.pack(side=LEFT, fill=BOTH, padx=20, pady=5) self.filenameVar = StringVar() self.filenameVar.set("*****.pgm") self.fileNameLabel = Label(self.PROGRAMLOADframe, textvariable=self.filenameVar) self.fileNameLabel.config(relief=GROOVE, borderwidth=2, width=17) self.fileNameLabel.pack(side=RIGHT, fill=BOTH, padx=20, pady=5) self.PROGRAMLOADframe.grid(row=15, column=9, rowspan=2, columnspan=4, sticky="wens") # ============================================================================== def mkMemory(self, f): self.MEMORYframe = Frame(f) self.MEMORYframe.config(relief=GROOVE) self.MEMORYframe.config(borderwidth=2) E = Frame(self.MEMORYframe) self.CLEAR = self.mkButton(E, "ClearMem", 0, 0) self.RANDOM = self.mkButton(E, "RandomMem", 0, 1) self.READ = self.mkButton(E, "ReadMem", 1, 0) self.WRITE = self.mkButton(E, "WriteMem", 1, 1) self.BUSTOMEM = self.mkButton(E, "BusToMem", 2, 0, 1, 2) F = Frame(self.MEMORYframe) for i in Range8: L = Label(F, textvariable=self.MEMORY[i]) L.config(relief=GROOVE, borderwidth=2, bg="black", fg="yellow", height=1) L.grid(row=0, column=i, sticky="wens", ipadx=5) E.pack(side=TOP) F.pack(side=BOTTOM) self.MEMORYframe.grid(row=18, column=9, rowspan=5, columnspan=2, sticky="wens") # ============================================================================== def mkDataBus(self, f): self.DBframe = Frame(f) self.DBframe.config(relief=GROOVE) self.DBframe.config(borderwidth=2, bg="red") self.DBframe.grid(row=0, column=0, rowspan=1, \ columnspan=9, sticky="wens") self.databusLabel = Label(self.DBframe, text="Data\nBus", width=10) self.databusLabel.pack(side=LEFT) self.DATABUSbuttons = [] for i in Range8: b = Button(self.DBframe, textvariable=self.DATABUS[i]) b.pack(side=LEFT, fill=BOTH) self.DATABUSbuttons.append(b) def mkAddressBus(self, f): self.ABframe = Frame(f) self.ABframe.config(relief=GROOVE) self.ABframe.config(borderwidth=2, bg="red") self.ABframe.grid(row=26, column=0, rowspan=1, columnspan=13, sticky="wens") self.AddressBusLabel = Label(self.ABframe, text="Address\nBus", width=12) self.AddressBusLabel.pack(side=LEFT) self.ADDRESSBUSbuttons = [] for i in Range16: b = Button(self.ABframe, textvariable=self.ADDRESSBUS[i]) b.pack(side=LEFT, fill=BOTH, ipadx=2) self.ADDRESSBUSbuttons.append(b) # ============================================================================== def mkALU(self, f): self.ALUframe = Frame(f) self.ALUframe.config(relief=GROOVE) self.ALUframe.config(borderwidth=2) self.mkFunctionChoice(self.ALUframe) self.mkStates(self.ALUframe) self.ALUframe.grid(row=23, column=9, rowspan=3, columnspan=4, sticky="wens") def mkFunctionChoice(self, f): self.FUNCTIONframe = Frame(f) self.FUNCTIONframe.config(relief=GROOVE) self.FUNCTIONframe.config(borderwidth=2) self.F0label = Label(self.FUNCTIONframe, text="F0", borderwidth=2, relief=GROOVE) self.F0label.grid(row=0, column=0, sticky="wens", padx=5) self.F1label = Label(self.FUNCTIONframe, text="F1", borderwidth=2, relief=GROOVE) self.F1label.grid(row=0, column=1, sticky="wens", padx=8) self.F2label = Label(self.FUNCTIONframe, text="F2", borderwidth=2, relief=GROOVE) self.F2label.grid(row=0, column=2, sticky="wens", padx=5) self.FUNCTIONbuttons = [] self.F0button = Button(self.FUNCTIONframe) self.F0button.config(textvariable=self.FUNCTION[0], borderwidth=2, relief=GROOVE) self.F1button = Button(self.FUNCTIONframe) self.F1button.config(textvariable=self.FUNCTION[1], borderwidth=2, relief=GROOVE) self.F2button = Button(self.FUNCTIONframe) self.F2button.config(textvariable=self.FUNCTION[2], borderwidth=2, relief=GROOVE) self.FUNCTIONbuttons.append(self.F0button) self.FUNCTIONbuttons.append(self.F1button) self.FUNCTIONbuttons.append(self.F2button) for i in Range3: self.FUNCTIONbuttons[i].grid(row=1, column=i, sticky="wens", padx=5) self.FUNCTIONframe.pack(side=LEFT, padx=8, pady=3) def mkStates(self, f): self.STATESframe = Frame(f) self.STATESframe.config(relief=GROOVE) self.STATESframe.config(borderwidth=2) self.CARRYtag = Label(self.STATESframe, text = " carry ", borderwidth=2, relief=GROOVE) self.CARRYtag.grid(row=0, column=0, padx=5, pady=2, sticky="wens") self.ZEROtag = Label(self.STATESframe, text = " zero ", borderwidth=2, relief=GROOVE) self.ZEROtag.grid(row=0, column=1, padx=5, pady=1, sticky="wens") self.SIGNtag = Label(self.STATESframe, text = " sign ", borderwidth=2, relief=GROOVE) self.SIGNtag.grid(row=0, column=2, padx=5, pady=2, sticky="wens") self.CARRY = self.mkStringVar("0") self.ZERO = self.mkStringVar("0") self.SIGN = self.mkStringVar("0") self.CARRYlabel = Label(self.STATESframe, textvariable = self.CARRY, borderwidth=2, relief=GROOVE) self.CARRYlabel.grid(row=1, column=0, padx=5, pady=2, sticky="wens") self.ZEROlabel = Label(self.STATESframe, textvariable = self.ZERO, borderwidth=2, relief=GROOVE) self.ZEROlabel.grid(row=1, column=1, padx=5, pady=1, sticky="wens") self.SIGNlabel = Label(self.STATESframe, textvariable = self.SIGN, borderwidth=2, relief=GROOVE) self.SIGNlabel.grid(row=1, column=2, padx=5, pady=2, sticky="wens") self.STATESframe.pack(side=RIGHT, padx=8, pady=3) # ============================================================================== def mkTagLabels(self, f): self.ALabel = self.mkLabel(f, "A", 1, 0) self.BLabel = self.mkLabel(f, "B", 2, 0) self.BLabel.config(bg="black", fg="yellow") self.CLabel = self.mkLabel(f, "C", 3, 0) self.CLabel.config(bg="black", fg="yellow") self.DLabel = self.mkLabel(f, "D", 4, 0) self.M1Label = self.mkLabel(f, "M1", 5, 0) self.M2Label = self.mkLabel(f, "M2", 6, 0) self.XLabel = self.mkLabel(f, "X", 7, 0) self.YLabel = self.mkLabel(f, "Y", 8, 0) self.J1Label = self.mkLabel(f, "J1", 9, 0) self.J2Label = self.mkLabel(f, "J2", 10, 0) self.PC1Label = self.mkLabel(f, "PC1", 11, 0) self.PC2Label = self.mkLabel(f, "PC2", 12, 0) self.Inc1Label = self.mkLabel(f, "Inc1", 13, 0) self.Inc2Label = self.mkLabel(f, "Inc2", 14, 0) self.IncUnit1Label = self.mkLabel(f, "IncUnit1", 15, 0) self.IncUnit2Label = self.mkLabel(f, "IncUnit2", 16, 0) self.InstLabel = self.mkLabel(f, "Inst", 17, 0) self.addLabel = self.mkLabel(f, "ADD", 18, 0) self.incLabel = self.mkLabel(f, "INC", 19, 0) self.andLabel = self.mkLabel(f, "AND", 20, 0) self.orLabel = self.mkLabel(f, "OR", 21, 0) self.xorLabel = self.mkLabel(f, "XOR", 22, 0) self.notLabel = self.mkLabel(f, "NOT", 23, 0) self.shlLabel = self.mkLabel(f, "SHL", 24, 0) self.clrLabel = self.mkLabel(f, "CLR", 25, 0) self.functionTagLabelDictionary = { (0,0,0) : self.addLabel, \ (0,0,1) : self.incLabel, \ (0,1,0) : self.andLabel, \ (0,1,1) : self.orLabel, \ (1,0,0) : self.xorLabel, \ (1,0,1) : self.notLabel, \ (1,1,0) : self.shlLabel, \ (1,1,1) : self.clrLabel \ } for i in self.functionTagLabelDictionary.values(): i.config(bg="black", fg="yellow") # ============================================================================== def mkRegisterStringVars(self): self.FUNCTION = [ self.mkStringVar("0") for unused_i in Range3 ] self.DATABUS = [ self.mkStringVar("0") for unused_i in Range8 ] self.Inst = [ self.mkStringVar("0") for unused_i in Range8 ] self.A = [ self.mkStringVar("0") for unused_i in Range8 ] self.B = [ self.mkStringVar("0") for unused_i in Range8 ] self.C = [ self.mkStringVar("0") for unused_i in Range8 ] self.D = [ self.mkStringVar("0") for unused_i in Range8 ] self.M1 = [ self.mkStringVar("0") for unused_i in Range8 ] self.M2 = [ self.mkStringVar("0") for unused_i in Range8 ] self.X = [ self.mkStringVar("0") for unused_i in Range8 ] self.Y = [ self.mkStringVar("0") for unused_i in Range8 ] self.J1 = [ self.mkStringVar("0") for unused_i in Range8 ] self.J2 = [ self.mkStringVar("0") for unused_i in Range8 ] self.PC1 = [ self.mkStringVar("0") for unused_i in Range8 ] self.PC2 = [ self.mkStringVar("0") for unused_i in Range8 ] self.Inc1 = [ self.mkStringVar("0") for unused_i in Range8 ] self.Inc2 = [ self.mkStringVar("0") for unused_i in Range8 ] self.IncUnit1 = [ self.mkStringVar("0") for unused_i in Range8 ] self.IncUnit2 = [ self.mkStringVar("0") for unused_i in Range8 ] self.Add = [ self.mkStringVar("0") for unused_i in Range8 ] self.Inc = [ self.mkStringVar("0") for unused_i in Range8 ] self.And = [ self.mkStringVar("0") for unused_i in Range8 ] self.Or = [ self.mkStringVar("0") for unused_i in Range8 ] self.Xor = [ self.mkStringVar("0") for unused_i in Range8 ] self.Not = [ self.mkStringVar("0") for unused_i in Range8 ] self.Shl = [ self.mkStringVar("0") for unused_i in Range8 ] self.Clr = [ self.mkStringVar("0") for unused_i in Range8 ] self.ADDRESSBUS = [ self.mkStringVar("0") for unused_i in Range16 ] self.MEMORY = [ self.mkStringVar("0") for unused_i in Range8 ] # ============================================================================== def setRegisterLabelColor(self, L, bc, fc="black"): for i in L: i.config(bg=bc, fg=fc) def mkRegisterLabels(self, f): self.Alabels = self.mkLabelList(f, self.A, 1) self.setRegisterLabelColor(self.Alabels, "gray90") self.Blabels = self.mkLabelList(f, self.B, 2) self.setRegisterLabelColor(self.Blabels, "black", "yellow") self.Clabels = self.mkLabelList(f, self.C, 3) self.setRegisterLabelColor(self.Clabels, "black", "yellow") self.Dlabels = self.mkLabelList(f, self.D, 4) self.setRegisterLabelColor(self.Dlabels, "gray90") self.M1labels = self.mkLabelList(f, self.M1, 5) self.setRegisterLabelColor(self.M1labels, "gray90") self.M2labels = self.mkLabelList(f, self.M2, 6) self.setRegisterLabelColor(self.M2labels, "gray90") self.Xlabels = self.mkLabelList(f, self.X, 7) self.setRegisterLabelColor(self.Xlabels, "gray90") self.Ylabels = self.mkLabelList(f, self.Y, 8) self.setRegisterLabelColor(self.Ylabels, "gray90") self.J1labels = self.mkLabelList(f, self.J1, 9) self.J2labels = self.mkLabelList(f, self.J2, 10) self.PC1labels = self.mkLabelList(f, self.PC1, 11) self.PC2labels = self.mkLabelList(f, self.PC2, 12) self.Inc1labels = self.mkLabelList(f, self.Inc1, 13) self.setRegisterLabelColor(self.Inc1labels, "gray95") self.Inc2labels = self.mkLabelList(f, self.Inc2, 14) self.setRegisterLabelColor(self.Inc2labels, "gray95") self.IncUnit1labels = self.mkLabelList(f, self.IncUnit1, 15) self.setRegisterLabelColor(self.IncUnit1labels, "gray95") self.IncUnit2labels = self.mkLabelList(f, self.IncUnit2, 16) self.setRegisterLabelColor(self.IncUnit2labels, "gray95") self.Instlabels = self.mkLabelList(f, self.Inst, 17) self.addlabels = self.mkLabelList(f, self.Add, 18) self.setRegisterLabelColor(self.addlabels, "black", "red") self.inclabels = self.mkLabelList(f, self.Inc, 19) self.setRegisterLabelColor(self.inclabels, "black", "yellow") self.andlabels = self.mkLabelList(f, self.And, 20) self.setRegisterLabelColor(self.andlabels, "black", "yellow") self.orlabels = self.mkLabelList(f, self.Or, 21) self.setRegisterLabelColor(self.orlabels, "black", "yellow") self.xorlabels = self.mkLabelList(f, self.Xor, 22) self.setRegisterLabelColor(self.xorlabels, "black", "yellow") self.notlabels = self.mkLabelList(f, self.Not, 23) self.setRegisterLabelColor(self.notlabels, "black", "yellow") self.shllabels = self.mkLabelList(f, self.Shl, 24) self.setRegisterLabelColor(self.shllabels, "black", "yellow") self.clrlabels = self.mkLabelList(f, self.Clr, 25) self.setRegisterLabelColor(self.clrlabels, "black", "yellow") self.functionLabelsDictionary = { (0,0,0) : self.addlabels, \ (0,0,1) : self.inclabels, \ (0,1,0) : self.andlabels, \ (0,1,1) : self.orlabels, \ (1,0,0) : self.xorlabels, \ (1,0,1) : self.notlabels, \ (1,1,0) : self.shllabels, \ (1,1,1) : self.clrlabels \ } # ===== Load & Select ========================================================== def mkLoad8Buttons(self, f): self.loadA = self.mkButton(f, "load A", 1, 9, 1, 2) self.loadB = self.mkButton(f, "load B", 2, 9, 1, 2) self.loadC = self.mkButton(f, "load C", 3, 9, 1, 2) self.loadD = self.mkButton(f, "load D", 4, 9, 1, 2) self.loadM1 = self.mkButton(f, "load M1", 5, 9, 1, 2) self.loadM2 = self.mkButton(f, "load M2", 6, 9, 1, 2) self.loadX = self.mkButton(f, "load X", 7, 9) self.loadY = self.mkButton(f, "load Y", 8, 9) self.loadJ1 = self.mkButton(f, "load J1", 9, 9, 1, 2) self.loadJ2 = self.mkButton(f, "load J2", 10, 9, 1, 2) self.loadInst = self.mkButton(f, "load Inst", 17, 9, 1, 2) def mkLoad16Buttons(self, f): self.loadXY = self.mkButton(f, "load XY", 7, 10, 2, 1) self.loadPC = self.mkButton(f, "load PC", 11, 9, 2, 2) self.loadINC = self.mkButton(f, "load INC", 13, 9, 2, 2) def mkSelect8Buttons(self, f): self.selectA = self.mkButton(f, "select A", 1, 11, 1, 2) self.selectB = self.mkButton(f, "select B", 2, 11, 1, 2) self.selectC = self.mkButton(f, "select C", 3, 11, 1, 2) self.selectD = self.mkButton(f, "select D", 4, 11, 1, 2) self.selectM1 = self.mkButton(f, "select M1", 5, 11) self.selectM2 = self.mkButton(f, "select M2", 6, 11) self.selectX = self.mkButton(f, "select X", 7, 11) self.selectY = self.mkButton(f, "select Y", 8, 11) def mkSelect16Buttons(self, f): self.selectM = self.mkButton(f, "select M", 5, 12, 2, 1) self.selectXY = self.mkButton(f, "select XY", 7, 12, 2, 1) self.selectJ = self.mkButton(f, "select J", 9, 11, 2, 2) self.selectPC = self.mkButton(f, "select PC", 11, 11, 2, 2) self.selectINC = self.mkButton(f, "select INC", 13, 11, 2, 2) # ===== System Messages ======================================================== def mkMessageArea(self, f): self.text = Text(f, height=36, width=64) self.text.configure(font=("Courier", 11, "bold"), bg="black", fg="green") self.scroll = Scrollbar(f, command = self.text.yview) self.text.configure(yscrollcommand = self.scroll.set) self.text.pack(side=LEFT, padx=3, pady=2) self.scroll.pack(side=RIGHT, fill=Y, padx=3, pady=2) def addText(self, text): self.text.insert(END, text + "\n") self.text.yview(END) # ===== Initialization ========================================================= def __init__(self): Tk.__init__(self) self.title("Virtual Machine") self.config(bg="blue") self.registers = LabelFrame(self, bg="blue") self.registers.config(relief=GROOVE) self.registers.config(borderwidth=2) self.registers.config(text = "Virtual Machine: controls and states") self.registers.config(labelanchor = "nw") self.registers.pack(side = LEFT, fill=BOTH) self.mkRegisterStringVars() self.mkTagLabels(self.registers) self.mkDataBus(self.registers) self.mkRegisterLabels(self.registers) self.mkLoad8Buttons(self.registers) self.mkLoad16Buttons(self.registers) self.mkSelect8Buttons(self.registers) self.mkSelect16Buttons(self.registers) self.mkAddressBus(self.registers) self.mkALU(self.registers) self.mkMemory(self.registers) self.mkProgramLoad(self.registers) self.mkProgramControl(self.registers) self.mkHaltArea(self.registers) self.messages = LabelFrame(self, bg="blue") self.messages.config(relief=GROOVE) self.messages.config(borderwidth=2) self.messages.config(text = "Virtual Machine: system messages") self.messages.config(labelanchor = "nw") self.messages.pack(side = RIGHT, fill=BOTH) self.mkMessageArea(self.messages)
class GuiImageSimilarResolver(object): def __init__(self, dry_run): self.dry_run = dry_run self.root = Tk() self.root.bind('s', self.are_similar) self.root.bind('d', self.are_not_similar) self.root.bind('n', self.are_not_similar) self.root.bind('c', self.clear_feedback) self.root.bind('q', self.quit) self.root.bind('<Left>', self.goto_prev) self.root.bind('<Right>', self.goto_next) self.root.bind('f', self.toggle_skip) screen_size = get_screen_size(self.root) self.max_image_size = (int(0.4 * screen_size[0]), int(0.75 * screen_size[1])) self.pairs = [] self.item_frame = Frame(self.root) self.background = self.item_frame.cget("background") self.item_frame.pack(expand=False, side=TOP) self.skip_pairs_with_feedback = 1 self.ref_counting = None self.label_sim = None self.label_bppl = self.label_bppr = None self.label_pixelsl = self.label_pixelsr = None self.label_resl = self.label_resr = None self.label_sizel = self.label_sizer = None self.label_pathl = self.label_pathr = None self.label_imgl = self.label_imgr = None self.create_gui() self.index = None def toggle_skip(self, *_): self.skip_pairs_with_feedback = not self.skip_pairs_with_feedback def goto_prev(self, *_): self.change_index(-1) def goto_next(self, *_): self.change_index(1) def are_similar(self, *_): self.save_feedback(1) def are_not_similar(self, *_): self.save_feedback(0) def clear_feedback(self, *_): self.pairs[self.index].clear_feedback() self.change_index(1) def save_feedback(self, are_similar): self.pairs[self.index].save_feedback(are_similar) self.change_index(1) def change_index(self, change): last_index = self.index while 1: self.index += change if self.index < 0: self.index = 0 if self.index >= len(self.pairs): self.index = len(self.pairs) - 1 if self.index == last_index: break if not self.skip_pairs_with_feedback: break if not self.has_feedback(): break last_index = self.index self.update_labels() def quit(self, _): self.root.destroy() def resolve(self, pair): self.pairs.append(pair) def finished(self): if self.pairs: self.index = 0 self.update_labels() mainloop() else: print ("No duplicated images found. Maybe f_image.py was not run" + " yet? Or there are no images in the path given.") def create_gui(self): root = self.item_frame row = 0 self.label_sim = Label(root, text="no text (sim)") self.label_sim.grid(row=row, column=0, columnspan=2) row += 1 self.label_imgl = Label(root, text="no image") self.label_imgl.grid(row=row, column=0) self.label_imgr = Label(root, text="no image") self.label_imgr.grid(row=row, column=1) row += 1 self.label_pathl = Label(root, text="no text (path)") self.label_pathl.grid(row=row, column=0) self.label_pathr = Label(root, text="no text (path)") self.label_pathr.grid(row=row, column=1) row += 1 self.label_sizel = Label(root, text="no text (size)") self.label_sizel.grid(row=row, column=0) self.label_sizer = Label(root, text="no text (size)") self.label_sizer.grid(row=row, column=1) row += 1 self.label_pixelsl = Label(root, text="no text (pixels)") self.label_pixelsl.grid(row=row, column=0) self.label_pixelsr = Label(root, text="no text (pixels)") self.label_pixelsr.grid(row=row, column=1) row += 1 self.label_resl = Label(root, text="no text (resolution)") self.label_resl.grid(row=row, column=0) self.label_resr = Label(root, text="no text (resolution)") self.label_resr.grid(row=row, column=1) row += 1 self.label_bppl = Label(root, text="no text (bbp)") self.label_bppl.grid(row=row, column=0) self.label_bppr = Label(root, text="no text (bbp)") self.label_bppr.grid(row=row, column=1) row += 1 Button(root, text="Similar images", underline=0, command=self.are_similar).grid(row=row, column=0) Button(root, text="Do not match (images are NOT similar)", underline=0, command=self.are_not_similar).grid(row=row, column=1) def has_feedback(self): pair = self.pairs[self.index] feedback = pair.get_feedback() return feedback is not None def update_labels(self): pair = self.pairs[self.index] feedback = pair.get_feedback() if feedback is None: feedback = "not yet" background = self.background elif feedback == 0: feedback = "not similar" background = "#FFE0E0" elif feedback == 1: feedback = "similar" background = "#E0FFE0" else: assert 0 img1 = ImageRelated(pair.path1, self.max_image_size, background) img2 = ImageRelated(pair.path2, self.max_image_size, background) self.ref_counting = (img1, img2) self.item_frame.config(background=background) text = "%d/%d similarity=%f feedback = %s skip=%d" % ( self.index + 1, len(self.pairs), self.pairs[self.index].similarity, feedback, self.skip_pairs_with_feedback) self.label_sim.config(background=background, text=text) self.label_imgl.config(text=None, image=img1.tk_image) self.label_imgr.config(text=None, image=img2.tk_image) size1 = img1.file_size size2 = img2.file_size color1, color2 = get_colors(cmp(size1, size2)) self.label_pathl.config(text=split_path(img1.path)) self.label_pathr.config(text=split_path(img2.path)) self.label_sizel.config(fg=color1, text=format_bytes(size1)) self.label_sizer.config(fg=color2, text=format_bytes(size2)) color1, color2 = get_colors(cmp(img1.pixels, img2.pixels)) self.label_pixelsl.config(fg=color1, text=format_bytes(img1.pixels)) self.label_pixelsr.config(fg=color2, text=format_bytes(img2.pixels)) self.label_resl.config(fg=color1, text="%d x %d" % img1.image.size) self.label_resr.config(fg=color2, text="%d x %d" % img2.image.size) color1, color2 = get_colors(cmp(img1.bpp, img2.bpp)) self.label_bppl.config(fg=color1, text="%f" % img1.bpp) self.label_bppr.config(fg=color2, text="%f" % img2.bpp)
def initUI(self): self.parent.title("IAF CALC 0.01") self.pack(fill=BOTH, expand=1) self.configure(background="white") frameTOP = Frame(self) frameTOP.config(bg="white") frameTOP.pack(side=TOP) frameFILES = Frame(frameTOP) frameFILES.pack(side=LEFT, padx=10) # --- BUTTON FOR FILE 1 --- # frameF1 = LabelFrame(frameFILES, text="Eyes open file:", relief=FLAT, borderwidth=1, background="white") frameF1.pack(fill=X, expand=1) self.nameF1 = Entry(frameF1, width=50) self.nameF1.config(bg="lightgray") self.nameF1.pack(side=LEFT) self.nameF1.delete(0, END) self.nameF1.insert(0, "") self.buttonLoadFile1 = Button(frameF1, text="...", command=self.askOpenFile1) self.buttonLoadFile1.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE 2 --- # frameF2 = LabelFrame(frameFILES, text="Eyes closed file:", relief=FLAT, borderwidth=1, background="white") frameF2.pack(fill=X, expand=1) self.nameF2 = Entry(frameF2, width=50) self.nameF2.config(bg="lightgray") self.nameF2.pack(side=LEFT) self.nameF2.delete(0, END) self.nameF2.insert(0, "") self.buttonLoadFile2 = Button(frameF2, text="...", command=self.askOpenFile2) self.buttonLoadFile2.pack(side=LEFT, padx=5, pady=5) # ----------------------- # # --- BUTTON FOR FILE OUTPUT --- # frameO = LabelFrame(frameFILES, text="Output directory:", relief=FLAT, borderwidth=1, background="white") frameO.pack(fill=X, expand=1) self.nameO = Entry(frameO, width=50) self.nameO.config(bg="lightgray") self.nameO.pack(side=LEFT) self.nameO.delete(0, END) self.nameO.insert(0, "") self.buttonSelectOutput = Button(frameO, text="...", command=self.askOutputDirectory) self.buttonSelectOutput.pack(side=LEFT, padx=5, pady=5) # -------------------------------# # self.pack() # self.pack(fill=Y, expand=1) # ---------- PSD PARAMETER SELECTION ---------- # framePARAM = Frame(frameTOP) framePARAM.config(bg="white") framePARAM.pack(side=LEFT, fill=X) frame = LabelFrame(framePARAM, text="PSD Parameters", relief=RIDGE, borderwidth=1, background="white") frame.pack(fill=BOTH, expand=1, side=TOP) wFs = Label(frame, text="Fs:", bg="white") wFs.pack(side=LEFT) self.inputFs = Entry(frame, width=5) self.inputFs.pack(side=LEFT, padx=5) self.inputFs.delete(0, END) self.inputFs.insert(0, "500") wWS = Label(frame, text="Window size:", bg="white") wWS.pack(side=LEFT) self.inputWinSize = Entry(frame, width=5) self.inputWinSize.pack(side=LEFT, padx=5) self.inputWinSize.delete(0, END) self.inputWinSize.insert(0, "1024") wOL = Label(frame, text="Overlap:", bg="white") wOL.pack(side=LEFT) self.inputOverlap = Entry(frame, width=5) self.inputOverlap.pack(side=LEFT, padx=5) self.inputOverlap.delete(0, END) self.inputOverlap.insert(0, "512") wWT = Label(frame, text="Window function:", bg="white") wWT.pack(side=LEFT) variable = StringVar(frame) variable.set("Hamming") # default value self.inputWinType = OptionMenu(frame, variable, "Hamming", "Bartlett", "Blackman", "Hanning", "None") self.inputWinType.config(bg="white", width=10) self.inputWinType.pack(side=LEFT) buttonRun = Button(frame, text="GO!", command=self.goTime) buttonRun.pack(side=RIGHT) # Channel selector frameCh = LabelFrame(framePARAM, text="Channels", relief=RIDGE, borderwidth=1, background="white") frameCh.pack(fill=BOTH, expand=1, side=TOP) self.EOch1 = IntVar() self.inputEOch1 = Checkbutton(frameCh, text="1", variable=self.EOch1, bg="white") self.inputEOch1.pack(side=LEFT) self.EOch2 = IntVar() self.inputEOch2 = Checkbutton(frameCh, text="2", variable=self.EOch2, bg="white") self.inputEOch2.pack(side=LEFT) self.EOch3 = IntVar() self.inputEOch3 = Checkbutton(frameCh, text="3", variable=self.EOch3, bg="white") self.inputEOch3.pack(side=LEFT) self.EOch4 = IntVar() self.inputEOch4 = Checkbutton(frameCh, text="4", variable=self.EOch4, bg="white") self.inputEOch4.pack(side=LEFT) self.EOch5 = IntVar() self.inputEOch5 = Checkbutton(frameCh, text="5", variable=self.EOch5, bg="white") self.inputEOch5.pack(side=LEFT) self.EOch6 = IntVar() self.inputEOch6 = Checkbutton(frameCh, text="6", variable=self.EOch6, bg="white") self.inputEOch6.pack(side=LEFT) self.EOch7 = IntVar() self.inputEOch7 = Checkbutton(frameCh, text="7", variable=self.EOch7, bg="white") self.inputEOch7.pack(side=LEFT) self.EOch8 = IntVar() self.inputEOch8 = Checkbutton(frameCh, text="8", variable=self.EOch8, bg="white") self.inputEOch8.pack(side=LEFT) # IAF Calculation parameters frameIAF = LabelFrame(framePARAM, text="IAF Search Limits", relief=RIDGE, borderwidth=1, background="white") frameIAF.pack(fill=BOTH, expand=1, side=TOP) labelLowBound = Label(frameIAF, text="Lower limit (Hz):", bg="white") labelLowBound.pack(side=LEFT) self.inputLowBound = Entry(frameIAF, width=5) self.inputLowBound.pack(side=LEFT, padx=5) self.inputLowBound.delete(0, END) self.inputLowBound.insert(0, "7") labelUpBound = Label(frameIAF, text="Upper limit (Hz):", bg="white") labelUpBound.pack(side=LEFT) self.inputUpBound = Entry(frameIAF, width=5) self.inputUpBound.pack(side=LEFT, padx=5) self.inputUpBound.delete(0, END) self.inputUpBound.insert(0, "14") self.GaussVar = IntVar() self.inputGauss = Checkbutton(frameIAF, text="Gauss", variable=self.GaussVar, bg="white") self.inputGauss.pack(side=LEFT) buttonRun = Button(frameIAF, text="IAF!", command=self.calculateIAF) buttonRun.pack(side=RIGHT) self.pack() # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # END OF TOP FRAME # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # my variables self.chSelect = 0 self.chOther = 0 self.P1 = ndarray(1) self.f1 = ndarray(1) self.P2 = ndarray(1) self.f2 = ndarray(1) self.filename1 = "..." self.filename2 = "..." self.IAF = 10 self.doGauss = True # FIGURE STUFF !!! self.Pmax = 0 self.Pmin = 0 self.Dmax = 0 self.Dmin = 0 frameBOTTOM = Frame(self) frameBOTTOM.config(bg="white") frameBOTTOM.pack(side=BOTTOM, pady=10) frameFig = LabelFrame(frameBOTTOM, text="Spectrum", relief=RIDGE, borderwidth=1, background="white") frameFig.pack(fill=X, expand=1, side=LEFT, padx=10) self.fig1 = matplotlib.figure.Figure(figsize=(7, 3), dpi=100) # ,frameon=False) self.fig1.set_facecolor("white") self.fig = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(self.fig1, master=frameFig) self.a1 = self.fig1.add_subplot(121) self.a2 = self.fig1.add_subplot(122) self.fig.show() self.fig.get_tk_widget().pack(side=BOTTOM) frameConfig = LabelFrame( frameBOTTOM, text="Filter configuration", relief=RAISED, borderwidth=1, background="white" ) frameConfig.pack(fill=BOTH, expand=1, side=RIGHT, padx=10) frameIAF = LabelFrame(frameConfig, text="Individual Alpha Frequency (IAF)") frameIAF.config(bg="white") frameIAF.pack(expand=1, side=TOP, padx=10) self.inputIAF = Entry(frameIAF, width=5) self.inputIAF.pack(side=LEFT, padx=5) self.inputIAF.delete(0, END) self.inputIAF.insert(0, "0") self.buttonWriteDefault = Button(frameIAF, text="Update Filters", command=self.updateFilters) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) frameFilters = LabelFrame(frameConfig, text="Filters", relief=RAISED, borderwidth=1, background="white") frameFilters.pack(fill=X, expand=1, side=TOP) # THETA FRAME frameTheta = LabelFrame(frameFilters, text="Theta", relief=RAISED, borderwidth=1, background="white") frameTheta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputThetaLow = Entry(frameTheta, width=8) self.inputThetaLow.pack(side=LEFT, padx=5, pady=5) self.inputThetaLow.delete(0, END) self.inputThetaLow.insert(0, "0") self.inputThetaHigh = Entry(frameTheta, width=8) self.inputThetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputThetaHigh.delete(0, END) self.inputThetaHigh.insert(0, "0") # BETA FRAME frameBeta = LabelFrame(frameFilters, text="Beta", relief=RAISED, borderwidth=1, background="white") frameBeta.pack(expand=1, side=TOP, pady=5, padx=5) self.inputBetaLow = Entry(frameBeta, width=8) self.inputBetaLow.pack(side=LEFT, padx=5, pady=5) self.inputBetaLow.delete(0, END) self.inputBetaLow.insert(0, "0") self.inputBetaHigh = Entry(frameBeta, width=8) self.inputBetaHigh.pack(side=LEFT, padx=5, pady=5) self.inputBetaHigh.delete(0, END) self.inputBetaHigh.insert(0, "0") # SMR FRAME frameSMR = LabelFrame(frameFilters, text="SMR", relief=RAISED, borderwidth=1, background="white") frameSMR.pack(expand=1, side=TOP, pady=5, padx=5) self.inputSMRLow = Entry(frameSMR, width=8) self.inputSMRLow.pack(side=LEFT, padx=5, pady=5) self.inputSMRLow.delete(0, END) self.inputSMRLow.insert(0, "0") self.inputSMRHigh = Entry(frameSMR, width=8) self.inputSMRHigh.pack(side=LEFT, padx=5, pady=5) self.inputSMRHigh.delete(0, END) self.inputSMRHigh.insert(0, "0") frameButtons = LabelFrame(frameConfig, text="Commands", relief=RAISED, borderwidth=1, background="white") frameButtons.pack(expand=1, side=BOTTOM) self.buttonWriteConfig = Button(frameButtons, text="Write Filters", command=self.writeFilters) self.buttonWriteConfig.pack(side=LEFT, padx=5, pady=5) self.buttonWriteDefault = Button(frameButtons, text="Reset to Defaults", command=self.resetIAFtoDefault) self.buttonWriteDefault.pack(side=LEFT, padx=5, pady=5) # self.buttonVisualize = Button(frameButtons, text="VIS",command=self.resetIAFtoDefault) # self.buttonVisualize.pack(side=LEFT,padx=5,pady=5) self.buttonPrintFig = Button(frameButtons, text="Print Figure", command=self.printFigureToFile) self.buttonPrintFig.pack(side=LEFT, padx=5, pady=5)
class ModelBayes(): def __init__(self, master, console, params, row, col, maingui): self.frame = Frame(master) self.maingui = maingui self.frame.config(padx=20, pady=20, bg=Styles.colours["grey"]) self.frame.grid(row=row, column=col, sticky=NW) self.console = console self.params = params self.headerbayes() self.policy() self.kernels() self.iterations() self.minormax() self.outputdir() def destroy(self): self.frame.destroy() def headerbayes(self): headerbayes = header(self.frame, "Set the Bayesian Optimization Parameters") headerbayes.config(width=400) headerbayes.grid(row=0, column=0, sticky=W, columnspan=2) def policy(self): policyheader = headersmall(self.frame, text="Policies:") cei = Checkbutton(self.frame, text="Expected Improvement", variable=self.params["policies"][0], bg=Styles.colours["grey"]) cpi = Checkbutton(self.frame, text="Probability Improvement", variable=self.params["policies"][1], bg=Styles.colours["grey"]) cucb = Checkbutton(self.frame, text="Upper Confidence Bound", variable=self.params["policies"][2], bg=Styles.colours["grey"]) ctho = Checkbutton(self.frame, text="Thompson", variable=self.params["policies"][3], bg=Styles.colours["grey"]) self.isreadyR(cei) self.isreadyR(cpi) self.isreadyR(cucb) self.isreadyR(ctho) policyheader.grid(row=1, column=0, sticky=W, columnspan=1) cei.grid(row=2, column=0, pady=0, sticky=W, padx=10, columnspan=1) cpi.grid(row=3, column=0, pady=0, sticky=W, padx=10, columnspan=1) cucb.grid(row=4, column=0, pady=0, sticky=W, padx=10, columnspan=1) ctho.grid(row=5, column=0, pady=0, sticky=W, padx=10, columnspan=1) def kernels(self): kernelsheader = headersmall(self.frame, text="Kernels:") cse = Checkbutton(self.frame, text="Squared Exponential", variable=self.params["kernels"][0], bg=Styles.colours["grey"]) cm5 = Checkbutton(self.frame, text="Matern 5", variable=self.params["kernels"][1], bg=Styles.colours["grey"]) cm3 = Checkbutton(self.frame, text="Matern 3", variable=self.params["kernels"][2], bg=Styles.colours["grey"]) cm1 = Checkbutton(self.frame, text="Matern 1", variable=self.params["kernels"][3], bg=Styles.colours["grey"]) self.isreadyR(cse) self.isreadyR(cm5) self.isreadyR(cm3) self.isreadyR(cm1) kernelsheader.grid(row=1, column=1, sticky=W, columnspan=2) cse.grid(row=2, column=1, pady=0, sticky=W, padx=10, columnspan=1) cm5.grid(row=3, column=1, pady=0, sticky=W, padx=10, columnspan=1) cm3.grid(row=4, column=1, pady=0, sticky=W, padx=10, columnspan=1) cm1.grid(row=5, column=1, pady=0, sticky=W, padx=10, columnspan=1) Label(self.frame, text="", font=("Arial", 6)).grid(row=6, column=0, sticky=W, columnspan=2) def iterations(self): iterheader = headersmall(self.frame, "Iterations:") e = smallentry(self.frame, self.params["iter"], 10, True) iterheader.grid(row=7, column=0, sticky=W, columnspan=1) self.isreadyR(e, "<FocusOut>") e.grid(row=8, column=0, sticky=W, padx=25) def minormax(self): objheader = headersmall(self.frame, text="Objective:") rmim = Radiobutton(self.frame, text="Minimize", variable=self.params["objective"], value="min", bg=Styles.colours["grey"]) rmax = Radiobutton(self.frame, text="Maximize", variable=self.params["objective"], value="max", bg=Styles.colours["grey"]) objheader.grid(row=7, column=1, sticky=W, columnspan=2) rmim.grid(row=8, column=1, pady=0, sticky=W, padx=10) rmax.grid(row=9, column=1, pady=0, sticky=W, padx=10) # Label(self.frame, text="", font=("Arial", 12)).grid(row=10, column=0, sticky=W, columnspan=2) def outputdir(self): iframe = Frame(self.frame) iframe.config(padx=5, pady=5, bg=Styles.colours["grey"]) iframe.grid(row=10, column=0, sticky=W + E + N + S, columnspan=3, rowspan=2) objheader = headersmall(iframe, text="Model Output Directory (Optional):") boutfile = yellowbutton(iframe, "Select Directory", 14, click=None) eoutfiledir = entry(iframe, self.params["outputdir"], 32, fileCheck=False, dir=True, button=boutfile) objheader.grid(row=0, column=0, sticky=W, columnspan=2) boutfile.grid(row=1, column=2, pady=5) eoutfiledir.grid(row=1, column=0, columnspan=2) def isreadyR(self, r, e=None): def check(): if self.checkall(): self.maingui.ready("bayes") else: self.maingui.notready("bayes") if e is None: r.config(command=check) else: r.bind(e, lambda e: check()) def checkall(self): p = sum([v.get() for v in self.params["policies"]]) k = sum([v.get() for v in self.params["kernels"]]) i = self.params["iter"].get() return p and k and i
class main_window(Frame): def __init__(self,master): #AQUI SE DESARROLLA LA APLICACION... #color= self.frame_left_up_right_in1 global var_phaser_level var_phaser_level=tk.DoubleVar() global var_phaser_order var_phaser_order=tk.DoubleVar() global var_phaser_gain var_phaser_gain=tk.DoubleVar() global var_distortion_level var_distortion_level=tk.DoubleVar() global var_distortion_mixer var_distortion_mixer=tk.DoubleVar() global var_distortion_gain var_distortion_gain=tk.DoubleVar() global var_high_level var_high_level=tk.DoubleVar() global var_middle_level var_middle_level=tk.DoubleVar() global var_low_level var_low_level=tk.DoubleVar() Frame.__init__(self, master, background="white") self.master=master global p p = pyaudio.PyAudio() #for i in range(p.get_device_count()): #dev = p.get_device_info_by_index(i) #in=str(dev['name']) #if in=='USB PnP Sound Device: USB Audio (hw:0,0)' # in_usb=i #if in=='snd_rpi_hifiberry_dacplus: (hw:1,0)' # out_hifi=i #print((i,dev['name'],dev['maxInputChannels'])) global stream stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,output=True,frames_per_buffer=CHUNK,input_device_index=0,output_device_index=1) get_phaser_level(None) master.geometry('800x800+0+0') master.title('Control Principal') master.configure(background="yellow") #main frames frame_main_left=Frame(master,width=400, height=450,bg="red") frame_main_left.grid(row=0,column=0) frame_main_right=Frame(master,width=400, height=450,bg="white") frame_main_right.grid(row=0,column=1) #sub frames frame_left_up=Frame(frame_main_left,width=400, height=300,bg="blue") frame_left_up.pack(side=TOP) frame_left_down=Frame(frame_main_left,width=400, height=150,bg="brown") frame_left_down.pack(side=BOTTOM) phaser_frame=LabelFrame(frame_left_down,text="PHASER EFFECT",width=380, height=150,bg="white") phaser_frame.pack() path_phaser = '/home/pi/Desktop/tesis/phasermodified.gif' img_phaser = PIL.Image.open(open('/home/pi/Desktop/tesis/phasermodified.gif','rb')) img_phaser.resize((300, 300), PIL.Image.ANTIALIAS) img_phaser=ImageTk.PhotoImage(img_phaser,width=380, height=150) button_phaser=Button(phaser_frame,text="PHASER EFFECT",width=380, height=150,bg="blue", image=img_phaser) button_phaser.bind('<Button-1>', lambda event:negar(flag,0)) button_phaser.pack() frame_right_up=Frame(frame_main_right,width=400, height=300,bg="red") frame_right_up.pack(side=TOP) frame_right_down=Frame(frame_main_right,width=400, height=150,bg="white") frame_right_down.pack(side=BOTTOM) distortion_frame=LabelFrame(frame_right_down,text="DISTORTION EFFECT",width=380, height=150,bg="white") distortion_frame.pack() path_distortion = '/home/pi/Desktop/tesis/distortionmodified.gif' img_distortion = PIL.Image.open(path_distortion) img_distortion.resize((300, 300), PIL.Image.ANTIALIAS) img_distortion=ImageTk.PhotoImage(img_distortion,width=380, height=150) button_distortion=Button(distortion_frame,text="DISTORTION EFFECT",width=380, height=150,bg="blue",image=img_distortion) button_distortion.bind('<Button-1>', lambda event:negar(flag,1)) button_distortion.pack() #subsubframes left frame_left_up_left=Frame(frame_left_up,width=300, height=300,bg="blue") frame_left_up_left.pack(side=LEFT) frame_left_up_right=Frame(frame_left_up,width=100, height=300,bg="blue") frame_left_up_right.pack(side=RIGHT) #subsubframes right frame_right_up_left=Frame(frame_right_up,width=300, height=300,bg="blue") frame_right_up_left.pack(side=LEFT) frame_right_up_right=Frame(frame_right_up,width=100, height=300,bg="blue") frame_right_up_right.pack(side=RIGHT) #------------------------------------------------------------------------------------------------------- #subframes left widgtes IN FRAME LEFT UP label_left1=LabelFrame(frame_left_up_left,text="PHASE",width=280, height=70,bg="white") label_left1.pack() frame_left_up_left_in1=Frame(label_left1,width=280, height=70,bg="black") frame_left_up_left_in1.pack(fill="both", expand=True, padx=5, pady=5) #phaser level parameter slide1_left= Scale(frame_left_up_left_in1,variable=var_phaser_level, from_=0, to=3.14,resolution=0.01, orient=HORIZONTAL) slide1_left.pack() slide1_left.config(length=270,width=30) #------------------------------------------------------------------------------------------- label_left2=LabelFrame(frame_left_up_left,text="ORDER",width=280, height=70,bg="white") label_left2.pack() frame_left_up_left_in2=Frame(label_left2,width=280, height=70,bg="yellow") frame_left_up_left_in2.pack(fill="both", expand=True, padx=5, pady=5) #phaser order parameter slide2_left = Scale(frame_left_up_left_in2,variable=var_phaser_order, from_=0, to=3,tickinterval=1, orient=HORIZONTAL) slide2_left.pack() slide2_left.config(length=270,width=30) #-------------------------------------------------------------------------------------------- label_left3=LabelFrame(frame_left_up_left,text="GAIN",width=280, height=70,bg="white") label_left3.pack() frame_left_up_left_in3=Frame(label_left3,width=280, height=70,bg="red") frame_left_up_left_in3.pack(fill="both", expand=True, padx=5, pady=5) #phaser gain parameter slide3_left = Scale(frame_left_up_left_in3,variable=var_phaser_gain, from_=0, to=5, orient=HORIZONTAL) slide3_left.pack() slide3_left.config(length=270,width=30) #subframes right widgtes IN FRAME LEFT UP self.frame_left_up_right_in1=Frame(frame_left_up_right,width=80, height=250,bg="white") self.frame_left_up_right_in1.pack(fill="both", expand=True, padx=5, pady=5) #frame_left_up_right_in2=Frame(frame_left_up_right,width=80, height=250,bg="brown") #frame_left_up_right_in2.pack(fill="both", expand=True, padx=5, pady=5) #------------------------------------------------------------------------------------------------ #subframes left widgtes IN FRAME RIGHT UP label_right1=LabelFrame(frame_right_up_left,text="MIX",width=280, height=70,bg="white") label_right1.pack() frame_right_up_left_in1=Frame(label_right1,width=280, height=120,bg="brown") frame_right_up_left_in1.pack(fill="both", expand=True, padx=5, pady=5) slide1_right = Scale(frame_right_up_left_in1,variable=var_distortion_mixer, from_=0, to=100, orient=HORIZONTAL) slide1_right.pack() slide1_right.config(length=270,width=30) #------------------------------------------------------------------------------------------------ label_right2=LabelFrame(frame_right_up_left,text="LEVEL",width=280, height=70,bg="white") label_right2.pack() frame_right_up_left_in2=Frame(label_right2,width=280, height=120,bg="yellow") frame_right_up_left_in2.pack(fill="both", expand=True, padx=5, pady=5) slide2_right = Scale(frame_right_up_left_in2, variable=var_distortion_level,from_=0, to=200, orient=HORIZONTAL) slide2_right.pack() slide2_right.config(length=270,width=30) #-------------------------------------------- #subframes right widgtes IN RIGHT LEFT UP self.frame_right_up_right_in1=Frame(frame_right_up_right,width=80, height=250,bg="white") self.frame_right_up_right_in1.pack(fill="both", expand=True, padx=5, pady=5) #new frames frame_equalizer=Frame(master,width=800, height=200,bg="black") frame_equalizer.grid(row=1,column=0,columnspan=2) high_label=LabelFrame(frame_equalizer,text="HIGH",width=800, height=72,bg="white") high_label.pack() middle_label=LabelFrame(frame_equalizer,text="MIDDLE",width=800, height=72,bg="white") middle_label.pack() low_label=LabelFrame(frame_equalizer,text="LOW",width=800, height=72,bg="white") low_label.pack() high_frame=Frame(high_label,width=780, height=70,bg="black") high_frame.pack(fill="both", expand=True, padx=5, pady=5) middle_frame=Frame(middle_label,width=780, height=70,bg="black") middle_frame.pack(fill="both", expand=True, padx=5, pady=5) low_frame=Frame(low_label,width=780, height=70,bg="black") low_frame.pack(fill="both", expand=True, padx=5, pady=5) high_scale = Scale(high_frame,variable=var_high_level, from_=-5, to=5, orient=HORIZONTAL) high_scale.set(0) high_scale.pack() high_scale.config(length=780,width=35) middle_scale = Scale(middle_frame,variable=var_middle_level, from_=-5, to=5, orient=HORIZONTAL) middle_scale.set(0) middle_scale.pack() middle_scale.config(length=780,width=35) low_scale = Scale(low_frame,variable=var_low_level, from_=-5, to=5, orient=HORIZONTAL) low_scale.set(0) low_scale.pack() low_scale.config(length=780,width=35) def cambiar_color(self, i): if i == 0: if flag[i] == True: self.frame_left_up_right_in1.config(bg="black") if flag[i] == False: self.frame_left_up_right_in1.config(bg="white") if i == 1: if flag[i] == True: self.frame_right_up_right_in1.config(bg="black") if flag[i] == False: self.frame_right_up_right_in1.config(bg="white")
def __init__(self, parent, root): AdvancedSearchDialog.singleton = True # pseudo singleton now active Toplevel.__init__(self, root) self.title = 'Advanced search' self.transient(root) self.shared_data = Query() self.shared_data.attach(parent) self.protocol('WM_DELETE_WINDOW', self.free) center(self, (constants.IMADVWIDTH, constants.IMADVHEIGHT)) window_frame = Frame(self) window_frame.pack(fill=BOTH, expand=True) top_window_frame = Frame(window_frame) top_window_frame.pack(side=TOP, fill=X, expand=False) Label(top_window_frame, text='Filter by: ').pack(side=LEFT, padx=15, pady=5) Label(top_window_frame, text='Leave fields untouched that you do not wish to search by', font=('Helvetica', 8)).pack(side=RIGHT, padx=15, pady=5) bottom_window_frame = Frame(window_frame) bottom_window_frame.pack(side=TOP, fill=BOTH, expand=False, padx=15) bottom_window_frame.config(highlightthickness=1) bottom_window_frame.config(highlightbackground='grey') Label(bottom_window_frame, text='Plot ').grid(row=0, column=0, padx=5, pady=5, sticky='w') Label(bottom_window_frame, text='Date(YYYY-MM-DD) ').grid(row=1, column=0, padx=5, pady=5, sticky='w') Label(bottom_window_frame, text='Time Range ').grid(row=2, column=0, padx=5, pady=5, sticky='w') Label(bottom_window_frame, text='Latitude Range ').grid(row=3, column=0, padx=5, pady=5, sticky='w') Label(bottom_window_frame, text='Altitude Range ').grid(row=4, column=0, padx=5, pady=5, sticky='w') Label(bottom_window_frame, text='File ').grid(row=5, column=0, padx=5, pady=5, sticky='w') self.plots = StringVar() self.am_pm = StringVar() self.plot_entry = OptionMenu(bottom_window_frame, self.plots, 'backscattered', 'depolarized', 'vfm') self.plot_entry.grid(row=0, column=1, padx=10, pady=5, sticky='w', columnspan=3) self.date_entry = Entry(bottom_window_frame, width=25) self.date_entry.grid(row=1, column=1, padx=5, pady=5, sticky='w', columnspan=4) self.date_entry.insert(END, '0000-00-00') self.b_time_entry = Entry(bottom_window_frame, width=10) self.b_time_entry.grid(row=2, column=1, padx=5, pady=5, sticky='w') self.b_time_entry.insert(END, '00:00:00') Label(bottom_window_frame, text='to').grid(row=2, column=2, pady=5, sticky='w') self.e_time_entry = Entry(bottom_window_frame, width=10) self.e_time_entry.grid(row=2, column=3, padx=5, pady=5, sticky='w') self.e_time_entry.insert(END, '00:00:00') self.am_pm_menu = OptionMenu(bottom_window_frame, self.am_pm, 'am', 'pm') self.am_pm_menu.grid(row=2, column=4, pady=5, sticky='w') self.b_lat_entry = Entry(bottom_window_frame, width=10) self.b_lat_entry.grid(row=3, column=1, padx=5, pady=5, sticky='w') self.b_lat_entry.insert(END, '0.0') Label(bottom_window_frame, text='to').grid(row=3, column=2, pady=5, sticky='w') self.e_lat_entry = Entry(bottom_window_frame, width=10) self.e_lat_entry.grid(row=3, column=3, padx=5, pady=5, sticky='w') self.e_lat_entry.insert(END, '0.0') self.b_alt_entry = Entry(bottom_window_frame, width=10) self.b_alt_entry.grid(row=4, column=1, padx=5, pady=5, sticky='w') self.b_alt_entry.insert(END, '0.0') Label(bottom_window_frame, text='to').grid(row=4, column=2, pady=5, sticky='w') self.e_alt_entry = Entry(bottom_window_frame, width=10) self.e_alt_entry.grid(row=4, column=3, padx=5, pady=5, sticky='w') self.e_alt_entry.insert(END, '0.0') self.file_entry = Entry(bottom_window_frame, width=25) self.file_entry.grid(row=5, column=1, padx=5, pady=5, sticky='w', columnspan=4) bottom_button_frame = Frame(window_frame) bottom_button_frame.pack(side=TOP, fill=BOTH, expand=False) Button(bottom_button_frame, text='Search', command=self.parse_ranges).\ pack(side=LEFT, padx=15, pady=10)