Beispiel #1
0
 def _build_state_display(self, position):
     state_field = LabelFrame(self,
                              text=s.language.cards,
                              relief=RAISED,
                              width=self.master.width - 31)
     state_slots_per_row = int((self.master.width - 31) / 32)
     state_slot_height = 24 + (
         (int(len(self._current_player.states) / state_slots_per_row) + 1) *
         32)
     if self._current_player.states:
         for index, state in enumerate(self._current_player.states):
             if state not in self._main_window.engine.nemKartyaStatusz:
                 if state in self._main_window.engine.eventszotar.keys():
                     origin = self._main_window.engine.eventszotar
                     prefix = "event"
                 else:
                     origin = self._main_window.engine.kincsszotar
                     prefix = "treasure"
                 icon = f"{prefix}_{self._main_window.engine.eventszotar[state].kep}_i"
                 icon = icon[(icon.find('_') + 1):]
                 button = Button(
                     state_field,
                     image=Gallery.get(icon),
                     command=lambda s=state: origin[s].megjelenik(1))
                 button.grid(row=int(index / state_slots_per_row),
                             column=index % state_slots_per_row)
         state_field.config(height=state_slot_height)
         if state_field.winfo_children():
             state_field.grid(row=position, column=0)
         state_field.grid_propagate(False)
Beispiel #2
0
    def popup_window(self, text, filename):
        top = Toplevel()

        info = LabelFrame(top, text=text)  #"Group Information")
        info_text = Text(
            info,
            width=50,
            height=8,
            #bg=projectBgColor,
            #fg=projectFgColor,
            font=("nimbus mono bold", "11"))

        def savefunc():
            self.writepaste(filename, info_text)

        def loadfunc():
            self.readpaste(filename, info_text)

        info_save_button = Button(info, text="Save", command=savefunc)
        info_load_button = Button(info, text="Load", command=loadfunc)

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_load_button.grid(row=5, column=5, padx=10, pady=5)
        info_save_button.grid(row=5, column=6, padx=10, pady=5)
        info_text.grid(row=1,
                       rowspan=3,
                       column=1,
                       columnspan=7,
                       padx=5,
                       pady=5)

        info.grid(row=7, column=0, columnspan=6, sticky=W, padx=20, pady=10)
        top.focus_force()
Beispiel #3
0
def showMainValues():

    global tkroot
    global labels
    global mframe
    global values

    from tkinter import Tk, N, W
    from tkinter.ttk import LabelFrame, Label

    # first run, set up the thingy
    print("Setting up Main Values...")
    init_parse(getMainValues, _parse_main_values_xml, values)

    sleep(0.5)

    print("Setting up Advanced Values...")
    init_parse(getAdvancedValues, _parse_adv_values_xml, values)

    print("initializing tkinter interface...")

    tkroot = Tk()
    mframe = LabelFrame(tkroot, text="Main Frame")
    labels = {}
    for group in values:
        lframe = LabelFrame(mframe, text=group)
        labels[group] = OrderedDict()
        labels[group]['frame'] = lframe
        for param, pv in values[group].items():
            labels[group][param] = {}
            plabel = Label(lframe, text=param)
            vlabel = Label(lframe, text=pv)
            labels[group][param]['plabel'] = plabel
            labels[group][param]['vlabel'] = vlabel

    mframe.grid()
    for i, group in enumerate(labels):
        for param in labels[group]:
            if param == 'frame':
                labels[group][param].grid(column=i, row=0, sticky=N)
            else:
                labels[group][param]['plabel'].grid(sticky=W)
                labels[group][param]['vlabel'].grid(sticky=W)

    tkroot.grid()

    print('setting up polling intervals')

    tkroot.after(500, poll_main_values)
    tkroot.after(750, poll_adv_values)

    print('Ready')

    tkroot.mainloop()
    print("afterloop")
Beispiel #4
0
def serverpanel(server):
    ''' Draws the top panel with the server information '''
    serverpanel = LabelFrame(win, text = "Server Details")
    serverpanel.grid(column = 0, row = 0, padx = 5, pady = 5, sticky = W+E)
    Label(serverpanel, text = "Server Name: ").grid(column = 0, row = 0, sticky = W)
    Label(serverpanel, text = "Server Type: ").grid(column = 0, row = 1, sticky = W)
    Label(serverpanel, text = "Load Balancer Status: ").grid(column = 0, row = 2, sticky = W)
    Label(serverpanel, textvariable = snv).grid(column = 1, row = 0, sticky = W)
    Label(serverpanel, textvariable = stv ).grid(column = 1, row = 1, sticky = W)
    Label(serverpanel, textvariable = lbv).grid(column = 1, row = 2, sticky = W)
    serverstatus(server)
Beispiel #5
0
class StatsTabFrame(Frame):

    def __init__(self, win, tabs):
        super().__init__(tabs)
        self.win = win
        self.tabs = tabs
        self.tabs.add(self, text="Stats")

        self.stats: StatsCollection = None
        self.selection: StatsCollection = None

        self._body = Frame(self)
        self._body.grid(row=0, column=0, sticky=EW, padx=PAD_X, pady=PAD_Y)

        # Load
        self._load_stats = LoadStatsFrame(self._body, self.set_stats)
        self._load_stats.grid(row=0, column=0, padx=PAD_X, pady=PAD_Y, sticky=EW)

        # Summary
        self._summary = LabelFrame(self._body, text="  Records  ")
        self._summary.grid(row=1, column=0, sticky=EW)

        self._all_counters = CountersFrame(self._summary, text="  All  ")
        self._all_counters.grid(row=0, column=0, padx=2 * PAD_X, pady=2 * PAD_Y, sticky=EW)

        self._selection_counters = CountersFrame(self._summary, text="  Selection  ")
        self._selection_counters.grid(column=1, row=0, padx=2 * PAD_X, pady=2 * PAD_Y, sticky=EW)

        # Filter
        self._filters = FilterSelectionFrame(self._body, self.get_all, self.get_selection, self.set_selection)
        self._filters.grid(row=2, column=0, sticky=EW)

        # Reports
        self._reports = ReportsFrame(self._body, self.get_selection)
        self._reports.grid(row=3, column=0, sticky=EW)

    def get_all(self) -> StatsCollection:
        return self.stats

    def get_selection(self) -> StatsCollection:
        return self.selection

    def set_stats(self, stats: StatsCollection):
        self.stats = stats
        self._all_counters.set_stats(stats.get_counters())
        self._filters.set_countries(stats.unique_countries)
        self.set_selection(stats)

    def set_selection(self, stats: StatsCollection):
        self.selection = stats
        self._selection_counters.set_stats(stats.get_counters())
        self._filters.set_tournaments(stats.unique_tournaments)
Beispiel #6
0
def buttonpanel():
    ''' Draws the panel with the buttons at the bottom '''
    butpanel = LabelFrame(win, text = "")
    butpanel.grid(column = 0, row = 2, padx = 5, pady = 5, sticky = W+E)
    Button(butpanel, text = "Stop Services", command = onStop).grid(column = 0, row = 0)
    Button(butpanel, text = "Start Services", command = onStart).grid(column = 1, row = 0)
    Button(butpanel, text = "Refresh List", command = onStatus).grid(column = 2, row = 0)
    
    if server.lbalanced.upper() == "YES":
        # lbutpanel = LabelFrame(win, text = "")
        # lbutpanel.grid(column = 0, row = 3, padx = 5, pady = 5, sticky = W+E)
        Button(butpanel, text = "Stop Load Balancer", command = lbStop).grid(column = 0, row = 1)
        Button(butpanel, text = "Start Load Balancer", command = lbStart).grid(column = 1, row = 1)
Beispiel #7
0
 def _build_inventory_display(self, position):
     gold_frame = LabelFrame(self._inventory_display,
                             text=s.language.treasure)
     Label(gold_frame, image=Gallery.get("penz-d2")).grid(row=0, column=0)
     Label(gold_frame,
           textvariable=self._current_player.gold).grid(row=0, column=1)
     gold_frame.grid(row=0, column=0, sticky=N + E + W + S, padx=5)
     crew_frame = LabelFrame(self._inventory_display, text=s.language.crew)
     Label(crew_frame, image=Gallery.get("crew")).grid(row=0, column=0)
     Label(crew_frame,
           textvariable=self._current_player.crew).grid(row=0, column=1)
     crew_frame.grid(row=0, column=1, sticky=N + E + W + S, padx=5)
     self._inventory_display.grid(row=position, column=0)
     self._inventory_display.columnconfigure(
         ALL, minsize=(self.master.width - 20) / 2)
Beispiel #8
0
    def create_widgets(self):
        ''' creates GUI for app '''
        # expand widget to fill the grid
        # self.columnconfigure(1, weight=1, pad=100)
        # self.rowconfigure(1, weight=1, pad=20)

        lframe = LabelFrame(self, text="Combobox", width=100, height=100)
        lframe.grid(row=1, column=1, sticky=N + S + E + W)

        self.cbov = StringVar()
        cbox = Combobox(lframe, textvariable=self.cbov)
        cbox['values'] = ('value1', 'value2', 'value3')
        # COMBO.bind('<<ComboboxSelected>>', self.ONCOMBOSELECT)
        cbox.current(0)
        cbox.grid(row=1, column=1, sticky=E + W, padx=10, pady=20)
    def create_widgets(self):
        ''' Creates all widgets.
        '''
        self.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)

        validate_btn = Button(self,
                              text='Validate weight restrictions',
                              command=self.on_validate_weights)
        validate_btn.grid(row=0, column=0, padx=10, pady=5, sticky=N + W)

        panel = LabelFrame(self, text='Weight restrictions')
        panel.columnconfigure(0, weight=1)
        panel.rowconfigure(0, weight=1)
        panel.grid(row=1, column=0, padx=5, pady=5, sticky=E + W + S + N)

        weight_tab_main = VerticalScrolledFrame(panel)
        weight_tab_main.grid(row=0, column=0, sticky=E + W + S + N)
        weights_tab = weight_tab_main.interior

        self.abs_weights = TextForWeights(weights_tab, 'absolute',
                                          'Input1 <= 0.02',
                                          self.current_categories, self.params,
                                          'ABS_WEIGHT_RESTRICTIONS')
        self.abs_weights.grid(row=0, column=0, padx=10, pady=5, sticky=N + W)
        self.virtual_weights = TextForWeights(weights_tab, 'virtual',
                                              'Input1 >= 0.34',
                                              self.current_categories,
                                              self.params,
                                              'VIRTUAL_WEIGHT_RESTRICTIONS')
        self.virtual_weights.grid(row=1,
                                  column=0,
                                  padx=10,
                                  pady=5,
                                  sticky=N + W)
        self.price_ratio_weights = TextForWeights(weights_tab, 'price ratio',
                                                  'Input1/Input2 <= 5',
                                                  self.current_categories,
                                                  self.params,
                                                  'PRICE_RATIO_RESTRICTIONS',
                                                  True)
        self.price_ratio_weights.grid(row=2,
                                      column=0,
                                      padx=10,
                                      pady=5,
                                      sticky=N + W)
Beispiel #10
0
def servicepanel(server):
    ''' Draws the panel with the service information '''
    global servv, spanel
    servicepanel = LabelFrame(win, text = "Service Details")
    servicepanel.grid(column = 0, row = 1, padx = 5, pady = 5, sticky = W+E)
    
    services = server.getservices()
    scount = 0
    for service in services:
        servv[service] = StringVar()
        Label(servicepanel, text = service + ": ").grid(column = 0, row = scount, sticky = W)

        Label(servicepanel, textvariable = servv[service]).grid(column = 1, row = scount, sticky = W)
        servicestatus(server, service)
        scount += 1
        
    spanel = Label(servicepanel, textvariable = status).grid(column = 0, row = scount + 1, columnspan = 2, sticky = W)
    status.set("")
Beispiel #11
0
    def add_model_component(self, sherpa_model_component):
        '''Create UI elements for model component.

        Each component is a separate LabelFrame.  Each
        model parameter is a row within that frame.
        '''
        self.sherpa_model = sherpa_model_component

        lfrm = LabelFrame(self.get_win(),
                          text=sherpa_model_component.name)
        lfrm.grid(row=self.get_row(), column=0, columnspan=1,
                  padx=(10, 10), pady=(10, 10))
        self.next_row()

        # Repeat column headers in each model component
        self.add_column_headers(lfrm)
        for par in self.sherpa_model.pars:
            mod_par = DaxModelParameter(self, lfrm, par)
            self.model_parameters.append(mod_par)
            self.next_row()
Beispiel #12
0
            def __init__(self, master):
                top = self.top = Toplevel(master)
                top.title("Parameters")
                top.attributes("-topmost", True)
                width = str(26 * (len(model_dict) + 4))
                top.geometry("310x" + width)
                top.grid()
                top.resizable(0, 0)

                frame = LabelFrame(top,
                                   text=model_name,
                                   relief=RIDGE,
                                   width=260)
                frame.grid(row=0,
                           column=0,
                           columnspan=2,
                           sticky="EWNS",
                           padx=15,
                           pady=15)

                self.values = list()
                line = 1
                for k, v in model_dict.items():
                    Label(frame, text=k, width=20) \
                        .grid(row=line, column=0, columnspan=1, sticky='W', padx=4, pady=1)
                    e = Entry(frame, width=10)
                    e.insert(END, str(v))
                    e.grid(row=line,
                           column=1,
                           columnspan=1,
                           sticky='E',
                           padx=6,
                           pady=1)
                    self.values.append(e)
                    line += 1

                Button(frame, text='  Help  ', command=self.help) \
                    .grid(row=line+2, column=0, columnspan=1, sticky='W', padx=4, pady=4)
                Button(frame, text='   Ok   ', command=self.cleanup) \
                    .grid(row=line+2, column=1, columnspan=1, sticky='E', padx=4, pady=4)
                top.bind('<Return>', self.cleanup)
    def create_widgets(self):
        ''' Creates all widgets.
        '''
        self.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)

        validate_btn = Button(self, text='Validate weight restrictions',
                              command=self.on_validate_weights)
        validate_btn.grid(row=0, column=0, padx=10, pady=5, sticky=N+W)

        panel = LabelFrame(self, text='Weight restrictions')
        panel.columnconfigure(0, weight=1)
        panel.rowconfigure(0, weight=1)
        panel.grid(row=1, column=0,
                   padx=5, pady=5, sticky=E+W+S+N)

        weight_tab_main = VerticalScrolledFrame(panel)
        weight_tab_main.grid(row=0, column=0, sticky=E+W+S+N)
        weights_tab = weight_tab_main.interior

        self.abs_weights = TextForWeights(weights_tab, 'absolute',
                                          'Input1 <= 0.02',
                                          self.current_categories, self.params,
                                          'ABS_WEIGHT_RESTRICTIONS')
        self.abs_weights.grid(row=0, column=0, padx=10, pady=5, sticky=N+W)
        self.virtual_weights = TextForWeights(weights_tab, 'virtual',
                                              'Input1 >= 0.34',
                                              self.current_categories,
                                              self.params,
                                              'VIRTUAL_WEIGHT_RESTRICTIONS')
        self.virtual_weights.grid(row=1, column=0, padx=10, pady=5, sticky=N+W)
        self.price_ratio_weights = TextForWeights(weights_tab, 'price ratio',
                                                  'Input1/Input2 <= 5',
                                                  self.current_categories,
                                                  self.params,
                                                  'PRICE_RATIO_RESTRICTIONS',
                                                  True)
        self.price_ratio_weights.grid(row=2, column=0, padx=10, pady=5,
                                      sticky=N+W)
Beispiel #14
0
    def add(self, widget, load=None):
        #print("Add New :",widget)
        # Widget Container
        wid_frame = LabelFrame(self.cont, text="Note {}\n".format(widget))
        # Text Widget Creation
        #TextBox = tk.Text(wid_frame, width=w, height=h, undo=True)
        TextBox = scrolledtext.ScrolledText(wid_frame,
                                            width=w,
                                            height=h,
                                            undo=True)
        TextBox.config(wrap="word")
        TextBox.setvar("NAME", value=widget)
        if load is None:
            #TextBox.insert(tk.INSERT, "Note {}\n".format(widget))
            pass
        else:
            TextBox.insert(INSERT, load)
        TextBox.pack()
        # BackUp
        self.widgets[widget] = [wid_frame, TextBox]
        # Place Widget Frame[container]
        wid_frame.grid(row=0, column=0)

        self.show(widget)
Beispiel #15
0
    def popup_window( self, text, filename ) :
        top = Toplevel()
  
        info = LabelFrame(top, text=text )#"Group Information")
        info_text = Text(info,
                              width=50,
                              height=8,
                              #bg=projectBgColor,
                              #fg=projectFgColor,
                              font=("nimbus mono bold","11")
                             )
        
        def savefunc() :
            self.writepaste( filename, info_text ) 
        
        def loadfunc() :
            self.readpaste( filename, info_text ) 
        
        info_save_button = Button(info, 
                                  text="Save", 
                                  command = savefunc )
        info_load_button = Button(info,
                                  text="Load",
                                  command = loadfunc )

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_load_button.grid( row=5, column=5, padx=10, pady=5 )
        info_save_button.grid( row=5, column=6, padx=10, pady=5 )
        info_text.grid(row=1,  rowspan=3, 
                       column=1,  columnspan=7,
                       padx=5, pady=5 )

        info.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        top.focus_force()
Beispiel #16
0
    def build(self):
        """widget construction"""

        fr4 = LabelFrame(self.fr0, text='yiq')
        fr4.grid(column=2, row=0)
        vcmdyiq = root.register(yiq_okay)

        self.cans = []
        sboxes = []
        comps = ['y', 'i', 'q']
        names = ['luma', 'i hue', 'q hue']
        tkvars = [self.yvar, self.ivar, self.qvar]
        froms = [0, -100, -100]
        ticks = [10, 20, 20]

        for ix, comp in enumerate(comps):
            Label(fr4, text=names[ix]).grid(row=3 * ix, column=0)
            Label(fr4, height=1).grid(row=2 + 3 * ix, column=2)
            self.cans.append(
                Canvas(fr4,
                       width=self.canvas_w,
                       height=self.canvas_h,
                       bd=0,
                       highlightthickness=0))
            self.cans[ix].grid(row=3 * ix, column=1)
            TtkScale(fr4,
                     from_=froms[ix],
                     to=100,
                     variable=tkvars[ix],
                     orient='horizontal',
                     length=self.scale_l,
                     command=self.yiqhandle,
                     tickinterval=ticks[ix]).grid(row=1 + 3 * ix,
                                                  column=1,
                                                  sticky='nw')
            sboxes.append(
                Spinbox(fr4,
                        from_=froms[ix],
                        to=100,
                        textvariable=tkvars[ix],
                        validatecommand=(vcmdyiq, '%d', '%P', '%S', froms[ix],
                                         100),
                        validate='key',
                        command=self.yiqhandle,
                        width=5,
                        increment=1))
            sboxes[ix].grid(row=1 + 3 * ix, column=2, sticky='nw')
            sboxes[ix].bind('<KeyRelease>', self.checksyiq)

        # assume initial setting 0,100,100 hsv
        to_colour = yiq_to_rgb(*(30, 100.0, 40.56))
        # print(self.canvas_w)
        draw_gradient(self.cans[0],
                      yiq_to_rgb(0.0, 100.0, 40.56),
                      yiq_to_rgb(100, 100, 40.56),
                      width=self.canvas_w)
        draw_gradient(self.cans[1],
                      yiq_to_rgb(30, -100.0, 40.56),
                      to_colour,
                      width=self.canvas_w)
        draw_gradient(self.cans[2],
                      yiq_to_rgb(30, 100, -100),
                      yiq_to_rgb(30, 100, 100),
                      width=self.canvas_w)

        self.can_yiq = can_yiq = Canvas(fr4,
                                        width=self.space,
                                        height=self.space)
        can_yiq.grid(column=1, row=9, pady=25, sticky='n')
        self.yiqGamut = PhotoImage(file='../../figures/colour_space.png')
        can_yiq.create_image(0, 0, anchor='nw', image=self.yiqGamut)
        self.ring = circle(can_yiq,
                           300.0,
                           210.84,
                           self.ring_radius,
                           width=self.ring_width,
                           activeoutline='#555555',
                           tags='ring')  # 240, 181

        can_yiq.bind('<Button-1>', self.move_ring)
        can_yiq.tag_bind('ring', '<B1-Motion>', self.move_ring)
Beispiel #17
0
        h = value.lstrip('#')
        tvalue = tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
        if contrast(tvalue) < 0.5:
            lbl2["foreground"] = 'white'

    lbl2["text"] = tvalue
    lbl2["background"] = value


root = Tk()
fr = Frame(root)
fr.grid(column=0, row=0)
fr2 = Frame(root)
fr2.grid(column=1, row=0)
lbl = Label(fr,
            text='Enter colour code\n use no quotes\n code can be r,g,b\n \
    hash #rrggbb\n or name')
lbl.grid(column=0, row=0, padx=5, pady=10)

ey = Entry(fr2)
ey.grid(column=0, row=0, padx=5, pady=10)
out = StringVar(ey.get())

lf = LabelFrame(fr, text='Colour')
lf.grid(column=0, row=1)
lbl2 = Label(lf, text='waiting')
lbl2.grid(column=0, row=1)
but1 = Button(fr2, text='Make Colour', command=getit)
but1.grid(column=0, row=1, padx=5, pady=5)
root.mainloop()
Beispiel #18
0
    def popup_window_contrast(self) :
        text = "Comparing ChIP-seq Peaks"
        contrast_fn = join(self.workpath.get(),self.contrast_fn)
        peakinfo_fn  = join(self.workpath.get(),self.peakinfo_fn)
        NA='N/A'
        
        try :
            groups = list(set([l.split('\t')[-1].strip() for l in open(peakinfo_fn) if l.split('\t')[-1].strip()]))
            if len(groups) < 2 :
                showwarning( 'WARNING!', "More than one groups need to be fefined in Peak Information File!" )
                print( 'groups:', groups )
                return
            
        except IOError :
            showerror( 'Error', "Did you set peak information?" )
            print('Error:', 'Cannot process peakcall.tab file:')
            return
        
        top = Toplevel()
        info = LabelFrame(top, text=text )#"Group Information")
        
        print( groups )
        contrast_vars = []
        contrast_menus = []
        n = 0
        groups.insert(0, NA)
        for i in range( int((len(groups)-1)*(len(groups)-2)/2) ):
            n = n + 1
            v1, v2 = StringVar(), StringVar()
            contrast_vars.append( [v1, v2] )
            o1, o2 = OptionMenu(info, v1, *groups), OptionMenu(info, v2, *groups)
            contrast_menus.append( [o1, o2] )

            v1.set(NA)
            v2.set(NA)
            vslabel = Label(info, text="  VS  ")

            o1.grid( row=n, column=0, padx=4, pady=1 )
            o2.grid( row=n, column=2, padx=4, pady=1 )
            vslabel.grid( row=n, column=1, padx=4, pady=1 )

        def savefunc() :
            info_text = StringIO()
            for v1, v2 in contrast_vars :
                v1 = v1.get() if v1.get() != NA else ""
                v2 = v2.get() if v2.get() != NA else ""
                
                if v1 and v2 :
                    pass
                elif v1 or v2 :
                    showerror( 'Error', "None or Both columns should be selected!" )
                    return
                else:
                    continue
                    
                print( v1, v2, file=info_text, sep="\t" )
            
            fp = open( contrast_fn, 'w' )
            fp.write( info_text.getvalue() )
            fp.close()
                              
        
        def loadfunc() :
            #self.readpaste( filename, info_text ) 
            for i, l in enumerate(open( contrast_fn )) :
                v1, v2 = l.split('\t')
                v1 = v1.strip()
                v2 = v2.strip()
                
                if v1 :
                    try : assert v1 in groups
                    except :
                        showwarning('WARNING', 'Group name is not in the selection list!' )
                        print( 'v1:',v1 ) 
                        print( 'group:', groups )
                        continue
                
                if v2 :
                    try: assert v2 in groups
                    except :
                        showwarning('WARNING', 'Group name is not in the selection list!' )
                        print( 'v2:',v2 ) 
                        print( 'group:', groups )
                        continue
                
                contrast_vars[i][0].set(v1)
                contrast_vars[i][1].set(v2)
                
        
        def clearfunc() :
            for v1, v2 in contrast_vars :
                v1.set(NA)
                v2.set(NA)
                
        
        info_clear_button = Button(top, 
                                  text="Clear", 
                                  command = clearfunc )
        info_save_button = Button(top, 
                                  text="Save", 
                                  command = savefunc )
        info_load_button = Button(top,
                                  text="Load",
                                  command = loadfunc )

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_clear_button.grid( row=5, column=3, padx=10, pady=5 )
        info_load_button.grid( row=5, column=4, padx=10, pady=5 )
        info_save_button.grid( row=5, column=5, padx=10, pady=5 )


        info.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        top.focus_force()
Beispiel #19
0
class GenomeSeqFrame( PipelineFrame ) :
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.pairs = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)

        PipelineLabels = ['Initial QC', 
			  'Germline',
			  'Somatic Tumor-Normal',
                          'Somatic Tumor-Only']
        Pipelines=["initialqcgenomeseq",
                   "wgslow", 
		   'wgs-somatic',
                   'wgs-somatic-tumoronly']

        self.label2pipeline = { k:v for k,v in zip(PipelineLabels, Pipelines)}
        PipelineLabel = self.PipelineLabel = StringVar()
        Pipeline = self.Pipeline = StringVar()
        PipelineLabel.set(PipelineLabels[0])
        
        #om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller)
        om = OptionMenu(eframe, PipelineLabel, *PipelineLabels, command=self.option_controller)
        om.config()#bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
        
    def option_controller( self, *args, **kwargs ) :
        PipelineFrame.option_controller( self )

        self.Pipeline.set( self.label2pipeline[self.PipelineLabel.get()] )
        print( self.Pipeline.get() )

        if self.Pipeline.get() == 'wgs-somatic' :
            self.add_pairs( self.eframe )
            #self.dry_button.config( state="disabled" )
        elif self.Pipeline.get() != 'wgs-somatic' :
            self.del_pairs( self.eframe )
            #if self.workpath.get() :
            #    self.dry_button.config( state='active' )

    
    def add_pairs( self, parent ) :
        if not self.pairs :
            self.pairs = LabelFrame(parent, text='Pairs')
            self.pairs_text = Text( self.pairs,
                             width=50,
                             height=8,
                             #bg=projectBgColor,
                             #fg=projectFgColor,
                             font=("nimbus mono bold","11")
                            )

            self.pairs_save_button = Button(self.pairs, 
                                            text="Save", 
                                            command = self.writepair )
            
            self.pairs_load_button = Button(self.pairs,
                                            text="Load",
                                            command = self.readpair )
            
            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.pairs_load_button.grid( row=5, column=5, padx=10, pady=5 )
            self.pairs_save_button.grid( row=5, column=6, padx=10, pady=5 )
            self.pairs_text.grid( row=1,  rowspan=3, 
                                 column=1,  columnspan=7,
                                 padx=5, pady=5 )

        self.pairs.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        
    def del_pairs( self, parent ) :
        if self.pairs :
            self.pairs.grid_forget()
            
    def writepair( self ) :
        self.writepaste( 'pairs', self.pairs_text )
        #self.dry_button.config( state='active' )
    
    def readpair( self ) :
        self.readpaste( 'pairs', self.pairs_text )
Beispiel #20
0
    def build(self):
        """widget construction

        Parameters
        ----------
        None

        Results
        -------
        None
        """

        fr1 = LabelFrame(self.fr0, text='rgb')
        fr1.grid(column=0, row=0, sticky='news')

        rl0 = Label(fr1, text='red  ')
        rl0.grid(column=0, row=0, sticky='s')

        self.rcan = Canvas(fr1, width=self.canvas_w, height=self.canvas_h, bd=0,
                           highlightthickness=0)
        self.rcan.grid(column=1, row=0, sticky='s')

        rsc = TtkScale(fr1, from_=0, to=255, variable=self.rvar, orient='horizontal',
                       length=self.scale_l, command=self.rhandle, tickinterval=20)
        rsc.grid(column=1, row=1, sticky='news')

        rsb = Spinbox(fr1, from_=0, to=255, textvariable=self.rvar,
                      command=self.rhandle, width=5)
        rsb.grid(column=2, row=1, sticky='nw')

        rel = Label(fr1, height=1)
        rel.grid(column=2, row=2)

        gl0 = Label(fr1, text='green')
        gl0.grid(column=0, row=3)

        self.gcan = Canvas(fr1, width=self.canvas_w, height=self.canvas_h, bd=0,
                           highlightthickness=0)
        self.gcan.grid(column=1, row=3, sticky='s')

        gsc = TtkScale(fr1, from_=0, to=255, variable=self.gvar, orient='horizontal',
                       length=self.scale_l, command=self.ghandle, tickinterval=20)
        gsc.grid(column=1, row=4, sticky='news')

        gsb = Spinbox(fr1, from_=0, to=255, textvariable=self.gvar,
                      command=self.ghandle, width=5)
        gsb.grid(column=2, row=4, sticky='nw')

        gel = Label(fr1, height=1)
        gel.grid(column=2, row=5)

        bl0 = Label(fr1, text='blue ')
        bl0.grid(column=0, row=6, sticky='s')

        self.bcan = Canvas(fr1, width=self.canvas_w, height=self.canvas_h, bd=0,
                           highlightthickness=0)
        self.bcan.grid(column=1, row=6, sticky='n')

        bsc = TtkScale(fr1, from_=0, to=255, variable=self.bvar, orient='horizontal',
                       length=self.scale_l, command=self.bhandle, tickinterval=20)
        bsc.grid(column=1, row=7, sticky='news')

        bsb = Spinbox(fr1, from_=0, to=255, textvariable=self.bvar,
                      command=self.bhandle, width=5)
        bsb.grid(column=2, row=7, sticky='nw')

        bel = Label(fr1, height=1)
        bel.grid(column=2, row=8)

        fr3 = LabelFrame(self.fr0, text='colour mix')
        fr3.grid(column=1, row=0, sticky='nw')

        self.cmcan = cmcan = Canvas(fr3, width=30, height=30, bd=0,
                                    highlightthickness=0)
        cmcan.grid(column=0, row=0, sticky='n', columnspan=2)
        cmcan.grid_propagate(0)
        vdraw_gradient(self.cmcan, (255, 0, 0), alpha=255)

        cml = Label(fr3, text='hash\nvalue')
        cml.grid(column=0, row=1)

        ent0 = Entry(fr3, width=8, textvariable=self.evar)
        ent0.grid(column=1, row=1)

        fr2 = LabelFrame(self.fr0, text='opacity')
        fr2.grid(column=0, row=1, sticky='news')

        al0 = Label(fr2, text='alpha')
        al0.grid(column=0, row=0, sticky='s')

        self.acan = Canvas(fr2, width=self.canvas_w, height=self.canvas_h, bd=0,
                           highlightthickness=0)
        self.acan.grid(column=1, row=0, sticky='n')

        asc = TtkScale(fr2, from_=0, to=255, variable=self.avar, orient='horizontal',
                       length=self.scale_l, command=self.ahandle, tickinterval=20)
        asc.grid(column=1, row=1, sticky='news')

        asb = Spinbox(fr2, from_=0, to=255, textvariable=self.avar,
                      command=self.ahandle, width=5)
        asb.grid(column=2, row=1, sticky='nw')

        ael = Label(fr2, text=' ', height=1)
        ael.grid(column=2, row=2, sticky='s')

        draw_gradient(self.rcan, (0, 0, 0), (255, 0, 0), width=self.canvas_w)
        draw_gradient(self.gcan, (255, 0, 0),
                      (255, 255, 0), width=self.canvas_w)
        draw_gradient(self.bcan, (255, 0, 0),
                      (255, 0, 255), width=self.canvas_w)
        draw_agradient(self.acan, (127, 127, 127),
                       (255, 0, 0), width=self.canvas_w)
Beispiel #21
0
class ExomeSeqFrame( PipelineFrame ) :
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.pairs = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
        Pipelines=["initialqc","exomeseq-somatic","exomeseq-germline"]
        Pipeline = self.Pipeline = StringVar()
        Pipeline.set(Pipelines[0])
        
        om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller)
        #om.config()#bg = widgetBgColor,fg=widgetFgColor)
        #om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)

        targetsL=Label(eframe,
                       text="Target Capture Kit")
                       #,fg=textLightColor,bg=baseColor)
        targetsL.grid(row=5,column=0,sticky=W,padx=10,pady=5)
        targetsE = Entry(eframe,textvariable=self.targetspath, width=50)

        if self.genome=="hg19":
            self.targetspath.set( 
                "/data/CCBR_Pipeliner/db/PipeDB/lib/SS_v5_UTRs_hg19.bed" )
        else:
            self.targetspath.set(
                "/data/CCBR_Pipeliner/db/PipeDB/lib/SureSelect_mm10.bed")

        targetsE.grid(row=5,column=1,columnspan=6,sticky=W,padx=10,pady=5)
        self.targetspath.trace('w', lambda a,b,c,x="targetspath":self.makejson(x))
        label = Label (eframe, 
                       text = 
                       "By default, the path to the Agilent V5+UTR targets file is filled in here" ) 
        
        label.grid(row=6, column=0, columnspan=5, sticky=W, padx=10, pady=5)
        
        
            
    def option_controller( self, *args, **kwargs ) :
        PipelineFrame.option_controller( self )
        
        if self.Pipeline.get() == 'exomeseq-somatic' :
            self.add_pairs( self.eframe )
            #self.dry_button.config( state="disabled" )
        elif self.Pipeline.get() != 'exomeseq-somatic' :
            self.del_pairs( self.eframe )
            #if self.workpath.get() :
            #    self.dry_button.config( state='active' )
                
    
    def add_pairs( self, parent ) :
        if not self.pairs :
            self.pairs = LabelFrame(parent, text='Pairs')
            self.pairs_text = Text( self.pairs,
                             width=50,
                             height=8,
                             #bg=projectBgColor,
                             #fg=projectFgColor,
                             font=("nimbus mono bold","11")
                            )

            self.pairs_save_button = Button(self.pairs, 
                                            text="Save", 
                                            command = self.writepair )
            
            self.pairs_load_button = Button(self.pairs,
                                            text="Load",
                                            command = self.readpair )
            
            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.pairs_load_button.grid( row=5, column=5, padx=10, pady=5 )
            self.pairs_save_button.grid( row=5, column=6, padx=10, pady=5 )
            self.pairs_text.grid( row=1,  rowspan=3, 
                                 column=1,  columnspan=7,
                                 padx=5, pady=5 )

        self.pairs.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        
    def del_pairs( self, parent ) :
        if self.pairs :
            self.pairs.grid_forget()
            
    def writepair( self ) :
        self.writepaste( 'pairs', self.pairs_text )
        #self.dry_button.config( state='active' )
    
    def readpair( self ) :
        self.readpaste( 'pairs', self.pairs_text )
Beispiel #22
0
class Assist_Serial_Port():
    def __init__(self):
        self.BTL = [110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600, 115200, 128000, 256000]  # 波特率下拉列表框内容
        self.JYW = ['NONE', 'ODD', 'EVEN', 'MARK', 'SPACE']  # 校验位下拉列表框内容
        self.SJW = [5, 6, 7, 8]  # 数据位下拉列表内容
        self.TZW = [1, 1.5, 2]  # 停止位下拉列表内容
        self.CKXX = self.read_serial_info()
        self.PZMC = ['串口号','波特率','校验位','数据位','停止位']
        self.serial_res_hex_bzw = False  # 接收数据框内容显示hex标志位
        self.serial_sen_hex_bzw = False  # 发送数据框内容显示hex标志位
        self.radiobutton_sen_ascii_click_count = 1  # 设置发送ASCII单选框点击次数为0
        self.radiobutton_sen_hex_click_count = 0  # 设置发送HEX单选框点击次数为0

        self.root = Tk(className='串口调试助手')  # 创建一个主窗体,并命名为‘串口调试助手’
        self.root.protocol('WM_DELETE_WINDOW',self.close_window)  # 实现点击窗口关闭按钮,调用self.close_window方法,关闭已经打开的串口,销毁窗口
        self.root.geometry('630x580')  # 设置窗体大小
        self.root.minsize(width=630, height=435)  # 这两句语言限制窗口不能随意变化
        self.root.maxsize(width=630, height=435)

        self.lf = LabelFrame(self.root, text='串口设置')  # 创建标签容器,并且命名为‘串口设置’
        self.lf.grid(padx=8, pady=10,ipadx=3, ipady=5,row=1,column=1,sticky='n')  # 设置标签容器在窗口中的位置

        self.text_res_con = LabelFrame(master=self.root,text='接收设置')  # 创建标签容器,并命名为接收设置
        self.text_res_con.grid(row=1,column=1,sticky='s')  # 设置标签容器在窗口中的位置

        self.text_sen_con = LabelFrame(master=self.root,text='发送设置')  # 创建标签容器,并命名为接收设置
        self.text_sen_con.grid(padx=8, pady=10,row=2,column=1,sticky='nesw')  # 设置标签容器在窗口中的位置

        self.data_rec = LabelFrame(self.root, text='数据日志')  # 创建标签容器,并且命名为‘数据日志’
        self.data_rec.grid(ipadx=3, ipady=5,row=1, column=2, sticky='e')  # 设置标签容器在窗口中的位置

        self.y_scroll = Scrollbar(self.data_rec)  # 创建接收文本框的Y轴下拉框
        self.y_scroll.pack(side=RIGHT,fill=Y)  # 确定位置

        self.result_text = Text(master=self.data_rec,height=22,width=66,yscrollcommand=self.y_scroll.set) # 创建一个多文本组件,用来显示接收的串口信息,并且配置关联滚轴
        self.result_text.pack(side=RIGHT,fill=Y)  # 设置多文本组件在窗口中的位置
        self.y_scroll.config(command=self.result_text.yview)  # 让文本框和滚轴关联起来

        self.data_sen = LabelFrame(self.root, text='数据发送')  # 创建标签容器,并且命名为‘数据日志’
        self.data_sen.grid(ipadx=3, ipady=5,row=2, column=2, sticky='w')  # 设置标签容器在窗口中的位置

        self.send_text = Text(master=self.data_sen,height=6,width=60)  # 创建一个发送文本框
        self.send_text.grid(row=1,column=1,sticky='n')  # 设置标签容器在窗口中的位置

        self.button_send = Button(self.data_sen,text='发送消息',command=self.button_send_serial_click,width=7)  # 创建一个发送文本框
        self.button_send.grid(row=1,column=2,sticky='NSEW')  # 设置串口打开按钮的位置

    '''关闭串口工具窗口触发的函数'''
    def close_window(self):
        ans = messagebox.askyesno('警告',message='确定关闭窗口?')
        print(ans,'ans')
        if ans:
            try:
                self.thd.stop()  # 停止读取串口线程
                '''确保串口会被关掉,修复关掉串口立马更改波特率,显示错误的问题'''
                while self.ser.isOpen():
                    self.ser.close()  # 将串口实例关闭
            except:
                print('关闭窗口')
            self.root.destroy()
        else:
            return

    '''创建串口配置框架'''
    def serial_config_frame(self):
        for temp in enumerate(self.PZMC):
            '''生成标签组'''
            label_name = Label(self.lf, text=temp[1])  # 创建串口标签
            label_name.grid(padx=5,pady=6,column=1,row=temp[0] + 1)   # 设置标签在标签容器中的位置

            '''生成下拉列表框组'''
            if temp[0] == 0:
                self.combobox0 = Combobox(master=self.lf, values=self.CKXX, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox0.current(0)  # 设置下拉列表当前选中项
                self.combobox0.grid(column=2, row=1, sticky='e')  # 设置下拉列表框在标签容器中的位置
                self.combobox0.bind('<Button-1>',self.update_serial_info)
            elif temp[0] == 1:
                self.combobox1 = Combobox(master=self.lf, values=self.BTL, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox1.current(6)   # 设置下拉列表当前选中项
                self.combobox1.grid(column=2, row=2, sticky='e')  # 设置下拉列表框在标签容器中的位置
            elif temp[0] == 2:
                self.combobox2 = Combobox(master=self.lf, values=self.JYW, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox2.current(0)   # 设置下拉列表当前选中项
                self.combobox2.grid(column=2, row=3, sticky='e')  # 设置下拉列表框在标签容器中的位置
            elif temp[0] == 3:
                self.combobox3 = Combobox(master=self.lf, values=self.SJW, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox3.current(3)   # 设置下拉列表当前选中项
                self.combobox3.grid(column=2, row=4, sticky='e')  # 设置下拉列表框在标签容器中的位置
            else:
                self.combobox4 = Combobox(master=self.lf, values=self.TZW, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox4.current(0)   # 设置下拉列表当前选中项
                self.combobox4.grid(column=2, row=5, sticky='e')  # 设置下拉列表框在标签容器中的位置

        self.button_open_serial = Button(self.lf,text='打开串口',command=self.button_open_serial_click)  # 创建串口打开按钮
        self.button_open_serial.grid(row=6,columnspan=5,sticky='s')  # 设置串口打开按钮的位置

    '''串口单击按钮函数'''
    def button_open_serial_click(self):
        if self.button_open_serial['text'] == '打开串口':
            '''下面的try...except...else操作确定当串口被占用报错后,无法在重新打开串口'''
            try:
                self.open_serial_and_config()  # 打开串口
                self.thd = Thread_myself(target=self.serial_read_content)  # 新建线程对象,并且传入串口对象
                self.thd.start()  # 启动串口助手
            except Exception:
                self.button_open_serial['text'] = '打开串口'
                self.result_text.config(state=NORMAL)
                self.result_text.tag_config('text_error_tag', foreground='red')  # 设置插入文本样式
                self.result_text.insert('end','\r\n无法打开串口,请检查串口连接或者是否被占用...\r\n','text_error_tag')
                self.result_text.config(state=DISABLED)
                self.result_text.see(END)  # 文本框总是显示最新内容
            else:
                self.button_open_serial['text'] = '关闭串口'
                self.combobox0.config(state='disabled')  # 打开之后将所有下拉列表框禁用防止误操作
                self.combobox1.config(state='disabled')
                self.combobox2.config(state='disabled')
                self.combobox3.config(state='disabled')
                self.combobox4.config(state='disabled')
        else:
            self.button_open_serial['text'] = '打开串口'
            self.combobox0.config(state='readonly')
            self.combobox1.config(state='readonly')
            self.combobox2.config(state='readonly')
            self.combobox3.config(state='readonly')
            self.combobox4.config(state='readonly')
            try:
                self.thd.stop()  # 停止读取串口线程
                '''确保串口会被关掉,修复关掉串口立马更改波特率,显示错误的问题'''
                while self.ser.isOpen():
                    self.ser.close()  # 将串口实例关闭
            except:
                print('无聊')

    '''打开串口并配置'''
    def open_serial_and_config(self,timeout=5):
        if self.combobox2.get() == 'NONE':  # 判断校验位方式
            parity = 'N'
        elif self.combobox2.get() == 'ODD':
            parity = 'O'
        elif self.combobox2.get() == 'EVEN':
            parity = 'E'
        elif self.combobox2.get() == 'MARK':
            parity = 'M'
        else:
            parity = 'S'

        if self.combobox3.get() == '5':  # 判断数据然后配数据位
            bytesize = 5
        elif self.combobox3.get() == '6':
            bytesize = 6
        elif self.combobox3.get() == '7':
            bytesize = 7
        else:
            bytesize = 8

        if self.combobox4.get() == '1':  # 判断串口停止位
            stopbits = 1
        elif self.combobox4.get() == '1.5':
            stopbits = 1.5
        else:
            stopbits = 2

        '''创建一个串口实例'''
        self.ser = Serial(port=self.combobox0.get(),baudrate=self.combobox1.get(),parity=parity,bytesize=bytesize,stopbits=stopbits,timeout=timeout)
        self.ser.set_buffer_size(rx_size=4096)  # 设置输入缓存去为4096个字节
        self.ser.flushInput()  # 将输入缓存去清空
        print('波特率为%s' %self.ser.baudrate)

    '''读取设备串口信息,并返回串口列表'''
    def read_serial_info(self):
        serial_info = [temp.__getitem__(0) for temp in list_ports.comports()]
        print(serial_info)
        if serial_info:
            return serial_info
        else:
            serial_info = ['No Port!']
            return serial_info

    '''当下拉框被选中时更新串口列表信息'''
    def update_serial_info(self,*args):
        self.combobox0['values'] = self.read_serial_info()

    '''将发送文本框中的内容发送出去'''
    def button_send_serial_click(self):
        '''if逻辑是判断串口有没有打开,如果打开在发送数据,如果没有打开提示打开串口'''
        if self.button_open_serial['text']  == '打开串口':
            messagebox.showwarning('警告','请先打开串口!')
        else:
            try:
                '''判断发送的内容是HEX还是ASCII,根据方式的不同发送方式也不同'''
                if self.serial_sen_hex_bzw:  # HEX方式发送
                    content = self.send_text.get(1.0, 'end').strip()
                    self.ser.write(bytes.fromhex(content))  # HEX方式发送串口数据
                else:  # ASCII方式发送
                    content = self.send_text.get(1.0, 'end').strip().encode().hex()
                    self.ser.write(bytes.fromhex(content))  # ASCII方式发送串口数据
                if content.encode() == b'':
                    messagebox.showwarning('警告', '发送内容不能为空...')
            except Exception:
                messagebox.showerror('错误','请先打开串口...')

    '''串口接收设置'''
    def text_res_config(self):
        '''创建单选框ASCII并配置单选框'''
        self.radiobutton_res_variable = IntVar()  # 设置单选框variable变量,作用是规定value的数值类型
        self.radiobutton_res_dx_acci = Radiobutton(master=self.text_res_con)
        self.radiobutton_res_dx_acci.config(
            text = 'ASCII',  # 单选框名字
            variable = self.radiobutton_res_variable,  # 设置数值类型
            value = 1,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.res_ascii_set  # 绑定单选框单击之后调用的函数
        )
        '''创建单选框HEX并配置单选框'''
        self.radiobutton_res_dx_hex = Radiobutton(master=self.text_res_con)
        self.radiobutton_res_dx_hex.config(
            text = 'HEX',  # 单选框名字
            variable = self.radiobutton_res_variable,  # 设置数值类型
            value = 2,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.res_hex_set   # 绑定单选框单击之后调用的函数
        )
        self.radiobutton_res_variable.set(1)  # 设置那个单选框初始的时候为选中状态
        self.radiobutton_res_dx_acci.grid(padx=5,row=1, column=1, sticky='w')  # 封装ASCII单选框
        self.radiobutton_res_dx_hex.grid(padx=5,row=1,column=2,sticky='e')  # 封装HEX单选框
        self.button_clear_res = Button(master=self.text_res_con,text='清空接收',command=lambda:self.clear_text(self.result_text))  # 添加清空接手区按键
        self.button_clear_res.grid(row=2,sticky='s',columnspan=5,pady=7)  # 将清空按键打包

    '''串口发送设置'''
    def text_sen_config(self):
        '''创建单选框ASCII并配置单选框'''
        self.radiobutton_sen_variable = IntVar()  # 设置单选框variable变量,作用是规定value的数值类型
        self.button_sen_dx_acci = Radiobutton(master=self.text_sen_con)
        self.button_sen_dx_acci.config(
            text = 'ASCII',  # 单选框名字
            variable = self.radiobutton_sen_variable,  # 设置数值类型
            value = 1,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.sen_ascii_set  # 绑定单选框单击之后调用的函数
        )
        '''创建单选框HEX并配置单选框'''
        self.button_sen_dx_hex = Radiobutton(master=self.text_sen_con)
        self.button_sen_dx_hex.config(
            text = 'HEX',  # 单选框名字
            variable = self.radiobutton_sen_variable,  # 设置数值类型
            value = 2,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.sen_hex_set   # 绑定单选框单击之后调用的函数
        )
        self.radiobutton_sen_variable.set(1)  # 设置那个单选框初始的时候为选中状态
        self.button_sen_dx_acci.grid(padx=5,row=1, column=1, sticky='w')  # 封装ASCII单选框
        self.button_sen_dx_hex.grid(padx=5,row=1,column=2,sticky='e')  # 封装HEX单选框
        self.button_sen_clear_res = Button(master=self.text_sen_con,text='清空发送',command=lambda:self.clear_text(self.send_text))  # 添加清空接手区按键
        self.button_sen_clear_res.grid(row=2,sticky='s',columnspan=5,pady=7)  # 将清空按键打包

    '''清空文本空间内容'''
    def clear_text(self,object):
        print('清除')
        object.config(state=NORMAL)  # 设置text对象可以操作
        object.delete(1.0,'end')  # 清空text对象内容
        # object.config(state=DISABLED)  # 设置text对象不可用

    '''设置接收框ASCII转换标志位'''
    def res_ascii_set(self):
        self.serial_res_hex_bzw = False

    '''设置接收框HEX转换标志位'''
    def res_hex_set(self):
        self.serial_res_hex_bzw = True

    '''将发送文本框中的内容以ASCII方式显示'''
    def sen_ascii_set(self):
        self.radiobutton_sen_hex_click_count = 0  # 清零
        self.radiobutton_sen_ascii_click_count += 1  # 单击一次次数+1
        self.serial_sen_hex_bzw = False  # 设置HEX标志位为False
        if not self.serial_sen_hex_bzw and self.radiobutton_sen_ascii_click_count == 1:
            self.send_text.unbind('<Key>')
            self.send_text.unbind('<BackSpace>')
            self.send_text.unbind('<Control--V>')
            self.send_text.unbind('<Control--v>')
            self.send_text.unbind('<Control--C>')
            self.send_text.unbind('<Control--c>')
            self.send_text.config(state=NORMAL)
            send_content = self.send_text.get(1.0,'end').strip()  # 读取输入文本框中的内容
            send_content = ''.join(send_content.split())  # 将16进制的文本去掉空格
            '''实现输入的数据个数不是偶数时,对不成对的数据用0进行补位'''
            if len(send_content) % 2 == 0:
                send_content = [send_content[x * 2:x * 2 + 2] for x in range(len(send_content)//2)]  # 将内容分成2个字符的数组,如:['01','02']
            else:
                temp = send_content
                send_content = [send_content[x * 2:x * 2 + 2] for x in range(len(send_content) // 2)]
                send_content.append(temp[-1].zfill(2))  # 在最后一位前面补0
                send_content = ''.join(send_content)
                send_content = [send_content[x * 2:x * 2 + 2] for x in range(len(send_content) // 2)]  # 将内容分成2个字符的数组,如:['01','02']
                print(send_content, 'send_content')
            send_content = ''.join([chr(int(x,16)) for x in send_content])  # 将上面的数组中的每个元素转换成ASCII格式
            self.clear_text(self.send_text)  # 清空输入文本框内容
            self.send_text.insert('end',send_content.encode())  # 将转换好的内容插入到文本框中

    '''将发送文本框中的内容以HEX方式显示'''
    def sen_hex_set(self):
        self.radiobutton_sen_ascii_click_count = 0  # 清零
        self.radiobutton_sen_hex_click_count += 1  # 单击一次次数+1
        self.serial_sen_hex_bzw = True  # 设置HEX标志位为True
        if self.serial_sen_hex_bzw and self.radiobutton_sen_hex_click_count == 1:
            self.send_text.bind('<Key>',self.key_callback)
            self.send_text.bind('<BackSpace>',self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--V>',self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--v>', self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--C>',self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--c>', self.key_backspace_control_v_callback)
            send_content = self.send_text.get(1.0, 'end').strip()  # 读取输入文本框中的内容
            # send_content = ''.join(send_content.split())  # 将16进制的文本去掉空格
            send_content = send_content.encode().hex()  # 将输入框中的内容转换成16进制

            send_content = ''.join([send_content[x * 2:x * 2 + 2] for x in range(len(send_content) // 2)])  # 转换成16进制的数据进行格式化
            print(send_content, '+++++++++++++++')
            self.clear_text(self.send_text)  # 清空原来的输入框内容
            self.send_text.insert('end', send_content.encode().upper())  # 将转换好的内容插入到文本框中

    '''backspace、control-v、control-c键盘事件回调函数'''
    def key_backspace_control_v_callback(self,event):
        self.send_text.config(state=NORMAL)

    '''发送框绑定键盘事件回调函数'''
    def key_callback(self,event):
        if event.char not in 'abcdefABCDEF0123456789 ':
            self.send_text.config(state=DISABLED)
        else:
            self.send_text.config(state=NORMAL)

    '''类方法:读取串口内容'''
    def serial_read_content(self):
        try:
            '''判断显示方式,self.serial_hex_bzw = True时为16进制显示,self.serial_hex_bzw=False时为ascii显示'''
            if self.serial_res_hex_bzw:
                time_str = time.strftime('[%Y-%m-%d %H:%M:%S]') + '-->HEX\r\n'
                data_res_sum = self.ser.inWaiting()  # 读取输入缓存中有多少个字节数据
                if data_res_sum:
                    text_content = self.ser.read(data_res_sum).hex()  # 将缓存中的数据读取出来
                    text_content = ' '.join([text_content[x*2:x*2+2] for x in range(len(text_content)//2)]).upper()  # 转换成16进制的数据进行格式化,带空格
                    print(text_content,'转换格式之后的文本')
            else:
                time_str = time.strftime('[%Y-%m-%d %H:%M:%S]') + '-->ASCII\r\n'
                data_res_sum = self.ser.inWaiting()  # 读取输入缓存中有多少个字节数据
                if data_res_sum:
                    text_content = self.ser.read(data_res_sum).decode(encoding='utf-8',
                                                                           errors='replace')  # 将缓存中的数据读取出来
                    print('---------------------{}'.format(data_res_sum), text_content)
            time.sleep(0.5)
            if text_content:
                # print('sssssss')
                self.result_text.config(state=NORMAL)  # 打开文本框输入
                self.result_text.tag_config('text_head_tag', foreground='blue')  # 设置插入文本样式
                self.result_text.tag_config('text_tag',foreground='green')  # 设置插入文本样式
                self.result_text.insert('end','\r\n' + time_str + '\r\n','text_head_tag')  # 在文本框中插入数据
                self.result_text.insert('end',text_content + '\r\n','text_tag')  # 在文本框中插入数据
                self.result_text.config(state=DISABLED)  # 禁止文本框输入
                self.result_text.see(END)  # 文本框总是显示最新内容
                text_content = ''
        except Exception:
            print('F**k you!')

    '''运行软件'''
    def run(self):
        self.serial_config_frame()
        self.text_res_config()
        self.text_sen_config()
        self.root.mainloop()
Beispiel #23
0
class App:
    def __init__(self):
        self.root = Tk()
        self.s = Style()
        self.fr = Frame(self.root)
        self.fr.grid(sticky='nsew')
        self.img = PhotoImage("frameBorder", data="""
R0lGODlhPwA/APcAAAAAAJWVlby8vMTExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAA/AD8A
AAj/AP8JHEiwoMGDCBMqXMiwocOHECNKnEixokWGATJq3Mixo8ePF/9pDLlw48SRJB2iVBkgpcSM
LF2ebIlRJkWaCmHafIkTYc+dEH8aFAq0IVGBAnQWjRhAwMGkS086NQg1KtOpBatafdj06dGtPrES
1AoWo9iBZMvmPIv0q1qCXam6fSswbta5dO2OxftWL1q+av22pVuS7b+0hAsKPgy47GLEiQc+bgx2
cuSwXi8ftKxZsWHIlzl3lvyZ8lbRo0WWTk06M2vVrlmjHj27c23Nt0Ovfp07cu/EvwkH7zvZ9NKM
pY0XRf40qXKbyA0zfi6TOUIBznE3ld5WaV7rCbGbNQysETtD7M5XLi9v3iH6j/Djy4/OXSH69PPz
e0Qf8r7//wAG+J9LAxRo4IEIJqjggq81CFZAADs=
""")
        self.img1 = PhotoImage("frameFocusBorder", data="""
R0lGODlhPwA/APcAAAAAAP9jR5WVlby8vMTExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAA/AD8A
AAj/AP8JHEiwoMGDCBMqXMiwocOHECNKnEixokWGAjJq3Mixo8ePF/9pDECypMmTKFOm3DhxZICQ
C0tqhJiRJMyHJDM6rPnyJs4AOjHa9AkxJ0YBPYkWDZoQqdKJQBc6fRoxKsIBNalKBDrgINakWnEK
6Grwa9iqY71OPeuQq1qwbGOmLbs2rlyyBc3aZeiWLty9B/vmrQs48NzBfwsTFExQr2LDeBsTfjyQ
8UDHlBcflpyYsmWBmDML/PwvtGjSpjOjnqx682XWnl2Dhv14defaskvTVmxbdMHevivnTh078uvb
vIfvLgw8+L/mwaH7ln5aOXLm1p2Pzq6demvjs6/vaQWqfLld8uB1m4+L3ivW9WHRp1c/tHb7q+/r
A845dv5snsyRl1tj7/Ek3kX8ZTSAf5ctyJFKEEao0kYLMpiXgx9lqOGG/VmIH4YchvhRhSFVaOKJ
KKaoIok3EeDiizDGKOOMNGpno2IBAQA7
""")
        self.s.element_create("RoundedFrame", "image", "frameBorder",
            ("focus", "frameFocusBorder"), border=16, sticky="nsew")
        self.s.layout("RoundedFrame", [("RoundedFrame", {"sticky": "nsew"})])
        self.build()

    def build(self):
        self.rbs = []
        self.rbs1 = []
        self.lF0 = lF0 = LabelFrame(self.fr, text='Widget and Themes')
        lF0.grid(row=0, column=0, sticky='nw')
        self.fr1 = fr1 = Frame(lF0)
        fr1.grid(row=0, column=0, sticky='nw')
        # create check box to select reverse selection order
        self.lF12 = lF12 = LabelFrame(fr1, text='Select Widget before Theme')
        lF12.grid(row=0, column=0, sticky='nw')
        self.ord = ord = IntVar()
        ord.set(0)
        cbut3 = Checkbutton(lF12, text='Reverse selection order', variable=ord, 
                command=self.selord)
        cbut3.grid(row=0, column=0, padx=5, pady=5)
        cbut3.state(['!selected'])
        
        # create a Combobox to choose widgets
        widget_sel = ['Button', 'Checkbutton', 'Combobox', 'Entry', 'Frame',
                      'Label', 'LabelFrame', 'Menubutton', 'Notebook', 
                      'PanedWindow', 'Progressbar', 'Radiobutton', 'Scale', 
                      'Scrollbar', 'Separator', 'Sizegrip', 'Treeview']
        ord = self.ord

        self.lf6 = LabelFrame(self.fr1, text='Select Widget', style="RoundedFrame",
                               padding=(10,1,10,10))
        self.lf6.grid(row=1, column=0, sticky='nw')
        
        self.lf6.state([("focus" if self.ord.get() == 0 else "!focus")]) 
        self.widget_value = StringVar()
        self.cb = Combobox(self.lf6, values=widget_sel,
                           textvariable=self.widget_value,
                           state= ('disabled' if self.ord.get()==1 else 'active'))
        self.cb.grid(row=0, column=0, padx=5, pady=5, sticky='nw')
        self.cb.bind('<<ComboboxSelected>>', self.enabled)

        # create a Radio Buttons to choose orientation
        fr2 = Frame(self.lF0)
        fr2.grid(row=0, column=1, sticky='nw')        
        self.lF5 = lF5 = LabelFrame(fr2, style="RoundedFrame", padding=(10,1,10,10),
            text='Orientation of \nProgressbar \nScale \nScrollbar')
        lF5.grid(row=0, column=0, padx=5, pady=5, sticky='nw')
        self.orient = StringVar()
        orientT = ['Horizontal', 'Vertical']
        for ix, val in enumerate(orientT):
            rb = Radiobutton(lF5, text=val, value=val, command=self.orient_command,
                             variable=self.orient, state='disabled')
            rb.grid(row=ix, column=0, sticky='w')
            self.rbs.append(rb)
            
        # create Radio Buttons to choose themes
        themes = {"alt":  "alt - standard", 
            "clam":  "clam - standard", "classic":  "classic - standard",
            "default":  "default - standard"}
            
        self.lF1 = LabelFrame(self.fr1, text='Select Theme', style="RoundedFrame",
                              padding=(10,1,10,10))
        self.lF1.grid(row=2, column=0, sticky='n')
        self.theme_value = StringVar()
        for ix, val in enumerate(themes):
            rb1 = Radiobutton(self.lF1, text=themes[val], value=val, 
                state='disabled', variable=self.theme_value, command=self.theme_command)
            rb1.grid(row=ix, column=0, padx=10, sticky='nw')
            self.rbs1.append(rb1)
            
    def enabled(self, event):
        # from widget selection
        self.lf6.state(["!focus"]) 
        if self.ord.get() == 0:
            if self.widget_value.get() in ('Progressbar', 'Scale', 'Scrollbar'):
                self.lF5.state(["focus"])
                for opt in self.rbs:
                    opt.state(['!disabled'])
                for opt in self.rbs1:
                    opt.state(['disabled'])
            else:
                for opt in self.rbs1:
                    opt.state(['!disabled'])
                self.lF1.state(["focus"])    
                self.lF1['text'] = 'Select Theme'
                self.theme_value.set(None)
        if self.ord.get() == 1:
            self.lf6['text'] = 'Widget'
            if self.widget_value.get() in ('Progressbar', 'Scale', 'Scrollbar'):
                self.lF5.state(["focus"])
                for opt in self.rbs:
                    opt.state(['!disabled'])
                

    def orient_command(self):
        # from orient selection
        self.lF5.state(["!focus"])
        if self.ord.get() == 0:
            try:
                for opt in self.rbs1:
                    opt.state(['!disabled'])
                self.lF1.state(["focus"])
                self.theme_value.set(None)
                self.lF1['text'] = 'Select Theme'
            except (NameError, AttributeError):
                pass
    
    def theme_command(self):
        # from theme selection
        self.s.theme_use(self.theme_value.get())
        self.lF1.state(["!focus"])
        if self.ord.get() == 0:
            self.lF1['text'] = 'Theme'
        if self.ord.get() == 1:
            self.cb.state(['!disabled'])
            self.lF1['text'] = 'Theme'
            self.lf6.state(["focus"])
            
    def selord(self):
        # from select ord
        if self.ord.get() == 0:
            self.lf6.state(["focus"]) 
            self.lF12['text'] = 'Select widget before theme'
            self.theme_value.set(None)
            self.orient.set(None)
            self.cb.set('')
            self.lF1.state(["!focus"])
            self.lF5.state(["!focus"])
        if self.ord.get() == 1:
            self.lF12['text'] = 'Select theme before widget'
            self.cb.state(['disabled'])
            for opt in self.rbs1:
                opt.state(['!disabled'])
            self.lF1.state(["focus"])
            self.theme_value.set(None)
            self.orient.set(None)
            self.cb.set('')
            self.lf6.state(["!focus"])
            self.lF5.state(["!focus"])
class DatabaseContent:

    def __init__(self, root):
        self.master = Frame(master=root)
        self.labelframe = None
        self.btn = None

        self.db_max = None
        self.db_min = None
        self.db_current = None

        self.text_field = None
        self.field_width = 40
        self.field_height = 10

        self.data_ing = DataProcessing()
        self.db = DB()
        self.config_file = './res/config/dbconfig.ini'


    def on_create_labelframe(self, name, col, row, px, py, pos):
        self.labelframe = LabelFrame(master=self.master, text=name)
        self.labelframe.grid(column=col, row=row, padx=px, pady=py, sticky=pos)

    def add_btn(self, col, row, colpad, rowpad):
        self.btn = sbutton(root=self.labelframe).get_btn()
        self.btn.configure(text='Load Content')
        self.btn.configure(command=self.on_writing_in_the_field)
        MessageTip(gui=self.btn, msg='Click here to pull the db')
        self.btn.grid(column=col, row=row, padx=rowpad, pady=colpad, sticky='W')

    def on_create_label(self, label_name, col, row, colpad, rowpad, pos):
        lab = Label(master=self.labelframe, text=label_name)
        lab.grid(column=col, row=row, padx=colpad, pady=rowpad, sticky=pos)

    def on_create_field(self, col, row, px, py, cspan):
        self.text_field = scrollT(master=self.labelframe, width=self.field_width, height=self.field_height, wrap=WORD)
        self.text_field.grid(column=col, row=row, padx=px, pady=py, columnspan=cspan)

    def on_writing_in_the_field(self):
        if self.btn['text'] == 'Load Content':
            self.btn.configure(text='Loading...')
            self.btn.configure(bg='#ffa500')

            print(self.btn['text'], self.btn['state'])

            self.write_all()

        time.sleep(.5)

        self.btn.configure(text='Load Content')
        self.btn.configure(bg='#00bfff')

    def format_date(self, d):
        return d.strftime('%Y %b %d')

    def write_all(self):
        print('Inhalt der Datenbank( aktuell ): \n')
        self.text_field.get(1.0, END)
        print('Inhalt nicht leer, wird gelöscht...')
        self.text_field.delete(1.0, END)

        connection = self.db.in_connecting(self.config_file)
        df = self.db.read_db_content(connection)
        id = df['id'].values
        strom = df['strom'].values
        datum = df['datum'].values
        m = df.min()
        print("MIN IN DF: ", m['strom'], "   date: ", m['datum'])

        print("STATISTIK:")
        self.print_db_stats(df)
        for i, s, d in zip(id, strom, datum):
            self.text_field.insert(INSERT, '   ' + str(i) + '\t\t' + str(s) + "\t    " + str(
                self.format_date(d)) + '\n')
            print(i, "\t", s, "\t", d)
        time.sleep(.2)

    def print_db_stats(self, df):
        new_df = self.data_ing.on_getting_data_from_server(df)
        min, max, current = new_df.min(), new_df.max(), self.data_ing.select_current_value(new_df)

        df_min = new_df[new_df['strom'] == min['strom']]
        df_max = new_df[new_df['strom'] == max['strom']]

        text1 = ' {} Watt \t\t Datum:   {}, den {}   {}   {}'.format(df_min['strom'][0], df_min['wochentag'][0],
                                                                     df_min['tag'][0], df_min.index[0].strftime('%b'),
                                                                     df_min['jahr'][0])

        text2 = ' {} Watt \t\t Datum:   {}, den {}   {}   {}'.format(df_max['strom'][0], df_max['wochentag'][0],
                                                                     df_max['tag'][0], df_max.index[0].strftime('%b'),
                                                                     df_max['jahr'][0])

        text3 = ' {} Watt \t\t Datum:   {}, den {}   {}   {}'.format(current['strom'][0], current['wochentag'][0],
                                                                     current['tag'][0], current.index[0].strftime('%b'),
                                                                     current['jahr'][0])
        self.db_min = Label(master=self.labelframe, text=text1)
        self.db_min.grid(column=3, row=0, padx=8, pady=8, sticky='N', columnspan=3)

        self.db_max = Label(master=self.labelframe, text=text2)
        self.db_max.grid(column=3, row=1, padx=8, pady=8, sticky='N', columnspan=3)

        self.db_current = Label(master=self.labelframe, text=text3)
        self.db_current.grid(column=3, row=2, padx=8, pady=8, sticky='N', columnspan=3)
Beispiel #25
0
    add_item_btn.grid(row=0, column=0, sticky="we", padx=10, pady=5)

    remove_item_btn = Button(button_frame, text="Remove item", command=remove_item)
    remove_item_btn.grid(row=0, column=1, sticky="we", padx=10, pady=5)

    update_item_btn = Button(button_frame, text="Update item", command=update_item)
    update_item_btn.grid(row=0, column=2, sticky="we", padx=10, pady=5)

    clear_item_btn = Button(button_frame, text="Clear Input", command=clear_input)
    clear_item_btn.grid(row=0, column=3, sticky="we", padx=10, pady=5)

    export_to_excel_btn = Button(
        button_frame, text="Export To Excel", command=export_to_excel
    )
    export_to_excel_btn.grid(row=0, column=4, sticky="we", padx=10, pady=5)


    entry_frame.grid(row=0, column=0, sticky="we", padx=10, pady=5)
    button_frame.grid(row=1, column=0, sticky="we", padx=10, pady=5)
    button_frame.grid_columnconfigure(0, weight=1)
    button_frame.grid_columnconfigure(1, weight=1)
    button_frame.grid_columnconfigure(2, weight=1)
    button_frame.grid_columnconfigure(3, weight=1)
    button_frame.grid_columnconfigure(4, weight=1)
    listing_frame.grid(row=2, column=0, sticky="we", padx=10)
    listing_frame.grid_columnconfigure(0, weight=2)

    populate_list()

    root.mainloop()
Beispiel #26
0
    def build(self):
        """widget construction"""

        lf1 = LabelFrame(self.fr0, text='rgb')
        lf1.grid(column=0, row=0, sticky='new')
        lf1.columnconfigure(1, weight=1)
        vcmdsb = root.register(sb_okay)

        self.rgbcans = []
        rgbsboxes = []
        rgbcomps = ['r', 'g', 'b', 'a']
        rgbnames = ['red  ', 'green', 'blue ', 'alpha']
        rgbvars = [self.rvar, self.gvar, self.bvar, self.avar]
        rgbhandles = [
            self.rgbhandle, self.rgbhandle, self.rgbhandle, self.ahandle
        ]
        binds = [self.checksb, self.checksb, self.checksb, self.checksba]

        for ix, comp in enumerate(rgbcomps):
            Label(lf1, text=rgbnames[ix]).grid(row=3 * ix, column=0)
            Label(lf1).grid(row=2 + 3 * ix, column=2)
            self.rgbcans.append(
                Canvas(lf1,
                       height=self.canvas_h,
                       width=self.canvas_w,
                       bd=0,
                       highlightthickness=0))
            self.rgbcans[ix].grid(row=3 * ix,
                                  column=1,
                                  sticky='ew',
                                  padx=self.sliderlength // 2)
            self.rgbcans[ix].bind("<Configure>",
                                  partial(self.resize, can=self.rgbcans[ix]))

            TtkScale(lf1,
                     self.scale_l,
                     from_=0,
                     to=255,
                     variable=rgbvars[ix],
                     orient='horizontal',
                     command=rgbhandles[ix],
                     tickinterval=20).grid(row=1 + 3 * ix,
                                           column=1,
                                           sticky='new')
            rgbsboxes.append(
                Spinbox(lf1,
                        from_=0,
                        to=255,
                        textvariable=rgbvars[ix],
                        validate='key',
                        validatecommand=(vcmdsb, '%d', '%P', '%S', 0, 255),
                        command=rgbhandles[ix],
                        width=5))
            rgbsboxes[ix].grid(row=1 + 3 * ix, column=2, sticky='nw')
            rgbsboxes[ix].bind('<KeyRelease>', binds[ix])

        lf3 = LabelFrame(self.fr0, text='colour mix')
        lf3.grid(column=1, row=0, sticky='nw')

        self.cmcan = cmcan = Canvas(lf3,
                                    width=30,
                                    height=30,
                                    bd=0,
                                    highlightthickness=0)
        cmcan.grid(column=0, row=0, sticky='n', columnspan=2)
        cmcan.grid_propagate(0)
        vdraw_gradient(self.cmcan, (255, 0, 0), alpha=255)

        cml = Label(lf3, text='hash\nvalue')
        cml.grid(column=0, row=1)

        vcmd = root.register(is_okay)
        self.en = en = Entry(lf3,
                             width=8,
                             validate='key',
                             validatecommand=(vcmd, '%i', '%P', '%S'),
                             textvariable=self.evar)
        en.grid(column=1, row=1)
        en.bind('<KeyRelease>', self.checkhash)

        lf5 = LabelFrame(lf3,
                         text='related colours')  # style='Width.Tlabelframe'
        lf5.grid(column=0, row=2, sticky='nw', columnspan=2)

        self.rcls = []
        self.rccans = []
        relateds = [0, 20, 40, 60, 80, 100]
        rtexts = ['0% Y', '20% Y', '40% Y', '60% Y', '80% Y', '100% Y']

        for ix, rel in enumerate(relateds):
            Label(lf5, text=rtexts[ix]).grid(row=1 + 2 * ix,
                                             column=0,
                                             sticky='n')
            self.rcls.append(Label(lf5))
            self.rcls[ix].grid(row=1 + 2 * ix, column=1, sticky='n')
            self.rccans.append(
                Canvas(lf5, width=30, height=30, bd=0, highlightthickness=0))
            self.rccans[ix].grid(row=2 * ix,
                                 column=0,
                                 sticky='n',
                                 columnspan=2)

        self.cccan = Canvas(lf5,
                            width=30,
                            height=30,
                            bd=0,
                            highlightthickness=0)
        self.cccan.grid(column=0, row=12, sticky='n', columnspan=2)

        self.ccla = Label(lf5, text="comp'y")
        self.ccla.grid(column=0, row=13, sticky='n')

        self.ccl = Label(lf5, text="")
        self.ccl.grid(column=1, row=13, sticky='n')

        draw_gradient(self.rgbcans[0], (0, 0, 0), (255, 0, 0),
                      width=self.canvas_w)
        draw_gradient(self.rgbcans[1], (255, 0, 0), (255, 255, 0),
                      width=self.canvas_w)
        draw_gradient(self.rgbcans[2], (255, 0, 0), (255, 0, 255),
                      width=self.canvas_w)
        draw_agradient(self.rgbcans[3], (127, 127, 127), (255, 0, 0),
                       width=self.canvas_w)

        lf4 = LabelFrame(self.fr0, text='yiq')
        lf4.grid(column=2, row=0, sticky='ew')
        lf4.columnconfigure(1, weight=1)
        vcmdyiq = root.register(yiq_okay)

        self.cans = []
        sboxes = []
        comps = ['y', 'i', 'q']
        names = ['luma', 'i hue', 'q hue']
        tkvars = [self.yvar, self.ivar, self.qvar]
        handles = [self.yhandle, self.iqhandle, self.iqhandle]
        froms = [0, -100, -100]
        ticks = [10, 20, 20]

        for ix, comp in enumerate(comps):
            Label(lf4, text=names[ix]).grid(row=3 * ix, column=0)
            Label(lf4).grid(row=2 + 3 * ix, column=2)
            self.cans.append(
                Canvas(lf4,
                       width=self.canvas_w,
                       height=self.canvas_h,
                       bd=0,
                       highlightthickness=0))
            self.cans[ix].grid(row=3 * ix,
                               column=1,
                               sticky='ew',
                               padx=self.sliderlength // 2)
            self.cans[ix].bind("<Configure>",
                               partial(self.resize_yiq, can=self.cans[ix]))
            TtkScale(lf4,
                     from_=froms[ix],
                     to=100,
                     variable=tkvars[ix],
                     orient='horizontal',
                     length=self.scale_l,
                     command=handles[ix],
                     tickinterval=ticks[ix]).grid(row=1 + 3 * ix,
                                                  column=1,
                                                  sticky='new')
            sboxes.append(
                Spinbox(lf4,
                        from_=froms[ix],
                        to=100,
                        textvariable=tkvars[ix],
                        validatecommand=(vcmdyiq, '%d', '%P', '%S', froms[ix],
                                         100),
                        validate='key',
                        command=handles[ix],
                        width=5,
                        increment=1))
            sboxes[ix].grid(row=1 + 3 * ix, column=2, sticky='nw')
            sboxes[ix].bind('<KeyRelease>', self.checksyiq)

        # assume initial setting 30,100.0,40.56 yiq
        to_colour = yiq_to_rgb(*(30, 100.0, 40.56))
        # print(self.canvas_w)
        draw_gradient(self.cans[0],
                      yiq_to_rgb(0.0, 100.0, 40.56),
                      yiq_to_rgb(100, 100, 40.56),
                      width=self.canvas_w)
        draw_gradient(self.cans[1],
                      yiq_to_rgb(30, -100.0, 40.56),
                      to_colour,
                      width=self.canvas_w)
        draw_gradient(self.cans[2],
                      yiq_to_rgb(30, 100, -100),
                      yiq_to_rgb(30, 100, 100),
                      width=self.canvas_w)

        self.related(30, 100.0, 40.56)

        self.canYiq = canYiq = Canvas(lf4, width=self.space, height=self.space)
        canYiq.grid(column=0, row=9, columnspan=3, pady=25, sticky='n')
        self.yiqGamut = PhotoImage(file='../../figures/colour_space.png')
        canYiq.create_image(0, 0, anchor='nw', image=self.yiqGamut)
        self.ring = circle(canYiq,
                           300.0,
                           210.84,
                           self.ring_radius,
                           width=self.ring_width,
                           activeoutline='#555555',
                           tags='ring')

        canYiq.bind('<Button-1>', self.move_ring)
        canYiq.tag_bind('ring', '<B1-Motion>', self.move_ring)
Beispiel #27
0
    def create_main_frame(self):
        """
        Large function creating all the basic elements of the main app frame.
        Creates the treeview and associated buttons, the scoring plugin frame
        and the go button.
        """
        # Frame for the Treeview and New/Edit/Delete buttons
        main = Frame(self, padding=(3, 3, 12, 12))
        main.rowconfigure(0, weight=1)
        main.columnconfigure(0, weight=1)
        main.columnconfigure(1, weight=0)
        main.grid(row=0, column=0, sticky="nsew")

        # ------------------------------------------------------- #
        # Frame for the Treeview and its scrollbars
        tree_frame = Frame(main, padding=(3, 3, 12, 12))
        tree_frame.rowconfigure(0, weight=1)
        tree_frame.rowconfigure(1, weight=0)
        tree_frame.columnconfigure(0, weight=1)
        tree_frame.columnconfigure(1, weight=0)
        tree_frame.grid(row=0, column=0, sticky="nsew")

        # ------------------------------------------------------- #
        # Treeview with column headings
        self.treeview = Treeview(tree_frame)
        self.treeview["columns"] = ("class", "barcodes", "variants")
        self.treeview.column("class", width=120)
        self.treeview.heading("class", text="Type")
        self.treeview.column("barcodes",
                             width=25,
                             stretch=tk.NO,
                             anchor=tk.CENTER)
        self.treeview.heading("barcodes", text="BC")
        self.treeview.column("variants",
                             width=25,
                             stretch=tk.NO,
                             anchor=tk.CENTER)
        self.treeview.heading("variants", text="V")
        self.treeview.grid(row=0, column=0, sticky="nsew")

        # Treeview context menu bindings
        self.treeview.bind("<Button-2>", self.treeview_context_menu)

        # Treeview scrollbars
        tree_ysb = tk.Scrollbar(tree_frame,
                                orient="vertical",
                                command=self.treeview.yview)
        tree_xsb = tk.Scrollbar(tree_frame,
                                orient="horizontal",
                                command=self.treeview.xview)
        tree_ysb.grid(row=0, column=1, sticky="nsw")
        tree_xsb.grid(row=1, column=0, sticky="ewn")
        self.treeview.config(yscroll=tree_ysb.set, xscroll=tree_xsb.set)

        # ------------------------------------------------------- #
        # Frame for New/Edit/Delete buttons
        button_frame = Frame(main, padding=(3, 3, 12, 12))
        button_frame.grid(row=1, column=0)
        new_button = Button(button_frame,
                            text="New...",
                            command=self.new_button_press)
        new_button.grid(row=0, column=0)
        edit_button = Button(button_frame,
                             text="Edit...",
                             command=self.edit_button_press)
        edit_button.grid(row=0, column=1)
        delete_button = Button(button_frame,
                               text="Delete",
                               command=self.delete_button_press)
        delete_button.grid(row=0, column=2)

        self.treeview_buttons = [new_button, delete_button, edit_button]

        # ------------------------------------------------------- #
        # Frame for Plugin and Analysis Options
        right_frame = Frame(main, padding=(3, 3, 12, 12))
        right_frame.rowconfigure(0, weight=1)
        right_frame.rowconfigure(1, weight=0)
        right_frame.columnconfigure(0, weight=1)
        right_frame.columnconfigure(1, weight=0)
        right_frame.grid(row=0, column=1, sticky="new")

        # ------------------------------------------------------- #
        # LabelFrame for plugin and options
        scoring_plugin = ScorerScriptsDropDown(right_frame,
                                               text="Scoring Options",
                                               padding=(3, 3, 12, 12))
        scoring_plugin.grid(row=0, column=0, sticky="new")
        self.scorer_widget = scoring_plugin

        # ------------------------------------------------------- #
        # LabelFrame for Analysis Options
        row = 0
        options_frame = LabelFrame(right_frame,
                                   text="Analysis Options",
                                   padding=(3, 3, 12, 12))
        options_frame.grid(row=1, column=0, sticky="new", pady=4)

        # force recalculate
        force_recalculate = Checkbutton(options_frame,
                                        text="Force Recalculation",
                                        variable=self.force_recalculate)
        force_recalculate.grid(column=0, row=row, sticky="w")
        row += 1

        # component outliers
        component_outliers = Checkbutton(
            options_frame,
            text="Component Outlier Statistics",
            variable=self.component_outliers,
        )
        component_outliers.grid(column=0, row=row, sticky="w")
        row += 1

        # write tsv
        tsv_requested = Checkbutton(options_frame,
                                    text="Write TSV Files",
                                    variable=self.tsv_requested)
        tsv_requested.grid(column=0, row=row, sticky="w")
        tsv_requested.invoke()
        row += 1

        # ------------------------------------------------------- #
        # Run Analysis button frame
        go_button_frame = Frame(main, padding=(3, 3, 12, 12))
        go_button_frame.grid(row=1, column=1)
        go_button = Button(go_button_frame,
                           text="Run Analysis",
                           command=self.go_button_press)
        go_button.grid(column=0, row=0)
        self.go_button = go_button
Beispiel #28
0
class ChIPSeqFrame(PipelineFrame):
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        Pipelines = ["ChIPSeq"]
        Pipeline = self.Pipeline = StringVar()
        Pipeline.set(Pipelines[0])

        om = OptionMenu(eframe,
                        Pipeline,
                        *Pipelines,
                        command=self.option_controller)
        om.config()  #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()  #bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        label.grid(row=6, column=0, columnspan=5, sticky=W, padx=10, pady=5)
        self.add_info(eframe)

    '''
    def set_data_directory( self ):
        fname = askdirectory( initialdir = USER_HOME, 
                             title="Select Data Directory")
        self.datapath.set(fname)                                    
        #count number
        self.data_count['text'] = str(
            len([fn for fn in listdir(fname) if fn.endswith(filetype) or fn.endswith('.fastq')] )
        ) 
        print( "Found", self.data_count['text'], filetype, "files!" )
    '''

    def add_info(self, parent):
        if not self.info:
            self.info = LabelFrame(parent, text='Peak Call Info')
            self.info_text = Text(
                self.info,
                width=50,
                height=8,
                #bg=projectBgColor,
                #fg=projectFgColor,
                font=("nimbus mono bold", "11"))

            self.info_save_button = Button(self.info,
                                           text="Save",
                                           command=self.writeinfo)
            self.info_load_button = Button(self.info,
                                           text="Load",
                                           command=self.readinfo)

            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.info_load_button.grid(row=5, column=5, padx=10, pady=5)
            self.info_save_button.grid(row=5, column=6, padx=10, pady=5)
            self.info_text.grid(row=1,
                                rowspan=3,
                                column=1,
                                columnspan=7,
                                padx=5,
                                pady=5)

        self.info.grid(row=7,
                       column=0,
                       columnspan=6,
                       sticky=W,
                       padx=20,
                       pady=10)

    def writeinfo(self):
        self.writepaste('peakcallinfo.csv', self.info_text)

    def readinfo(self):
        self.readpaste('peakcallinfo.csv', self.info_text)
Beispiel #29
0
    def readData_createWindow(self):
        try:
            filename = filedialog.askopenfilename()
            f = open(filename, "rb")
            self.set_header(self.header_bool)
            # f = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
            header = self.header_bool.get() == 1
            self.data = pd.read_csv(f, header=0 if header else None, sep=',')
            if not header:
                self.data.columns = [
                    'var' + str(i) for i in range(len(self.data.columns))
                ]
        except AttributeError:
            pass
        except Exception as e:
            return showerror("Error", "Data could not be loaded! Make sure the data is " \
                      + "formated in a similar way as the sample data: {}.".format(e))

        self.cols = self.data.columns
        self.setUpData()
        self.bools = [
        ]  # variables for columns: first axis: which col; second axis: what type

        height = min(5, self.data.shape[0])
        width = len(self.cols)

        # data frame
        data_frame = LabelFrame(self.master, text="Data Summary", relief=RIDGE)
        data_frame.grid(row=0,
                        column=0,
                        columnspan=5,
                        sticky="EWNS",
                        padx=15,
                        pady=7.5)
        data_size = "Data size is {} kilobytes. " \
            .format(np.round(self.data.memory_usage(deep=False).sum() / 1000, 2))
        cols_rows = "The number of columns is {} and the number of rows is {}. " \
            .format(self.data.shape[1], self.data.shape[0])
        miss_data = "The data does have missing values." if self.data.isnull().values.any() \
            else "The data does not have missing values."
        Message(data_frame, text=data_size + cols_rows + miss_data, width=335) \
            .grid(row=0, column=0, columnspan=width-1, rowspan=3, sticky='NW')
        Button(data_frame, text="Data", width=13, command=self.show_data) \
               .grid(row=0, column=4, columnspan=1, padx=4, pady=4)
        Button(data_frame, text="Description", width=13, command=self.show_description) \
               .grid(row=1, column=4, columnspan=1, padx=4, pady=0)
        Button(data_frame, text="Pair Plot", width=13, command=self.pair_plot) \
               .grid(row=2, column=4, columnspan=1, padx=4, pady=4)

        # head frame
        head_frame = LabelFrame(self.master, text="Head of data", relief=RIDGE)
        head_frame.grid(row=5,
                        column=0,
                        columnspan=5,
                        sticky="EWNS",
                        padx=15,
                        pady=7.5)

        for i in range(len(self.cols)):
            self.bools.append(
                self.initBools(5, trues=[0, 3] if i < width - 1 else [1, 3]))
        table = CustomTable(main_window=self,
                            parent=head_frame,
                            dataframe=self.data.head(),
                            editable=False,
                            width=1,
                            height=120)
        config.apply_options({'fontsize': 10}, table)
        table.show()

        # modeling frame
        model_frame = LabelFrame(self.master, text="Modeling", relief=RIDGE)
        model_frame.grid(row=height + 11,
                         column=0,
                         columnspan=5,
                         sticky="EWNS",
                         padx=15,
                         pady=7.5)

        # train / test ratio
        self.train_test_ratio = 1 / 3
        self.train_test_ratio_str = StringVar(
            self.master, value=str(np.round(self.train_test_ratio, 2)))
        Button(model_frame, text="Shuffle Data", width=13, command=self.shuffle_data) \
               .grid(row=0, column=0, columnspan=1)
        Button(model_frame, text="TrainTest Ratio", width=13, command=self.set_traintest) \
               .grid(row=0, column=2, columnspan=1)
        Label(model_frame, textvariable=self.train_test_ratio_str) \
               .grid(row=0, column=3, columnspan=1, sticky="E")

        # model selection
        ttk.Style().configure("TMenubutton", background="#E1E1E1")
        self.model_btn = Menubutton(model_frame, text="Model", width=9)
        self.set_model(self.model_btn)
        self.model_btn.grid(row=1, column=0, columnspan=1, padx=0, pady=4)
        Button(model_frame, text="Parameters", width=13, command=self.set_model_parameters) \
               .grid(row=1, column=1, columnspan=1, padx=0, pady=4)
        self.metric_btn = Menubutton(model_frame, text="Metric", width=9)
        self.set_metric(self.metric_btn)
        self.metric_btn.grid(row=1, column=2, columnspan=1, padx=0, pady=4)

        # model training
        self.score = -1
        self.score_str = StringVar(self.master, value="")
        Button(model_frame, text="Train Model", width=13, command=self.startModel) \
               .grid(row=1, column=3, columnspan=width-1)
        Label(model_frame, textvariable=self.score_str) \
               .grid(row=3, columnspan=width, sticky='W')

        # Export Frame
        export_frame = LabelFrame(self.master, text="Save", relief=RIDGE)
        export_frame.grid(row=height + 15,
                          column=0,
                          columnspan=5,
                          sticky="EWNS",
                          padx=15,
                          pady=7.5)
        Button(export_frame, text="Export Data", width=13, command=self.export_data) \
               .grid(row=0, column=0, columnspan=1, padx=4, pady=4)
        Button(export_frame, text="Export Model", width=13, command=self.export_model) \
               .grid(row=0, column=1, columnspan=1, padx=0, pady=4)
Beispiel #30
0
class scRNASeqFrame(PipelineFrame):
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        PipelineLabels = ["Initial QC", "Differential Expression"]
        Pipelines = ["scrnaQC", "scrnaDE"]

        self.label2pipeline = {k: v for k, v in zip(PipelineLabels, Pipelines)}

        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])
        om = OptionMenu(eframe,
                        PipelineLabel,
                        *PipelineLabels,
                        command=self.option_controller)
        om.config()  #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()  #bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        ######## QUALITY CONTROL/FILTERING/CLUSTERING ###############
        self.qcOptions = qcOptions = LabelFrame(
            eframe, text="QC, Filtering, and Initial Clustering")

        #algorithm selection
        self.clustAlg = clustAlg = StringVar()
        clustAlgLabel = Label(qcOptions, text="Clustering Algorithm: ")
        clustAlgDropdown = [
            "SLM (Smart Local Moving)", "Louvain (Original)",
            "Louvain (with Multilevel Refinement)"
        ]
        clustAlg.set(clustAlgDropdown[0])
        clustAlgOptMenu = OptionMenu(qcOptions, clustAlg, *clustAlgDropdown)
        clustAlgLabel.grid(row=8, column=1, sticky=W, padx=10, pady=5)
        clustAlgOptMenu.grid(row=8, column=2, sticky=W, padx=0, pady=5)

        #clustering resolutions
        self.resolution = resolution = StringVar()
        resolution.set("0.4,0.6,0.8,1.0,1.2")
        resolutionLabel = Label(
            qcOptions, text="Clustering Resolution(s): \nSeparate with commas")
        resolutionEntry = Entry(qcOptions,
                                bd=2,
                                width=25,
                                textvariable=resolution)
        resolutionLabel.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        resolutionEntry.grid(row=9, column=2, sticky=W, padx=0, pady=5)

        #annotation db: human: HPCA/BP Encode; mouse: immgen/mouseRNAseq
        self.annotDB = annotDB = StringVar()
        annotLabel = Label(qcOptions, text="Annotation database: ")
        annotHuman = [
            "Human Primary Cell Atlas", "Blueprint/ENCODE", "Monaco Immune",
            "Database of Immune Cell Expression (DICE)"
        ]
        annotMouse = ["ImmGen", "Mouse RNASeq"]
        annotDropdown = []
        genome = self.global_info.annotation.get()
        if (genome == "GRCh38"):
            annotDropdown = annotHuman.copy()
        elif (genome == "mm10"):
            annotDropdown = annotMouse.copy()
        else:
            annotDropdown.append("No genome selected")
        annotDB.set(annotDropdown[0])
        annotDB_om = OptionMenu(qcOptions, annotDB, *annotDropdown)
        annotLabel.grid(row=10, column=1, sticky=W, padx=10, pady=5)
        annotDB_om.grid(row=10, column=2, sticky=W, padx=0, pady=5)

        self.citeseq = citeseq = StringVar()
        citeseqLabel = Label(qcOptions, text="CITESeq Included: ")
        citeseqDropdown = ["Yes", "No"]
        citeseq.set(citeseqDropdown[1])
        citeseqOptMenu = OptionMenu(qcOptions, citeseq, *citeseqDropdown)
        citeseqLabel.grid(row=11, column=1, sticky=W, padx=10, pady=5)
        citeseqOptMenu.grid(row=11, column=2, sticky=W, padx=0, pady=5)

        #set groups, mostly for relabeling purposes
        self.add_info(qcOptions)  #Position 13
        # self.option_controller()

        # groups_buttonL = Label(qcOptions, text="Sample Information: ")
        # groups_button = Button(qcOptions,
        #                                     text="Set Groups",
        #                                     command = self.popup_groups )
        # groups_buttonL.grid(row=12,column=1,sticky=W,padx=10,pady=5)
        # groups_button.grid(row=12,column=2,sticky=W,padx=0,pady=5)
        #
        #
        ######### DIFFERENTIAL EXPRESSION #########
        self.deOptions = deOptions = LabelFrame(
            eframe, text="Differential Gene Expression")

        #option for which object to run DE on
        self.rdsObject = rdsObject = StringVar()
        rdsLabel = Label(deOptions,
                         text="Use the pre- or post-batch corrected data:")
        rdsDropdown = [
            "Merged (Pre-batch correction)",
            "Integrated (Post-batch correction)", "Both"
        ]
        rdsObject.set(rdsDropdown[2])
        rdsOptMenu = OptionMenu(deOptions, rdsObject, *rdsDropdown)
        rdsLabel.grid(row=8, column=1, sticky=W, padx=10, pady=5)
        rdsOptMenu.grid(row=8, column=2, sticky=W, padx=0, pady=5)

        #option for cluster resolution for DE
        self.resolutionDE = resolutionDE = StringVar()
        resolutionDE.set("0.4,0.6,0.8,1.0,1.2")
        resolutionDELabel = Label(
            deOptions,
            text=
            "Clustering Resolution: \nChoose a previous resolution or \nselect a new resolution to run"
        )
        resolutionDEEntry = Entry(deOptions,
                                  bd=2,
                                  width=25,
                                  textvariable=resolutionDE)
        resolutionDELabel.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        resolutionDEEntry.grid(row=9, column=2, sticky=W, padx=0, pady=5)

        #options for difftest
        self.testDE = testDE = StringVar()
        testDELabel = Label(
            deOptions, text="Statistical test for differential expression:")
        testDEDropdown = [
            "MAST", "DESeq2", "Likelihood Ratio", "Logistic regression",
            "Negative Binomial", "Wilcoxon", "Student's T"
        ]
        testDE.set(testDEDropdown[0])
        testDEMenu = OptionMenu(deOptions, testDE, *testDEDropdown)
        testDELabel.grid(row=10, column=1, sticky=W, padx=10, pady=5)
        testDEMenu.grid(row=10, column=2, sticky=W, padx=0, pady=5)

        #options for filters
        self.deMinPct = deMinPct = StringVar()
        deMinPctLabel = Label(
            deOptions, text="Minimum fraction of cells expressing DE genes:")
        deMinPct.set("0.1")
        deMinPctEntry = Entry(deOptions, bd=2, width=10, textvariable=deMinPct)
        deMinPctLabel.grid(row=11, column=1, sticky=W, padx=10, pady=5)
        deMinPctEntry.grid(row=11, column=2, sticky=W, padx=0, pady=5)

        self.deMinFC = deMinFC = StringVar()
        deMinFCLabel = Label(deOptions,
                             text="Minimum fold change to report DE genes:")
        deMinFC.set("0.25")
        deMinFCEntry = Entry(deOptions, bd=2, width=10, textvariable=deMinFC)
        deMinFCLabel.grid(row=12, column=1, sticky=W, padx=10, pady=5)
        deMinFCEntry.grid(row=12, column=2, sticky=W, padx=0, pady=5)

        #use groups and contrasts for differential expression, have options to create new groups
        self.om_groups = LabelFrame(deOptions, text="Sample Information")
        self.groups_button = Button(self.om_groups,
                                    text="Set Groups",
                                    command=self.popup_groups)
        self.groups_button.grid(row=5, column=5, padx=10, pady=5)
        self.contrasts_button = Button(self.om_groups,
                                       text="Set Contrasts",
                                       command=self.popup_groups)
        self.contrasts_button.grid(row=5, column=6, padx=10, pady=5)
        self.om_groups.grid(row=13,
                            column=0,
                            columnspan=6,
                            sticky=W,
                            padx=20,
                            pady=10)

        #option for merged/integrated object
        # self.integrateOption = integrateOption = StringVar()
        # integrateLabel = Label(deOptions, text="Merged or Integrated (batch corrected): ")
        # integrateDropdown = ["Merged","Integrated"]
        # integrateOption.set(integrateDropdown[0])
        # integrateOptMenu = OptionMenu(deOptions, integrateOption, *integrateDropdown)
        # integrateLabel.grid(row=9,column=1,sticky=W,padx=10,pady=5)
        # integrateOptMenu.grid(row=9,column=2,sticky=W,padx=0,pady=5)

        self.option_controller()

### SUBFUNCTION FOR CREATING GROUPS.TAB AND CLUSTERS.TAB WINDOW ######

    def add_info(self, parent):
        if not self.info:
            self.info = LabelFrame(parent, text="Sample Information")
            self.groups_button = Button(self.info,
                                        text="Set Groups",
                                        command=self.popup_groups)
            self.contrasts_button = Button(self.info,
                                           text="Set Contrasts",
                                           command=self.popup_contrasts)

            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.groups_button.grid(row=5, column=5, padx=10, pady=5)
            self.contrasts_button.grid(row=5, column=6, padx=10, pady=5)

        self.info.grid(row=13,
                       column=0,
                       columnspan=6,
                       sticky=W,
                       padx=20,
                       pady=10)

    def popup_groups(self):
        self.popup_window("Groups Information", "groups.tab")

    def popup_contrasts(self):
        self.popup_window("Contrasts Information", "contrasts.tab")

    def popup_window(self, text, filename):
        top = Toplevel()

        info = LabelFrame(top, text=text)  #"Group Information")
        info_text = Text(
            info,
            width=50,
            height=8,
            #bg=projectBgColor,
            #fg=projectFgColor,
            font=("nimbus mono bold", "11"))

        def savefunc():
            self.writepaste(filename, info_text)

        def loadfunc():
            self.readpaste(filename, info_text)

        info_save_button = Button(info, text="Save", command=savefunc)
        info_load_button = Button(info, text="Load", command=loadfunc)

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_load_button.grid(row=5, column=5, padx=10, pady=5)
        info_save_button.grid(row=5, column=6, padx=10, pady=5)
        info_text.grid(row=1,
                       rowspan=3,
                       column=1,
                       columnspan=7,
                       padx=5,
                       pady=5)

        info.grid(row=7, column=0, columnspan=6, sticky=W, padx=20, pady=10)
        top.focus_force()

    def set_count_directory(self):
        fname = askdirectory(initialdir=USER_HOME,
                             title="Select Data Directory")
        self.countpath.set(fname)

    def option_controller(self, *args, **kwargs):

        PipelineFrame.option_controller(self)

        self.Pipeline.set(self.label2pipeline[self.PipelineLabel.get()])
        print(self.Pipeline.get())

        if self.Pipeline.get() == 'scrnaQC':
            self.deOptions.grid_forget()
            self.qcOptions.grid(row=8,
                                column=0,
                                columnspan=6,
                                sticky=W,
                                padx=20,
                                pady=10)

        elif self.Pipeline.get() == 'scrnaDE':
            self.deOptions.grid(row=8,
                                column=0,
                                columnspan=4,
                                sticky=W,
                                padx=20,
                                pady=10)
            self.qcOptions.grid_forget()

    def makejson_wrapper(self, *args, **kwargs):
        self.makejson(*args, **kwargs)

    def makejson(self, *args):
        ###################################################### FROM RNASEQ.PY, NOT SURE WHAT ALL THIS DOES #############################3
        #print(args[0])
        caller = args[0]
        #global PD
        #global UnitsBak
        #global RGbak
        D = dict()
        try:
            F = open(self.workpath.get() + "/samples", "r")
            f = F.read().split("\n")
            F.close()
            for line in f:
                L = line.split()
                a = L.pop(0)
                D[a] = L
                samples = D
        except:
            samples = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/pairs", "r")
            f = F.read().split()
            F.close()
            for i in range(0, len(f), 2):
                #            a=f[i].split(".")[0]
                #            b=f[i+1].split(".")[0]
                a = f[i]
                b = f[i + 1]

                D[a + "+" + b] = [a, b]

            pairs = D
        except:
            pairs = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/contrasts.tab", "r")
            #        f=F.read().split('\n')
            #        F.close()
            #        D["rsamps"]=f[0].split()
            #        D["rgroups"]=f[1].split()
            #        D["rcontrasts"]=f[2].split()
            #        D["rlabels"]=f[3].split()
            f = F.readlines()
            F.close()
            ##        sampl=[]
            ##        grp=[]
            cont = []
            ##        lbl=[]
            for x in f:
                if len(x.split()) == 2:
                    cont.append(x.split()[0])
                    cont.append(x.split()[1])
            D["rcontrasts"] = cont
            #        contrasts["rcontrasts"]=cont
            contrasts = D
        except:
            contrasts = {"rcontrasts": "na"}
    ##        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
    ##------
        D = dict()
        try:
            F = open(self.workpath.get() + "/groups.tab", "r")
            f = F.readlines()
            F.close()
            sampl = []
            grp = []
            #        cont=[]
            lbl = []
            for x in f:
                #           if len(x.split()) == 4 or len(x.split()) == 3:
                if len(x.split()) == 3:
                    sampl.append(x.split()[0])
                    grp.append(x.split()[1])
                    lbl.append(x.split()[2])
            D["rsamps"] = sampl
            D["rgroups"] = grp
            D["rlabels"] = lbl
            #        D["rcontrasts"]="na"
            #        contrasts=D
            groups = D
        except:
            #        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
            groups = {"rsamps": "na", "rgroups": "na", "rlabels": "na"}

    ##------
        D = dict()
        FT = filetype  #.get()
        #    p = Popen("ls "+workpath.get()+"/*."+FT, shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
        p = Popen("find " + self.workpath.get() +
                  " -maxdepth 1 -type l -printf '%f\n' ",
                  shell=True,
                  stdin=PIPE,
                  stdout=PIPE,
                  stderr=DEVNULL,
                  close_fds=True)
        a = p.stdout.read().decode(encoding='UTF-8').split("\n")

        RG = dict()
        b = a.pop()
        #    tkinter.messagebox.showerror("",a)
        #    if freezeunits.get()=="no":
        for i in a:

            key = re.sub(".realign", "", i.split("/")[-1])
            key = re.sub(".bai", "", key)
            key = re.sub(".bam", "", key)
            key = re.sub(".sam", "", key)
            key = re.sub(".recal", "", key)
            key = re.sub(".dedup", "", key)
            key = re.sub(".sorted", "", key)
            key = re.sub(".fin", "", key)
            key = re.sub("\.R[12]", "", key)
            key = re.sub("_R[12]", "", key)
            key = re.sub(".fastq", "", key)
            key = re.sub(".gz", "", key)
            #        key=re.sub("[\._](R[12]\.)*"+FT+"$","",i.split("/")[-1])
            #        key=re.sub(".R[12]."+FT+"$","",i.split("/")[-1])
            #        key=re.sub("([._]R[12][._])*([fin|sorted|dedup|recal|realign])*\.{0}$".format(FT),"",i.split("/")[-1])
            D[key] = key
            RG[key] = {
                'rgsm': key,
                'rglb': 'na',
                'rgpu': 'na',
                'rgpl': 'ILLUMINA',
                'rgcn': 'na'
            }
        units = D
        UnitsBak = D

        try:
            F = open(self.workpath.get() + "/rg.tab", "r")
            f = F.read().splitlines()
            F.close()
            for theLine in f:
                if not re.match("^ID", theLine):
                    (rgid, rgsm, rglb, rgpl, rgpu, rgcn) = theLine.split("\t")
                    RG[rgid] = {
                        'rgsm': rgsm,
                        'rglb': rglb,
                        'rgpu': rgpu,
                        'rgpl': rgpl,
                        'rgcn': rgcn
                    }
        except:
            pass

        RGbak = RG
        #     else:
        #         units=UnitsBak
        #         RG=RGbak
        # ###########################################################################################################################

        PD = dict()

        smparams = []

        algorithmDict = {
            "Louvain (Original)": 1,
            "Louvain (with Multilevel Refinement)": 2,
            "SLM (Smart Local Moving)": 3
        }
        algorithm = algorithmDict[self.clustAlg.get()]

        annotationDict = {
            "Human Primary Cell Atlas": "HPCA",
            "Blueprint/ENCODE": "BP_encode",
            "Monaco Immune": "monaco",
            "Database of Immune Cell Expression (DICE)": "dice",
            "ImmGen": "immgen",
            "Mouse RNASeq": "mouseRNAseq"
        }
        annotation = annotationDict[self.annotDB.get()]

        resolutionStr = self.resolution.get()
        resolutionStr = re.sub("\s", ",", resolutionStr)  #remove whitespaces
        resolutionStr = re.sub("[,]+", ",",
                               resolutionStr)  #remove multiple commas

        rdsDict = {
            "Merged (Pre-batch correction)": "merged",
            "Integrated (Post-batch correction)": "integrated",
            "Both": "both"
        }
        rdsSelect = rdsDict[self.rdsObject.get()]

        deResolutionStr = self.resolutionDE.get()
        deResolutionStr = re.sub("\s", ",",
                                 deResolutionStr)  #remove whitespace
        deResolutionStr = re.sub("[,]+", ",",
                                 deResolutionStr)  #remove multiple commas

        deTestDict = {
            "MAST": "MAST",
            "DESeq2": "DESeq2",
            "Likelihood Ratio": "bimod",
            "Logistic regression": "LR",
            "Negative Binomial": "negbinom",
            "Wilcoxon": "wilcox",
            "Student's T": "t"
        }
        testDESelect = deTestDict[self.testDE.get()]

        for i in range(len(self.parameters)):

            if cp[i].var.get() == "1":
                smparams.append(parameters[i])

        AD = eval(
            open(join(PIPELINER_HOME,
                      self.annotation.get() + ".json"), "r").read())
        gi = self.global_info
        species = ""
        if gi.annotation.get() == "GRCh38":
            species = "human"
        elif gi.annotation.get() == "mm10":
            species = "mouse"
        PD = {
            'project': {
                'pfamily': gi.pfamily.get(),
                'units': units,
                'samples': samples,
                'pairs': pairs,
                'id': gi.eprojectid.get(),
                'pi': gi.epi.get(),
                'organism': gi.eorganism.get(),
                'analyst': gi.eanalyst.get(),
                'poc': gi.epoc.get(),
                'pipeline': self.Pipeline.get(),
                'version': "4.0",
                'annotation': gi.annotation.get(),
                'datapath': self.datapath.get(),
                'targetspath': self.targetspath.get(),
                'filetype': filetype,
                'binset': "standard-bin",
                'username': gi.euser.get(),
                'flowcellid': gi.eflowcell.get(),
                'platform': gi.eplatform.get(),
                'custom': customRules,
                'efiletype': efiletype,
                'workpath': self.workpath.get(),
                'batchsize': batchsize,
                "smparams": smparams,
                "rgid": RG,
                "cluster": "cluster_medium.json",
                "description": gi.description.get('1.0', END),
                "technique": gi.technique.get(),
                "CLUSTALG": algorithm,
                "ANNOTDB": annotation,
                "CLUSTRESOLUTION": resolutionStr,
                #               "INTEGRATEDE": self.integrateOption.get(),
                "SPECIES": species,
                "CITESEQ": self.citeseq.get(),
                # "CRID": self.scrCRID.get(),
                # "EXPECTED": self.scrExpected.get(),
                # "COUNTSPATH": self.countpath.get(),
                # "MATTYPE": self.mattype.get(),
                # "DOCYCLEREGRESS": self.docycleregress.get(),
                # "RESOLUTION": self.scrRes.get(),
                # "PCS": self.scrPCs.get(),
                "FILEDE": rdsSelect,
                "CLUSTERDE": deResolutionStr,
                "TESTDE": testDESelect,
                "DEMINPCT": self.deMinPct.get(),
                "DEMINFC": self.deMinFC.get(),
                "contrasts": contrasts,
                "groups": groups
            }
        }

        J = json.dumps(PD, sort_keys=True, indent=4, ensure_ascii=True)
        gi.jsonconf.delete("1.0", END)
        gi.jsonconf.insert(INSERT, J)
        self.saveproject(gi.jsonconf.get("1.0", END))
Beispiel #31
0
class ExomeSeqFrame(PipelineFrame):
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.pairs = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        PipelineLabels = [
            "Initial QC", "Germline", 'Somatic Tumor-Normal',
            'Somatic Tumor-Only'
        ]
        Pipelines = [
            "initialqc", "exomeseq-germline", "exomeseq-somatic",
            "exomeseq-somatic-tumoronly"
        ]
        self.label2pipeline = {k: v for k, v in zip(PipelineLabels, Pipelines)}

        Pipeline = self.Pipeline = StringVar()
        PipelineLabel = self.PipelineLabel = StringVar()
        self.Pipeline = StringVar()

        PipelineLabel.set(PipelineLabels[0])

        om = OptionMenu(eframe,
                        PipelineLabel,
                        *PipelineLabels,
                        command=self.option_controller)
        #om.config()#bg = widgetBgColor,fg=widgetFgColor)
        #om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        targetsL = Label(eframe, text="Target Capture Kit")
        #,fg=textLightColor,bg=baseColor)
        targetsL.grid(row=5, column=0, sticky=W, padx=10, pady=5)
        targetsE = Entry(eframe, textvariable=self.targetspath, width=50)

        label_ref_text = "By default, the path to the Agilent SureSelect V7 targets file is filled in here"

        if self.genome == "hg19":
            self.targetspath.set(
                "/data/CCBR_Pipeliner/db/PipeDB/lib/Agilent_SSv7_allExons_hg19.bed"
            )
        elif self.genome == "hg38":
            self.targetspath.set(
                "/data/CCBR_Pipeliner/db/PipeDB/lib/Agilent_SSv7_allExons_hg38.bed"
            )
        else:
            self.targetspath.set(
                "/data/CCBR_Pipeliner/db/PipeDB/lib/SureSelect_mm10.bed")
            label_ref_text = "By default, the path to the Agilent SureSelect Mouse All Exon V1 targets file is filled in here"

        targetsE.grid(row=5, column=1, columnspan=6, sticky=W, padx=10, pady=5)
        self.targetspath.trace(
            'w', lambda a, b, c, x="targetspath": self.makejson(x))

        label = Label(eframe, text=label_ref_text)

        label.grid(row=6, column=0, columnspan=5, sticky=W, padx=10, pady=5)

    def option_controller(self, *args, **kwargs):
        PipelineFrame.option_controller(self)
        self.Pipeline.set(self.label2pipeline[self.PipelineLabel.get()])
        print(self.Pipeline.get())

        if self.Pipeline.get() == 'exomeseq-somatic':
            self.add_pairs(self.eframe)
            #self.dry_button.config( state="disabled" )
        elif self.Pipeline.get() != 'exomeseq-somatic':
            self.del_pairs(self.eframe)
            #if self.workpath.get() :
            #    self.dry_button.config( state='active' )

    def add_pairs(self, parent):
        if not self.pairs:
            self.pairs = LabelFrame(parent, text='Pairs')
            self.pairs_text = Text(
                self.pairs,
                width=50,
                height=8,
                #bg=projectBgColor,
                #fg=projectFgColor,
                font=("nimbus mono bold", "11"))

            self.pairs_save_button = Button(self.pairs,
                                            text="Save",
                                            command=self.writepair)

            self.pairs_load_button = Button(self.pairs,
                                            text="Load",
                                            command=self.readpair)

            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.pairs_load_button.grid(row=5, column=5, padx=10, pady=5)
            self.pairs_save_button.grid(row=5, column=6, padx=10, pady=5)
            self.pairs_text.grid(row=1,
                                 rowspan=3,
                                 column=1,
                                 columnspan=7,
                                 padx=5,
                                 pady=5)

        self.pairs.grid(row=7,
                        column=0,
                        columnspan=6,
                        sticky=W,
                        padx=20,
                        pady=10)

    def del_pairs(self, parent):
        if self.pairs:
            self.pairs.grid_forget()

    def writepair(self):
        self.writepaste('pairs', self.pairs_text)
        #self.dry_button.config( state='active' )

    def readpair(self):
        self.readpaste('pairs', self.pairs_text)
Beispiel #32
0
class MiRSeqFrame( PipelineFrame ) :
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
        Pipelines=["CAPmirseq-plus"]
        Pipeline = self.Pipeline = StringVar()
        Pipeline.set(Pipelines[0])
        
        om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller)
        om.config()#bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)
     
        self.add_info( eframe )
        
    
    def add_info( self, parent ) :
        if not self.info :
            self.info = LabelFrame(parent, text="Sample Information")
            self.groups_button = Button(self.info, 
                                            text="Set Groups", 
                                            command = self.popup_groups )
            self.contrasts_button = Button(self.info,
                                            text="Set Contrasts",
                                            command = self.popup_contrasts )
            
            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.groups_button.grid( row=5, column=5, padx=10, pady=5 )
            self.contrasts_button.grid( row=5, column=6, padx=10, pady=5 )
            

        self.info.grid(row=10,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
   
  
    def popup_groups( self ) :
        self.popup_window( "Groups Information", "groups.tab" )
        
    def popup_contrasts( self ) :
        self.popup_window( "Contrasts Information", "contrasts.tab" )
 
    def popup_window( self, text, filename ) :
        top = Toplevel()
  
        info = LabelFrame(top, text=text )#"Group Information")
        info_text = Text(info,
                              width=50,
                              height=8,
                              #bg=projectBgColor,
                              #fg=projectFgColor,
                              font=("nimbus mono bold","11")
                             )
        
        def savefunc() :
            self.writepaste( filename, info_text ) 
        
        def loadfunc() :
            self.readpaste( filename, info_text ) 
        
        info_save_button = Button(info, 
                                  text="Save", 
                                  command = savefunc )
        info_load_button = Button(info,
                                  text="Load",
                                  command = loadfunc )

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_load_button.grid( row=5, column=5, padx=10, pady=5 )
        info_save_button.grid( row=5, column=6, padx=10, pady=5 )
        info_text.grid(row=1,  rowspan=3, 
                       column=1,  columnspan=7,
                       padx=5, pady=5 )

        info.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        top.focus_force()
 
    def makejson(self, *args):
        #print(args[0])
        caller=args[0]
        #global PD
        #global UnitsBak
        #global RGbak
        D=dict()
        try:
            F=open(self.workpath.get()+"/samples","r")
            f=F.read().split("\n")
            F.close()
            for line in f:
                L=line.split()
                a=L.pop(0)
                D[a]=L
                samples=D
        except:
            samples={"na":"na"}
            
        D=dict()
        try:
            F=open(self.workpath.get()+"/pairs","r")
            f=F.read().split()
            F.close()
            for i in range(0,len(f),2):
    #            a=f[i].split(".")[0]
    #            b=f[i+1].split(".")[0]
                a=f[i]
                b=f[i+1]

                D[a+"+"+b]=[a,b]

            pairs=D
        except:
            pairs={"na":"na"}   

        D=dict()
        try:
            F=open(self.workpath.get()+"/contrasts.tab","r")
    #        f=F.read().split('\n')
    #        F.close()
    #        D["rsamps"]=f[0].split()
    #        D["rgroups"]=f[1].split()
    #        D["rcontrasts"]=f[2].split()
    #        D["rlabels"]=f[3].split()        
            f=F.readlines()
            F.close()
    ##        sampl=[]
    ##        grp=[]
            cont=[]
    ##        lbl=[]
            for x in f:
                  if len(x.split()) == 2:
                     cont.append(x.split()[0])
                     cont.append(x.split()[1])
            D["rcontrasts"]=cont
    #        contrasts["rcontrasts"]=cont
            contrasts=D
        except:
            contrasts={"rcontrasts":"na"}
    ##        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}   
    ##------
        D=dict()
        try:
            F=open(self.workpath.get()+"/groups.tab","r")
            f=F.readlines()
            F.close()
            sampl=[]
            grp=[]
    #        cont=[]
            lbl=[]
            for x in f:
    #           if len(x.split()) == 4 or len(x.split()) == 3:
                if len(x.split()) == 3:  
                    sampl.append(x.split()[0])
                    grp.append(x.split()[1])
                    lbl.append(x.split()[2])
            D["rsamps"]=sampl
            D["rgroups"]=grp
            D["rlabels"]=lbl
    #        D["rcontrasts"]="na"
    #        contrasts=D
            groups=D
        except:
    #        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
            groups={"rsamps":"na","rgroups":"na","rlabels":"na"}          
    ##------   
        D=dict() 
        FT = filetype#.get()
    #    p = Popen("ls "+workpath.get()+"/*."+FT, shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
        p = Popen("find "+self.workpath.get()+" -maxdepth 1 -type l -printf '%f\n' ", shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
        a = p.stdout.read().decode(encoding='UTF-8').split("\n")

        RG=dict()   
        b=a.pop()
    #    tkinter.messagebox.showerror("",a)
    #    if freezeunits.get()=="no":
        for i in a:

            key=re.sub(".realign","",i.split("/")[-1])
            key=re.sub(".bai","",key)
            key=re.sub(".bam","",key)
            key=re.sub(".sam","",key)        
            key=re.sub(".recal","",key)
            key=re.sub(".dedup","",key)
            key=re.sub(".sorted","",key)
            key=re.sub(".fin","",key)
            key=re.sub(".R[12]","",key)
            key=re.sub("_R[12]","",key)
            key=re.sub(".fastq","",key)
            key=re.sub(".gz","",key)                                
    #        key=re.sub("[\._](R[12]\.)*"+FT+"$","",i.split("/")[-1])        
    #        key=re.sub(".R[12]."+FT+"$","",i.split("/")[-1])
    #        key=re.sub("([._]R[12][._])*([fin|sorted|dedup|recal|realign])*\.{0}$".format(FT),"",i.split("/")[-1])
            D[key]=key
            RG[key]={'rgsm':key,'rglb':'na','rgpu':'na','rgpl':'ILLUMINA','rgcn':'na'}
        units=D
        UnitsBak=D

        try:
            F=open(self.workpath.get()+"/rg.tab","r")
            f=F.read().splitlines()
            F.close()
            for theLine in f:
                if not re.match("^ID",theLine):
                    (rgid,rgsm,rglb,rgpl,rgpu,rgcn)=theLine.split("\t")
                    RG[rgid]={'rgsm':rgsm,'rglb':rglb,'rgpu':rgpu,'rgpl':rgpl,'rgcn':rgcn}
        except:
            pass
        
        RGbak=RG
    #     else:
    #         units=UnitsBak
    #         RG=RGbak
    # 
        PD=dict()

        smparams=[]

        for i in range(len(self.parameters)):

            if cp[i].var.get()=="1":
                smparams.append(parameters[i])
                
        AD=eval( open( join(PIPELINER_HOME, 
                            self.annotation.get()+".json"
                           ), "r"
                     ).read()
               )
        
        SD=AD['references']['rnaseq']['STARDIR']
    #    tkinter.messagebox.showinfo("initLock","SD={0}".format(SD))
        gi = self.global_info 
        PD={
            'project': {
                'pfamily': gi.pfamily.get(),
                'units': units, 
                'samples': samples, 
                'pairs': pairs,
                'id': gi.eprojectid.get(), 
                'pi': gi.epi.get(), 
                'organism': gi.eorganism.get(), 
                'analyst': gi.eanalyst.get(), 
                'poc': gi.epoc.get(), 
                'pipeline': self.Pipeline.get(), 
                'version':"1.0", 
                'annotation': gi.annotation.get(), 
                'datapath': self.datapath.get(), 
                'targetspath': self.targetspath.get(), 
                'filetype': filetype , 
                'binset': "standard-bin", 
                'username': gi.euser.get(), 
                'flowcellid': gi.eflowcell.get(), 
                'platform': gi.eplatform.get(), 
                'custom': customRules, 
                'efiletype': efiletype, 
                'workpath': self.workpath.get(), 
                'batchsize': batchsize, 
                "smparams": smparams, 
                "rgid": RG, 
                "cluster": "cluster_medium.json", 
                "description": gi.description.get('1.0',END), 
                "technique" : gi.technique.get(), 
                "TRIM": "yes", 
                "groups": groups,
                "contrasts": contrasts,
             }
        } 
        
        J=json.dumps(PD, sort_keys = True, indent = 4, ensure_ascii=True)
        gi.jsonconf.delete("1.0", END)    
        gi.jsonconf.insert(INSERT, J)
        self.saveproject(gi.jsonconf.get("1.0",END))
Beispiel #33
0
    def build(self):
        """widget construction

        Parameters
        ----------
        None

        Results
        -------
        None
        """

        fr4 = LabelFrame(self.fr0, text='hsv')
        fr4.grid(column=2, row=0)

        hl = Label(fr4, text='hue  ')
        hl.grid(column=0, row=0, sticky='s')

        self.hcan = Canvas(fr4,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.hcan.grid(column=1, row=0, sticky='s')

        hsc = TtkScale(fr4,
                       from_=0,
                       to=360,
                       variable=self.hvar,
                       orient='horizontal',
                       length=self.scale_l,
                       command=self.hhandle,
                       tickinterval=30)
        hsc.grid(column=1, row=1, sticky='nw')

        vcmdsb = root.register(sb_okay)

        hsb = Spinbox(fr4,
                      from_=0,
                      to=360,
                      textvariable=self.hvar,
                      validate='key',
                      validatecommand=(vcmdsb, '%P', '%S', 360),
                      command=self.hhandle,
                      width=5)
        hsb.grid(column=2, row=1, sticky='nw')
        hsb.bind('<KeyRelease>', self.checksbh)

        hel = Label(fr4, height=1)
        hel.grid(column=2, row=2)

        sl = Label(fr4, text='sat  ')
        sl.grid(column=0, row=3)

        self.scan = Canvas(fr4,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.scan.grid(column=1, row=3, sticky='s')

        ssc = TtkScale(fr4,
                       from_=0,
                       to=100,
                       variable=self.svar,
                       orient='horizontal',
                       length=self.scale_l,
                       command=self.shandle,
                       tickinterval=10)
        ssc.grid(column=1, row=4, sticky='nw')

        ssb = Spinbox(fr4,
                      from_=0,
                      to=100,
                      textvariable=self.svar,
                      validate='key',
                      validatecommand=(vcmdsb, '%P', '%S', 100),
                      command=self.shandle,
                      width=5)
        ssb.grid(column=2, row=4, sticky='nw')
        ssb.bind('<KeyRelease>', self.checksb100)

        sel = Label(fr4, height=1)
        sel.grid(column=2, row=5)

        vl = Label(fr4, text='value')
        vl.grid(column=0, row=6, sticky='s')

        self.vcan = Canvas(fr4,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.vcan.grid(column=1, row=6, sticky='n')

        vsc = TtkScale(fr4,
                       from_=0,
                       to=100,
                       variable=self.vvar,
                       orient='horizontal',
                       length=self.scale_l,
                       command=self.vhandle,
                       tickinterval=10)
        vsc.grid(column=1, row=7, sticky='nw')

        vsb = Spinbox(fr4,
                      from_=0,
                      to=100,
                      textvariable=self.vvar,
                      validate='key',
                      validatecommand=(vcmdsb, '%P', '%S', 100),
                      command=self.vhandle,
                      width=5)
        vsb.grid(column=2, row=7, sticky='nw')
        vsb.bind('<KeyRelease>', self.checksb100)

        vel = Label(fr4, height=1)
        vel.grid(column=2, row=8)

        # assume initial setting 0,100,100 hsv
        to_colour = hsv_to_rgb(*(0, 100, 100))

        hue_gradient(self.hcan, width=self.canvas_w)
        draw_gradient(self.scan, (255, 255, 255),
                      to_colour,
                      width=self.canvas_w)
        draw_gradient(self.vcan, (0, 0, 0), to_colour, width=self.canvas_w)
Beispiel #34
0
class MiRSeqFrame(PipelineFrame):
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        Pipelines = ["CAPmirseq-plus"]
        Pipeline = self.Pipeline = StringVar()
        Pipeline.set(Pipelines[0])

        om = OptionMenu(eframe,
                        Pipeline,
                        *Pipelines,
                        command=self.option_controller)
        om.config()  #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()  #bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        self.add_info(eframe)

    def add_info(self, parent):
        if not self.info:
            self.info = LabelFrame(parent, text="Sample Information")
            self.groups_button = Button(self.info,
                                        text="Set Groups",
                                        command=self.popup_groups)
            self.contrasts_button = Button(self.info,
                                           text="Set Contrasts",
                                           command=self.popup_contrasts)

            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.groups_button.grid(row=5, column=5, padx=10, pady=5)
            self.contrasts_button.grid(row=5, column=6, padx=10, pady=5)

        self.info.grid(row=10,
                       column=0,
                       columnspan=6,
                       sticky=W,
                       padx=20,
                       pady=10)

    def popup_groups(self):
        self.popup_window("Groups Information", "groups.tab")

    def popup_contrasts(self):
        self.popup_window("Contrasts Information", "contrasts.tab")

    def popup_window(self, text, filename):
        top = Toplevel()

        info = LabelFrame(top, text=text)  #"Group Information")
        info_text = Text(
            info,
            width=50,
            height=8,
            #bg=projectBgColor,
            #fg=projectFgColor,
            font=("nimbus mono bold", "11"))

        def savefunc():
            self.writepaste(filename, info_text)

        def loadfunc():
            self.readpaste(filename, info_text)

        info_save_button = Button(info, text="Save", command=savefunc)
        info_load_button = Button(info, text="Load", command=loadfunc)

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_load_button.grid(row=5, column=5, padx=10, pady=5)
        info_save_button.grid(row=5, column=6, padx=10, pady=5)
        info_text.grid(row=1,
                       rowspan=3,
                       column=1,
                       columnspan=7,
                       padx=5,
                       pady=5)

        info.grid(row=7, column=0, columnspan=6, sticky=W, padx=20, pady=10)
        top.focus_force()

    def makejson(self, *args):
        #print(args[0])
        caller = args[0]
        #global PD
        #global UnitsBak
        #global RGbak
        D = dict()
        try:
            F = open(self.workpath.get() + "/samples", "r")
            f = F.read().split("\n")
            F.close()
            for line in f:
                L = line.split()
                a = L.pop(0)
                D[a] = L
                samples = D
        except:
            samples = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/pairs", "r")
            f = F.read().split()
            F.close()
            for i in range(0, len(f), 2):
                #            a=f[i].split(".")[0]
                #            b=f[i+1].split(".")[0]
                a = f[i]
                b = f[i + 1]

                D[a + "+" + b] = [a, b]

            pairs = D
        except:
            pairs = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/contrasts.tab", "r")
            #        f=F.read().split('\n')
            #        F.close()
            #        D["rsamps"]=f[0].split()
            #        D["rgroups"]=f[1].split()
            #        D["rcontrasts"]=f[2].split()
            #        D["rlabels"]=f[3].split()
            f = F.readlines()
            F.close()
            ##        sampl=[]
            ##        grp=[]
            cont = []
            ##        lbl=[]
            for x in f:
                if len(x.split()) == 2:
                    cont.append(x.split()[0])
                    cont.append(x.split()[1])
            D["rcontrasts"] = cont
            #        contrasts["rcontrasts"]=cont
            contrasts = D
        except:
            contrasts = {"rcontrasts": "na"}
    ##        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
    ##------
        D = dict()
        try:
            F = open(self.workpath.get() + "/groups.tab", "r")
            f = F.readlines()
            F.close()
            sampl = []
            grp = []
            #        cont=[]
            lbl = []
            for x in f:
                #           if len(x.split()) == 4 or len(x.split()) == 3:
                if len(x.split()) == 3:
                    sampl.append(x.split()[0])
                    grp.append(x.split()[1])
                    lbl.append(x.split()[2])
            D["rsamps"] = sampl
            D["rgroups"] = grp
            D["rlabels"] = lbl
            #        D["rcontrasts"]="na"
            #        contrasts=D
            groups = D
        except:
            #        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
            groups = {"rsamps": "na", "rgroups": "na", "rlabels": "na"}

    ##------
        D = dict()
        FT = filetype  #.get()
        #    p = Popen("ls "+workpath.get()+"/*."+FT, shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
        p = Popen("find " + self.workpath.get() +
                  " -maxdepth 1 -type l -printf '%f\n' ",
                  shell=True,
                  stdin=PIPE,
                  stdout=PIPE,
                  stderr=DEVNULL,
                  close_fds=True)
        a = p.stdout.read().decode(encoding='UTF-8').split("\n")

        RG = dict()
        b = a.pop()
        #    tkinter.messagebox.showerror("",a)
        #    if freezeunits.get()=="no":
        for i in a:

            key = re.sub(".realign", "", i.split("/")[-1])
            key = re.sub(".bai", "", key)
            key = re.sub(".bam", "", key)
            key = re.sub(".sam", "", key)
            key = re.sub(".recal", "", key)
            key = re.sub(".dedup", "", key)
            key = re.sub(".sorted", "", key)
            key = re.sub(".fin", "", key)
            key = re.sub("\.R[12]", "", key)
            key = re.sub("_R[12]", "", key)
            key = re.sub(".fastq", "", key)
            key = re.sub(".gz", "", key)
            #        key=re.sub("[\._](R[12]\.)*"+FT+"$","",i.split("/")[-1])
            #        key=re.sub(".R[12]."+FT+"$","",i.split("/")[-1])
            #        key=re.sub("([._]R[12][._])*([fin|sorted|dedup|recal|realign])*\.{0}$".format(FT),"",i.split("/")[-1])
            D[key] = key
            RG[key] = {
                'rgsm': key,
                'rglb': 'na',
                'rgpu': 'na',
                'rgpl': 'ILLUMINA',
                'rgcn': 'na'
            }
        units = D
        UnitsBak = D

        try:
            F = open(self.workpath.get() + "/rg.tab", "r")
            f = F.read().splitlines()
            F.close()
            for theLine in f:
                if not re.match("^ID", theLine):
                    (rgid, rgsm, rglb, rgpl, rgpu, rgcn) = theLine.split("\t")
                    RG[rgid] = {
                        'rgsm': rgsm,
                        'rglb': rglb,
                        'rgpu': rgpu,
                        'rgpl': rgpl,
                        'rgcn': rgcn
                    }
        except:
            pass

        RGbak = RG
        #     else:
        #         units=UnitsBak
        #         RG=RGbak
        #
        PD = dict()

        smparams = []

        for i in range(len(self.parameters)):

            if cp[i].var.get() == "1":
                smparams.append(parameters[i])

        AD = eval(
            open(join(PIPELINER_HOME,
                      self.annotation.get() + ".json"), "r").read())

        SD = AD['references']['rnaseq']['STARDIR']
        #    tkinter.messagebox.showinfo("initLock","SD={0}".format(SD))
        gi = self.global_info
        PD = {
            'project': {
                'pfamily': gi.pfamily.get(),
                'units': units,
                'samples': samples,
                'pairs': pairs,
                'id': gi.eprojectid.get(),
                'pi': gi.epi.get(),
                'organism': gi.eorganism.get(),
                'analyst': gi.eanalyst.get(),
                'poc': gi.epoc.get(),
                'pipeline': self.Pipeline.get(),
                'version': "1.0",
                'annotation': gi.annotation.get(),
                'datapath': self.datapath.get(),
                'targetspath': self.targetspath.get(),
                'filetype': filetype,
                'binset': "standard-bin",
                'username': gi.euser.get(),
                'flowcellid': gi.eflowcell.get(),
                'platform': gi.eplatform.get(),
                'custom': customRules,
                'efiletype': efiletype,
                'workpath': self.workpath.get(),
                'batchsize': batchsize,
                "smparams": smparams,
                "rgid": RG,
                "cluster": "cluster_medium.json",
                "description": gi.description.get('1.0', END),
                "technique": gi.technique.get(),
                "TRIM": "yes",
                "groups": groups,
                "contrasts": contrasts,
            }
        }

        J = json.dumps(PD, sort_keys=True, indent=4, ensure_ascii=True)
        gi.jsonconf.delete("1.0", END)
        gi.jsonconf.insert(INSERT, J)
        self.saveproject(gi.jsonconf.get("1.0", END))
Beispiel #35
0
    def popup_window_peakinfo( self, text, filename ) :
        
        NA = 'N/A'
        selections = [fn.split('.R1.fastq.gz')[0] 
                     for fn in self.datafiles if fn.endswith( ".R1.fastq.gz" )]
        
        ################################
        #check availablity of the files before moving on!
        if not selections :
            showerror( "No FASTQ files available matching the pattern *.R1.fastq.gz" )
            return
        ################################
        
        selections.insert(0, NA) #Adding N/A for the groups where no input is available
        groups = ['Grp%d'%i for i in range(1, len(selections)+1)]
        
        ##checking for debugging purpose
        print( selections )
        assert len(selections) == len(set(selections))
        ##
        
  
        top = Toplevel()
        info = LabelFrame(top, text=text )#"Group Information")
        chip_vars = [ StringVar() for s in selections[1:] ]
        input_vars = [ StringVar() for s in selections[1:] ]
        group_vars = [ StringVar() for s in selections[1:] ]
        
        chip_menus = [OptionMenu(info,var,*selections) for var in chip_vars]
        input_menus = [OptionMenu(info,var,*selections) for var in input_vars]
        group_menus = [OptionMenu(info,var,*groups) for var in group_vars]
        group_entries = [Entry(info, bd=2, width=8, textvariable=var) for var in group_vars]
        
        chiplabel = Label(info, text= "ChIP Names")
        inputlabel = Label(info, text="Input Names")
        grouplabel = Label(info, text="Group Names")
        
        chiplabel.grid( row = 0, column = 1, padx=4, pady=1)
        inputlabel.grid( row = 0, column = 2, padx=4, pady=1)
        grouplabel.grid( row = 0, column = 3, padx=4, pady=1 )
        
        
        for i, (chvar, invar) in enumerate(zip(chip_vars, input_vars)) :
            chvar.set(selections[0])
            invar.set(selections[0])
            
            chip_menus[i].grid( row = i+1, column = 1, padx=4, pady=1 )
            input_menus[i].grid( row = i+1, column = 2, padx=4, pady=1 )
            group_entries[i].grid( row = i+1, column = 3, padx=4, pady=1 )
            group_menus[i].grid( row = i+1, column = 4, padx=4, pady=1 )
        
        
        def savefunc() :
            info_text = StringIO()
            for v1, v2, v3 in zip( chip_vars, input_vars, group_vars ) :
                v1 = v1.get().strip() if v1.get().strip() != NA else ""
                
                if not v1 :
                    continue
                    
                v2 = v2.get().strip() if v2.get().strip() != NA else ""
                v3 = v3.get().strip() if v3.get().strip() != NA else ""
                
                if not v3 :
                    showerror( "Error", "Missing Replicate group name detected.\nReplicate group names should be given!" )
                    print( "Error", "Missing Replicate group name detected.\nReplicate group names should be given!" )
                    return
                    
                print( v1, v2, v3, file=info_text, sep="\t" )
            
            fp = open( filename, 'w' )
            fp.write( info_text.getvalue() )
            fp.close()
        
        def loadfunc() :
            if not exists(filename) :
                print( filename, 'does not exists!' )
                return
            
            for i, l in enumerate(open( filename )) :
                v1, v2, v3 = l.split('\t')
                
                if v1 :
                    try : assert v1 in selections
                    except :
                        showwarning('WARNING', 'ChIP name is not in the selection list!' )
                        print( 'v1:',v1 ) 
                        print( 'selection:', selection )
                        continue
                
                if v2 :
                    try: assert v2 in selections
                    except :
                        showwarning('WARNING', 'Input name is not in the selection list!' )
                        print( 'v2:',v2 ) 
                        print( 'selection:', selection )
                        return
                    
                chip_vars[i].set(v1.strip())
                input_vars[i].set(v2.strip())
                group_vars[i].set(v3.strip())
            
        def clearfunc() :
            for i, (chvar, invar, grvar) in enumerate(zip(chip_vars, input_vars, group_vars)) :
                chvar.set(selections[0])
                invar.set(selections[0])
                grvar.set('')
        
        info_clear_button = Button(top, 
                                  text="Clear", 
                                  command = clearfunc )
        
        info_save_button = Button(top, 
                                  text="Save", 
                                  command = savefunc )
        
        info_load_button = Button(top,
                                  text="Load",
                                  command = loadfunc )

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_clear_button.grid( row=5, column=3, padx=10, pady=5 )
        info_load_button.grid( row=5, column=4, padx=10, pady=5 )
        info_save_button.grid( row=5, column=5, padx=10, pady=5 )

        info.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        top.focus_force()
Beispiel #36
0
class MarkovDemo(Frame):

    "MarkovDemo(master=None, **kw) -> MarkovDemo instance"

    TEXT = dict(height=2, width=46, wrap=WORD)  # Text Options
    GRID = dict(padx=5, pady=5)                 # Grid Options

    # Initialize a MarkovDemo instance with a GUI for interaction.

    def __init__(self, master=None, **kw):
        "Initialize the MarkovDemo instance's widgets and settings."
        super().__init__(master, **kw)
        self.build_widgets()
        self.place_widgets()
        self.setup_widgets()
        self.grid_rowconfigure(2, weight=1)
        self.grid_rowconfigure(3, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.key = self.primer = None

    def build_widgets(self):
        "Build the various widgets that will be used in the program."
        # Create processing frame widgets.
        self.processing_frame = LabelFrame(self, text='Processing Mode:')
        self.mode_var = StringVar(self, 'encode')
        self.decode_button = Radiobutton(self.processing_frame,
                                         text='Decode Cipher-Text',
                                         command=self.handle_radiobuttons,
                                         value='decode',
                                         variable=self.mode_var)
        self.encode_button = Radiobutton(self.processing_frame,
                                         text='Encode Plain-Text',
                                         command=self.handle_radiobuttons,
                                         value='encode',
                                         variable=self.mode_var)
        self.freeze_var = BooleanVar(self, False)
        self.freeze_button = Checkbutton(self.processing_frame,
                                         text='Freeze Key & Primer',
                                         command=self.handle_checkbutton,
                                         offvalue=False,
                                         onvalue=True,
                                         variable=self.freeze_var)
        # Create encoding frame widgets.
        self.encoding_frame = LabelFrame(self, text='Encoding Options:')
        self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
        self.chain_size_entry = Entry(self.encoding_frame)
        self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
        self.plain_text_entry = Entry(self.encoding_frame)
        # Create input frame widgets.
        self.input_frame = LabelFrame(self, text='Input Area:')
        self.input_text = ScrolledText(self.input_frame, **self.TEXT)
        # Create output frame widgets.
        self.output_frame = LabelFrame(self, text='Output Area:')
        self.output_text = ScrolledText(self.output_frame, **self.TEXT)

    def place_widgets(self):
        "Place the widgets where they belong in the MarkovDemo frame."
        # Locate processing frame widgets.
        self.processing_frame.grid(sticky=EW, **self.GRID)
        self.decode_button.grid(row=0, column=0, **self.GRID)
        self.encode_button.grid(row=0, column=1, **self.GRID)
        self.freeze_button.grid(row=0, column=2, **self.GRID)
        # Locate encoding frame widgets.
        self.encoding_frame.grid(sticky=EW, **self.GRID)
        self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID)
        self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID)
        self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID)
        self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID)
        self.encoding_frame.grid_columnconfigure(1, weight=1)
        # Locate input frame widgets.
        self.input_frame.grid(sticky=NSEW, **self.GRID)
        self.input_text.grid(sticky=NSEW, **self.GRID)
        self.input_frame.grid_rowconfigure(0, weight=1)
        self.input_frame.grid_columnconfigure(0, weight=1)
        # Locate output frame widgets.
        self.output_frame.grid(sticky=NSEW, **self.GRID)
        self.output_text.grid(sticky=NSEW, **self.GRID)
        self.output_frame.grid_rowconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(0, weight=1)

    def setup_widgets(self):
        "Setup each widget's configuration for the events they handle."
        self.input_text.bind('<Key>', self.handle_key_events)
        self.input_text.bind('<Control-Key-a>', self.handle_control_a)
        self.input_text.bind('<Control-Key-/>', lambda event: 'break')
        self.output_text['state'] = DISABLED
        self.output_text.bind('<Control-Key-a>', self.handle_control_a)
        self.output_text.bind('<Control-Key-/>', lambda event: 'break')

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

    # Take care of any special event needing dedicated processing.

    def handle_radiobuttons(self):
        "Change the interface based on the encoding / decoding setting."
        if self.encrypting:
            self.freeze_button.grid()
            if not self.freeze_var.get():
                self.encoding_frame.grid()
        else:
            self.freeze_button.grid_remove()
            if not self.freeze_var.get():
                self.encoding_frame.grid_remove()
        self.handle_key_events(None)

    def handle_checkbutton(self):
        "Change the interface based on the key / primer freeze setting."
        if self.freeze_var.get():
            self.encoding_frame.grid_remove()
        else:
            self.encoding_frame.grid()

    def handle_key_events(self, event):
        "Schedule refreshing the output area after an input area event."
        if event is None or event.char and event.state | 0o11 == 0o11:
            self.after_idle(self.refresh)

    @staticmethod
    def handle_control_a(event):
        "Select all text in the widget associated with the given event."
        event.widget.tag_add(SEL, 1.0, END + '-1c')
        return 'break'

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

    # Handle interface's updates when either encoding or decoding.

    def refresh(self):
        "Refresh the output based on the value of the input."
        text = self.input_text.get(1.0, END + '-1c')
        if not text:
            self.output = text
        elif self.encrypting:
            self.encode(text)
        else:
            self.decode(text)

    def output(self, value):
        "Set the text in the output area to the string value."
        self.output_text['state'] = NORMAL
        self.output_text.delete(1.0, END)
        self.output_text.insert(END, value)
        if self.encrypting and self.freeze_var.get():
            self.output_text.see(END)
        self.output_text['state'] = DISABLED

    output = property(fset=output, doc='Output area property.')

    @property
    def chain_size(self):
        "Chain size for the Markov chains used when encrypting."
        try:
            value = ast.literal_eval(self.chain_size_entry.get())
            assert isinstance(value, int) and 2 <= value <= 256
            return value
        except:
            self.chain_size_entry.delete(0, END)
            self.chain_size_entry.insert(0, '2')
            return 2

    @property
    def plain_text(self):
        "Plain text or ignored characters in encryption process."
        try:
            value = self.repr_to_obj(self.plain_text_entry.get(), '')
            assert isinstance(value, str)
            return value
        except:
            self.plain_text_entry.delete(0, END)
            return ''

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

    # Encrypt a string for display in the interface's output area.

    def encode(self, string):
        "Encode the string and show the cipher-text in the output."
        try:
            cipher = self.build_cipher(string)
        except ValueError:
            self.output = ''
        except:
            self.output = traceback.format_exc()
        else:
            self.output = self.build_header() + '\n\n' + cipher

    def build_cipher(self, string):
        "Build cipher-text based on plain-text and return answer."
        if self.key and self.freeze_var.get():
            cipher, primer = me.encrypt_str(string, self.key, self.primer)
        else:
            args = string, self.chain_size, self.plain_text
            cipher, self.key, self.primer = me.auto_encrypt_str(*args)
        return cipher

    def build_header(self):
        "Build header from key and primer values in current use."
        header = '\n'.join(map(self.bytes_to_repr, self.key.data))
        header += '\n' + self.bytes_to_repr(self.primer.data)
        return header

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

    # Decrypt a string for display in the interface's output area.

    def decode(self, string):
        "Decode encrypted message and display plain-text in output."
        try:
            cipher = self.extract_keys(string)
            text = self.extract_text(cipher)
        except ValueError:
            self.output = ''
        except:
            self.output = traceback.format_exc()
        else:
            self.output = text

    def extract_keys(self, string):
        "Extract keys to decryption and return the cipher-text area."
        header, cipher = string.split('\n\n', 1)
        *key, primer = map(self.repr_to_obj, header.split('\n'))
        self.key, self.primer = me.Key(tuple(key)), me.Primer(primer)
        return cipher

    def extract_text(self, string):
        "Extract text message from string using built key and primer."
        text, primer = me.decrypt_str(string, self.key, self.primer)
        return text

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

    # Provide some special methods to simplify the program's code.

    @property
    def encrypting(self):
        "Encrypting boolean stating current operations mode."
        return {'encode': True, 'decode': False}[self.mode_var.get()]

    @staticmethod
    def bytes_to_repr(obj):
        "Convert bytes object into suitable representation."
        if not isinstance(obj, bytes):
            raise TypeError('Object must be a bytes instance!')
        return repr(obj)[2:-1]

    @staticmethod
    def repr_to_obj(string, prefix='b'):
        "Convert representation into an equivalent object."
        for template in '{}"{}"', "{}'{}'":
            try:
                return ast.literal_eval(template.format(prefix, string))
            except:
                pass
        raise ValueError('Cannot convert {!r} to object!'.format(string))

    @classmethod
    def main(cls):
        "Create context for demo and run a test instance."
        NoDefaultRoot()
        root = Tk()
        root.minsize(420, 330)
        root.title('Markov Demo 2')
        test = cls(root)
        test.grid(sticky=NSEW)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.mainloop()
class MarkovDemo(Frame):

    "MarkovDemo(master=None, **kw) -> MarkovDemo instance"

    TEXT = dict(height=2, width=46, wrap=WORD)  # Text Options
    GRID = dict(padx=5, pady=5)  # Grid Options

    # Initialize a MarkovDemo instance with a GUI for interaction.

    def __init__(self, master=None, **kw):
        "Initialize the MarkovDemo instance's widgets and settings."
        super().__init__(master, **kw)
        self.build_widgets()
        self.place_widgets()
        self.setup_widgets()
        self.grid_rowconfigure(2, weight=1)
        self.grid_rowconfigure(3, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.key = self.primer = None

    def build_widgets(self):
        "Build the various widgets that will be used in the program."
        # Create processing frame widgets.
        self.processing_frame = LabelFrame(self, text='Processing Mode:')
        self.mode_var = StringVar(self, 'encode')
        self.decode_button = Radiobutton(self.processing_frame,
                                         text='Decode Cipher-Text',
                                         command=self.handle_radiobuttons,
                                         value='decode',
                                         variable=self.mode_var)
        self.encode_button = Radiobutton(self.processing_frame,
                                         text='Encode Plain-Text',
                                         command=self.handle_radiobuttons,
                                         value='encode',
                                         variable=self.mode_var)
        self.freeze_var = BooleanVar(self, False)
        self.freeze_button = Checkbutton(self.processing_frame,
                                         text='Freeze Key & Primer',
                                         command=self.handle_checkbutton,
                                         offvalue=False,
                                         onvalue=True,
                                         variable=self.freeze_var)
        # Create encoding frame widgets.
        self.encoding_frame = LabelFrame(self, text='Encoding Options:')
        self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
        self.chain_size_entry = Entry(self.encoding_frame)
        self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
        self.plain_text_entry = Entry(self.encoding_frame)
        # Create input frame widgets.
        self.input_frame = LabelFrame(self, text='Input Area:')
        self.input_text = ScrolledText(self.input_frame, **self.TEXT)
        # Create output frame widgets.
        self.output_frame = LabelFrame(self, text='Output Area:')
        self.output_text = ScrolledText(self.output_frame, **self.TEXT)

    def place_widgets(self):
        "Place the widgets where they belong in the MarkovDemo frame."
        # Locate processing frame widgets.
        self.processing_frame.grid(sticky=EW, **self.GRID)
        self.decode_button.grid(row=0, column=0, **self.GRID)
        self.encode_button.grid(row=0, column=1, **self.GRID)
        self.freeze_button.grid(row=0, column=2, **self.GRID)
        # Locate encoding frame widgets.
        self.encoding_frame.grid(sticky=EW, **self.GRID)
        self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID)
        self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID)
        self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID)
        self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID)
        self.encoding_frame.grid_columnconfigure(1, weight=1)
        # Locate input frame widgets.
        self.input_frame.grid(sticky=NSEW, **self.GRID)
        self.input_text.grid(sticky=NSEW, **self.GRID)
        self.input_frame.grid_rowconfigure(0, weight=1)
        self.input_frame.grid_columnconfigure(0, weight=1)
        # Locate output frame widgets.
        self.output_frame.grid(sticky=NSEW, **self.GRID)
        self.output_text.grid(sticky=NSEW, **self.GRID)
        self.output_frame.grid_rowconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(0, weight=1)

    def setup_widgets(self):
        "Setup each widget's configuration for the events they handle."
        self.input_text.bind('<Key>', self.handle_key_events)
        self.input_text.bind('<Control-Key-a>', self.handle_control_a)
        self.input_text.bind('<Control-Key-/>', lambda event: 'break')
        self.output_text['state'] = DISABLED
        self.output_text.bind('<Control-Key-a>', self.handle_control_a)
        self.output_text.bind('<Control-Key-/>', lambda event: 'break')

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

    # Take care of any special event needing dedicated processing.

    def handle_radiobuttons(self):
        "Change the interface based on the encoding / decoding setting."
        if self.encrypting:
            self.freeze_button.grid()
            if not self.freeze_var.get():
                self.encoding_frame.grid()
        else:
            self.freeze_button.grid_remove()
            if not self.freeze_var.get():
                self.encoding_frame.grid_remove()
        self.handle_key_events(None)

    def handle_checkbutton(self):
        "Change the interface based on the key / primer freeze setting."
        if self.freeze_var.get():
            self.encoding_frame.grid_remove()
        else:
            self.encoding_frame.grid()

    def handle_key_events(self, event):
        "Schedule refreshing the output area after an input area event."
        if event is None or event.char and event.state | 0o11 == 0o11:
            self.after_idle(self.refresh)

    @staticmethod
    def handle_control_a(event):
        "Select all text in the widget associated with the given event."
        event.widget.tag_add(SEL, 1.0, END + '-1c')
        return 'break'

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

    # Handle interface's updates when either encoding or decoding.

    def refresh(self):
        "Refresh the output based on the value of the input."
        text = self.input_text.get(1.0, END + '-1c')
        if not text:
            self.output = text
        elif self.encrypting:
            self.encode(text)
        else:
            self.decode(text)

    def output(self, value):
        "Set the text in the output area to the string value."
        self.output_text['state'] = NORMAL
        self.output_text.delete(1.0, END)
        self.output_text.insert(END, value)
        if self.encrypting and self.freeze_var.get():
            self.output_text.see(END)
        self.output_text['state'] = DISABLED

    output = property(fset=output, doc='Output area property.')

    @property
    def chain_size(self):
        "Chain size for the Markov chains used when encrypting."
        try:
            value = ast.literal_eval(self.chain_size_entry.get())
            assert isinstance(value, int) and 2 <= value <= 256
            return value
        except:
            self.chain_size_entry.delete(0, END)
            self.chain_size_entry.insert(0, '2')
            return 2

    @property
    def plain_text(self):
        "Plain text or ignored characters in encryption process."
        try:
            value = self.repr_to_obj(self.plain_text_entry.get(), '')
            assert isinstance(value, str)
            return value
        except:
            self.plain_text_entry.delete(0, END)
            return ''

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

    # Encrypt a string for display in the interface's output area.

    def encode(self, string):
        "Encode the string and show the cipher-text in the output."
        try:
            cipher = self.build_cipher(string)
        except ValueError:
            self.output = ''
        except:
            self.output = traceback.format_exc()
        else:
            self.output = self.build_header() + '\n\n' + cipher

    def build_cipher(self, string):
        "Build cipher-text based on plain-text and return answer."
        if self.key and self.freeze_var.get():
            cipher, primer = me.encrypt_str(string, self.key, self.primer)
        else:
            args = string, self.chain_size, self.plain_text
            cipher, self.key, self.primer = me.auto_encrypt_str(*args)
        return cipher

    def build_header(self):
        "Build header from key and primer values in current use."
        header = '\n'.join(map(self.bytes_to_repr, self.key.data))
        header += '\n' + self.bytes_to_repr(self.primer.data)
        return header

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

    # Decrypt a string for display in the interface's output area.

    def decode(self, string):
        "Decode encrypted message and display plain-text in output."
        try:
            cipher = self.extract_keys(string)
            text = self.extract_text(cipher)
        except ValueError:
            self.output = ''
        except:
            self.output = traceback.format_exc()
        else:
            self.output = text

    def extract_keys(self, string):
        "Extract keys to decryption and return the cipher-text area."
        header, cipher = string.split('\n\n', 1)
        *key, primer = map(self.repr_to_obj, header.split('\n'))
        self.key, self.primer = me.Key(tuple(key)), me.Primer(primer)
        return cipher

    def extract_text(self, string):
        "Extract text message from string using built key and primer."
        text, primer = me.decrypt_str(string, self.key, self.primer)
        return text

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

    # Provide some special methods to simplify the program's code.

    @property
    def encrypting(self):
        "Encrypting boolean stating current operations mode."
        return {'encode': True, 'decode': False}[self.mode_var.get()]

    @staticmethod
    def bytes_to_repr(obj):
        "Convert bytes object into suitable representation."
        if not isinstance(obj, bytes):
            raise TypeError('Object must be a bytes instance!')
        return repr(obj)[2:-1]

    @staticmethod
    def repr_to_obj(string, prefix='b'):
        "Convert representation into an equivalent object."
        for template in '{}"{}"', "{}'{}'":
            try:
                return ast.literal_eval(template.format(prefix, string))
            except:
                pass
        raise ValueError('Cannot convert {!r} to object!'.format(string))

    @classmethod
    def main(cls):
        "Create context for demo and run a test instance."
        NoDefaultRoot()
        root = Tk()
        root.minsize(420, 330)
        root.title('Markov Demo 2')
        test = cls(root)
        test.grid(sticky=NSEW)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.mainloop()
Beispiel #38
0
class RNASeqFrame(PipelineFrame):
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs):
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None

        eframe = self.eframe = LabelFrame(self, text="Options")
        #,fg=textLightColor,bg=baseColor)
        eframe.grid(row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5)

        label = Label(eframe,
                      text="Pipeline")  #,fg=textLightColor,bg=baseColor)
        label.grid(row=3, column=0, sticky=W, padx=10, pady=5)
        Pipelines = ["initialqcrnaseq", "rnaseq"]
        Pipeline = self.Pipeline = StringVar()
        Pipeline.set(Pipelines[0])
        om = OptionMenu(eframe,
                        Pipeline,
                        *Pipelines,
                        command=self.option_controller)
        om.config()  #bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()  #bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3, column=1, sticky=W, padx=10, pady=5)

        rReadlens = [
            'Read Length is 50', 'Read Length is 75', 'Read Length is 100',
            'Read Length is 125', 'Read Length is 150', 'Read Length is 250'
        ]
        self.rReadlen = rReadlen = StringVar()
        rReadlen.set(rReadlens[2])
        self.om2 = OptionMenu(eframe,
                              rReadlen,
                              *rReadlens,
                              command=self.option_controller)
        #self.om2.grid(row=4,column=1,sticky=W,padx=10,pady=5)

        rStrands = [
            '0, Reads are Unstranded', '1, Reads are from Sense Strand',
            '2, Reads are from Anti-Sense Strand'
        ]
        self.rStrand = rStrand = StringVar()
        rStrand.set(rStrands[0])
        self.om3 = OptionMenu(eframe,
                              rStrand,
                              *rStrands,
                              command=self.option_controller)
        #self.om3.grid(row=5,column=1,sticky=W,padx=10,pady=5)

        rDegs = [
            "no, Do not Report Differentially Expressed Genes",
            "yes, Report Differentially Expressed Genes"
        ]
        self.rDeg = rDeg = StringVar()
        rDeg.set(rDegs[0])
        self.om4 = OptionMenu(eframe,
                              rDeg,
                              *rDegs,
                              command=self.option_controller)
        self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5)

        #####################
        #Sample Threshold
        #####################
        self.sampleLF = sampleLF = LabelFrame(
            eframe, text="Low Abundance Gene Thresholds")

        self.rMincount = rMincount = StringVar()
        rMincount.set("5")
        self.rMinsamples = rMinsamples = StringVar()
        rMinsamples.set("2")

        #rMincount.trace('w', lambda a,b,c,x="rmincount": makejson(x))

        #Filter out genes < [5] read counts in < [2] samples
        rminsamplesL = Label(sampleLF, text="Include genes with >=")  # in")
        rmincountE = Entry(sampleLF, bd=2, width=3, textvariable=rMincount)
        rmincountL = Label(sampleLF, text="read counts in  >=")
        rminsamplesE = Entry(sampleLF, bd=2, width=3, textvariable=rMinsamples)
        rminsamplesR = Label(sampleLF, text="samples")

        rminsamplesL.grid(row=9, column=1, sticky=W, padx=10, pady=5)
        rmincountE.grid(row=9, column=2, sticky=W, padx=0, pady=5)
        rmincountL.grid(row=9, column=3, sticky=W, padx=5, pady=5)
        rminsamplesE.grid(row=9, column=4, sticky=W, padx=0, pady=5)
        rminsamplesR.grid(row=9, column=5, sticky=W, padx=10, pady=5)
        #rMinsamples.trace('w', lambda a,b,c,x="rmincount": makejson(x))

        sampleLF.grid(row=8,
                      column=0,
                      columnspan=4,
                      sticky=W,
                      padx=20,
                      pady=10)
        #####################

        self.add_info(eframe)
        self.option_controller()

    def option_controller(self, *args, **kwargs):
        PipelineFrame.option_controller(self)
        if self.Pipeline.get() == 'initialqcrnaseq':
            self.om4.grid_forget()
            self.sampleLF.grid_forget()
        else:
            self.om4.grid(row=6, column=1, sticky=W, padx=10, pady=5)
            self.sampleLF.grid(row=8,
                               column=0,
                               columnspan=4,
                               sticky=W,
                               padx=20,
                               pady=10)

    def makejson_wrapper(self, *args, **kwargs):
        self.makejson(*args, **kwargs)

    def add_info(self, parent):
        if not self.info:
            self.info = LabelFrame(parent, text="Sample Information")
            self.groups_button = Button(self.info,
                                        text="Set Groups",
                                        command=self.popup_groups)
            self.contrasts_button = Button(self.info,
                                           text="Set Contrasts",
                                           command=self.popup_contrasts)

            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.groups_button.grid(row=5, column=5, padx=10, pady=5)
            self.contrasts_button.grid(row=5, column=6, padx=10, pady=5)

        self.info.grid(row=10,
                       column=0,
                       columnspan=6,
                       sticky=W,
                       padx=20,
                       pady=10)

    def popup_groups(self):
        self.popup_window("Groups Information", "groups.tab")

    def popup_contrasts(self):
        self.popup_window("Contrasts Information", "contrasts.tab")

    def popup_window(self, text, filename):
        top = Toplevel()

        info = LabelFrame(top, text=text)  #"Group Information")
        info_text = Text(
            info,
            width=50,
            height=8,
            #bg=projectBgColor,
            #fg=projectFgColor,
            font=("nimbus mono bold", "11"))

        def savefunc():
            self.writepaste(filename, info_text)

        def loadfunc():
            self.readpaste(filename, info_text)

        info_save_button = Button(info, text="Save", command=savefunc)
        info_load_button = Button(info, text="Load", command=loadfunc)

        #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
        #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

        info_load_button.grid(row=5, column=5, padx=10, pady=5)
        info_save_button.grid(row=5, column=6, padx=10, pady=5)
        info_text.grid(row=1,
                       rowspan=3,
                       column=1,
                       columnspan=7,
                       padx=5,
                       pady=5)

        info.grid(row=7, column=0, columnspan=6, sticky=W, padx=20, pady=10)
        top.focus_force()

    def makejson(self, *args):
        #print(args[0])
        caller = args[0]
        #global PD
        #global UnitsBak
        #global RGbak
        D = dict()
        try:
            F = open(self.workpath.get() + "/samples", "r")
            f = F.read().split("\n")
            F.close()
            for line in f:
                L = line.split()
                a = L.pop(0)
                D[a] = L
                samples = D
        except:
            samples = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/pairs", "r")
            f = F.read().split()
            F.close()
            for i in range(0, len(f), 2):
                #            a=f[i].split(".")[0]
                #            b=f[i+1].split(".")[0]
                a = f[i]
                b = f[i + 1]

                D[a + "+" + b] = [a, b]

            pairs = D
        except:
            pairs = {"na": "na"}

        D = dict()
        try:
            F = open(self.workpath.get() + "/contrasts.tab", "r")
            #        f=F.read().split('\n')
            #        F.close()
            #        D["rsamps"]=f[0].split()
            #        D["rgroups"]=f[1].split()
            #        D["rcontrasts"]=f[2].split()
            #        D["rlabels"]=f[3].split()
            f = F.readlines()
            F.close()
            ##        sampl=[]
            ##        grp=[]
            cont = []
            ##        lbl=[]
            for x in f:
                if len(x.split()) == 2:
                    cont.append(x.split()[0])
                    cont.append(x.split()[1])
            D["rcontrasts"] = cont
            #        contrasts["rcontrasts"]=cont
            contrasts = D
        except:
            contrasts = {"rcontrasts": "na"}
    ##        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
    ##------
        D = dict()
        try:
            F = open(self.workpath.get() + "/groups.tab", "r")
            f = F.readlines()
            F.close()
            sampl = []
            grp = []
            #        cont=[]
            lbl = []
            for x in f:
                #           if len(x.split()) == 4 or len(x.split()) == 3:
                if len(x.split()) == 3:
                    sampl.append(x.split()[0])
                    grp.append(x.split()[1])
                    lbl.append(x.split()[2])
            D["rsamps"] = sampl
            D["rgroups"] = grp
            D["rlabels"] = lbl
            #        D["rcontrasts"]="na"
            #        contrasts=D
            groups = D
        except:
            #        contrasts={"rsamps":"na","rgroups":"na","rcontrasts":"na","rlabels":"na"}
            groups = {"rsamps": "na", "rgroups": "na", "rlabels": "na"}

    ##------
        D = dict()
        FT = filetype  #.get()
        #    p = Popen("ls "+workpath.get()+"/*."+FT, shell=True, stdin=PIPE, stdout=PIPE, stderr=DEVNULL, close_fds=True)
        p = Popen("find " + self.workpath.get() +
                  " -maxdepth 1 -type l -printf '%f\n' ",
                  shell=True,
                  stdin=PIPE,
                  stdout=PIPE,
                  stderr=DEVNULL,
                  close_fds=True)
        a = p.stdout.read().decode(encoding='UTF-8').split("\n")

        RG = dict()
        b = a.pop()
        #    tkinter.messagebox.showerror("",a)
        #    if freezeunits.get()=="no":
        for i in a:

            key = re.sub(".realign", "", i.split("/")[-1])
            key = re.sub(".bai", "", key)
            key = re.sub(".bam", "", key)
            key = re.sub(".sam", "", key)
            key = re.sub(".recal", "", key)
            key = re.sub(".dedup", "", key)
            key = re.sub(".sorted", "", key)
            key = re.sub(".fin", "", key)
            key = re.sub(".R[12]", "", key)
            key = re.sub("_R[12]", "", key)
            key = re.sub(".fastq", "", key)
            key = re.sub(".gz", "", key)
            #        key=re.sub("[\._](R[12]\.)*"+FT+"$","",i.split("/")[-1])
            #        key=re.sub(".R[12]."+FT+"$","",i.split("/")[-1])
            #        key=re.sub("([._]R[12][._])*([fin|sorted|dedup|recal|realign])*\.{0}$".format(FT),"",i.split("/")[-1])
            D[key] = key
            RG[key] = {
                'rgsm': key,
                'rglb': 'na',
                'rgpu': 'na',
                'rgpl': 'ILLUMINA',
                'rgcn': 'na'
            }
        units = D
        UnitsBak = D

        try:
            F = open(self.workpath.get() + "/rg.tab", "r")
            f = F.read().splitlines()
            F.close()
            for theLine in f:
                if not re.match("^ID", theLine):
                    (rgid, rgsm, rglb, rgpl, rgpu, rgcn) = theLine.split("\t")
                    RG[rgid] = {
                        'rgsm': rgsm,
                        'rglb': rglb,
                        'rgpu': rgpu,
                        'rgpl': rgpl,
                        'rgcn': rgcn
                    }
        except:
            pass

        RGbak = RG
        #     else:
        #         units=UnitsBak
        #         RG=RGbak
        #
        PD = dict()

        smparams = []

        for i in range(len(self.parameters)):

            if cp[i].var.get() == "1":
                smparams.append(parameters[i])

        AD = eval(
            open(join(PIPELINER_HOME,
                      self.annotation.get() + ".json"), "r").read())

        SD = AD['references']['rnaseq']['STARDIR']
        #    tkinter.messagebox.showinfo("initLock","SD={0}".format(SD))
        gi = self.global_info
        PD = {
            'project': {
                'pfamily':
                gi.pfamily.get(),
                'units':
                units,
                'samples':
                samples,
                'pairs':
                pairs,
                'id':
                gi.eprojectid.get(),
                'pi':
                gi.epi.get(),
                'organism':
                gi.eorganism.get(),
                'analyst':
                gi.eanalyst.get(),
                'poc':
                gi.epoc.get(),
                'pipeline':
                self.Pipeline.get(),
                'version':
                "1.0",
                'annotation':
                gi.annotation.get(),
                'datapath':
                self.datapath.get(),
                'targetspath':
                self.targetspath.get(),
                'filetype':
                filetype,
                'binset':
                "standard-bin",
                'username':
                gi.euser.get(),
                'flowcellid':
                gi.eflowcell.get(),
                'platform':
                gi.eplatform.get(),
                'custom':
                customRules,
                'efiletype':
                efiletype,
                'workpath':
                self.workpath.get(),
                'batchsize':
                batchsize,
                "smparams":
                smparams,
                "rgid":
                RG,
                "cluster":
                "cluster_medium.json",
                "description":
                gi.description.get('1.0', END),
                "technique":
                gi.technique.get(),
                "TRIM":
                "yes",
                "groups":
                groups,
                "contrasts":
                contrasts,
                "SJDBOVERHANG":
                self.rReadlen.get().split(" ")[3],
                "STRANDED":
                self.rStrand.get().split(",")[0],
                "DEG":
                self.rDeg.get().split(",")[0].lower(),
                "STARSTRANDCOL":
                "{0}".format(int(self.rStrand.get().split(",")[0]) + 2),
                "MINSAMPLES":
                self.rMinsamples.get(),
                "MINCOUNTGENES":
                self.rMincount.get(),
                "MINCOUNTJUNCTIONS":
                self.rMincount.get(),
                "MINCOUNTGENEJUNCTIONS":
                self.rMincount.get(),
                "STARDIR":
                SD + self.rReadlen.get().split(" ")[3],
                "PICARDSTRAND": [
                    "NONE", "FIRST_READ_TRANSCRIPTION_STRAND",
                    "SECOND_READ_TRANSCRIPTION_STRAND"
                ][int(self.rStrand.get().split(",")[0])]
            }
        }

        J = json.dumps(PD, sort_keys=True, indent=4, ensure_ascii=True)
        gi.jsonconf.delete("1.0", END)
        gi.jsonconf.insert(INSERT, J)
        self.saveproject(gi.jsonconf.get("1.0", END))
style = Style()
# both theme_create and theme_settings worked
style.theme_create(
    "yummy",
    parent="clam",
    settings={
        #style.theme_settings('default', {
        # start of theme extract
        'Labelframe.border': {
            "element create": ('image', "frame", ('disabled', "frame-d"), {
                'border': 5,
                'sticky': "nsew"
            })
        }  #'padding':5,
        # end of theme extract - don't forget to add comma at end when inserting
    })

style.theme_use('yummy')  # 'default'
widg = LabelFrame(fr, text='Piratz!')
widg.grid(column=0, row=11, sticky='nsew', padx=5, pady=5, ipadx=5, ipady=5)
f0 = Label(widg, text='Something to say')
f0.grid()
widg1 = LabelFrame(fr, text='Piratz!\nextra line')
widg1.grid(column=0, row=12, sticky='nsew', padx=5, pady=5, ipadx=5,
           ipady=5)  #  ipadx=5, ipady=5
f1 = Label(widg1, text='Something else to say\nwith an extra line')
f1.grid()
run_state(fr, widg, widg1)

root.mainloop()
Beispiel #40
0
    def build(self):
        """Widget construction."""

        lf1 = LabelFrame(self.fr0, text='rgb')
        lf1.grid(column=0, row=0, sticky='new')
        lf1.columnconfigure(1, weight=1)

        rl0 = Label(lf1, text='red  ')
        rl0.grid(column=0, row=0, sticky='s')

        self.rcan = Canvas(lf1,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.rcan.grid(column=1,
                       row=0,
                       sticky='sew',
                       padx=self.sliderlength // 2)
        self.rcan.bind("<Configure>", self.resize_rcan)

        rsc = TtkScale(lf1,
                       self.scale_l,
                       from_=0,
                       to=255,
                       variable=self.rvar,
                       orient='horizontal',
                       command=self.rhandle,
                       tickinterval=20)
        rsc.grid(column=1, row=1, sticky='new')

        vcmdsb = root.register(sb_okay)

        rsb = Spinbox(lf1,
                      from_=0,
                      to=255,
                      textvariable=self.rvar,
                      validate='key',
                      validatecommand=(vcmdsb, '%d', '%P', '%S', 255),
                      command=self.rhandle,
                      width=5)
        rsb.grid(column=2, row=1, sticky='nw')
        rsb.bind('<KeyRelease>', self.checksb)

        rel = Label(lf1)
        rel.grid(column=2, row=2)

        gl0 = Label(lf1, text='green')
        gl0.grid(column=0, row=3)

        self.gcan = Canvas(lf1,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.gcan.grid(column=1,
                       row=3,
                       sticky='sew',
                       padx=self.sliderlength // 2)
        self.gcan.bind("<Configure>", self.resize_gcan)

        gsc = TtkScale(lf1,
                       self.scale_l,
                       from_=0,
                       to=255,
                       variable=self.gvar,
                       orient='horizontal',
                       command=self.ghandle,
                       tickinterval=20)
        gsc.grid(column=1, row=4, sticky='new')

        gsb = Spinbox(lf1,
                      from_=0,
                      to=255,
                      textvariable=self.gvar,
                      validate='key',
                      validatecommand=(vcmdsb, '%d', '%P', '%S', 255),
                      command=self.ghandle,
                      width=5)
        gsb.grid(column=2, row=4, sticky='nw')
        gsb.bind('<KeyRelease>', self.checksb)

        gel = Label(lf1)
        gel.grid(column=2, row=5)

        bl0 = Label(lf1, text='blue ')
        bl0.grid(column=0, row=6, sticky='s')

        self.bcan = Canvas(lf1,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.bcan.grid(column=1,
                       row=6,
                       sticky='new',
                       padx=self.sliderlength // 2)
        self.bcan.bind("<Configure>", self.resize_bcan)

        bsc = TtkScale(lf1,
                       self.scale_l,
                       from_=0,
                       to=255,
                       variable=self.bvar,
                       orient='horizontal',
                       command=self.bhandle,
                       tickinterval=20)
        bsc.grid(column=1, row=7, sticky='new')

        bsb = Spinbox(lf1,
                      from_=0,
                      to=255,
                      textvariable=self.bvar,
                      validate='key',
                      validatecommand=(vcmdsb, '%d', '%P', '%S', 255),
                      command=self.bhandle,
                      width=5)
        bsb.grid(column=2, row=7, sticky='nw')
        bsb.bind('<KeyRelease>', self.checksb)

        bel = Label(lf1)
        bel.grid(column=2, row=8)

        lf3 = LabelFrame(self.fr0, text='colour mix')
        lf3.grid(column=1, row=0, sticky='nw')

        self.cmcan = cmcan = Canvas(lf3,
                                    width=30,
                                    height=30,
                                    bd=0,
                                    highlightthickness=0)
        cmcan.grid(column=0, row=0, sticky='n', columnspan=2)
        cmcan.grid_propagate(0)
        vdraw_gradient(self.cmcan, (255, 0, 0), alpha=255)

        cml = Label(lf3, text='hash\nvalue')
        cml.grid(column=0, row=1)

        vcmd = root.register(is_okay)
        self.ent0 = ent0 = Entry(lf3,
                                 width=8,
                                 validate='key',
                                 validatecommand=(vcmd, '%i', '%P', '%S'),
                                 textvariable=self.evar)
        ent0.grid(column=1, row=1)
        ent0.bind('<KeyRelease>', self.checkhash)

        lf5 = LabelFrame(lf3, text='related colours', style='Wide.TLabelframe')
        lf5.grid(column=0, row=2, sticky='nw', columnspan=2)

        self.srcls = []
        self.vrcls = []
        self.srccans = []
        self.vrccans = []
        relateds = [25, 50, 75, 100]
        stexts = ['25% sat', '50% sat', '75% sat', '100% sat']
        vtexts = ['25% val', '50% val', '75% val', '100% val']

        for ix, rel in enumerate(relateds):
            Label(lf5, text=stexts[ix]).grid(row=1 + 2 * ix,
                                             column=0,
                                             sticky='n')
            self.srcls.append(Label(lf5))
            self.srcls[ix].grid(row=1 + 2 * ix, column=1, sticky='n')
            self.srccans.append(
                Canvas(lf5, width=30, height=30, bd=0, highlightthickness=0))
            self.srccans[ix].grid(row=2 * ix,
                                  column=0,
                                  sticky='n',
                                  columnspan=2)
            Label(lf5, text=vtexts[ix]).grid(row=9 + 2 * ix,
                                             column=0,
                                             sticky='n')
            self.vrcls.append(Label(lf5))
            self.vrcls[ix].grid(row=9 + 2 * ix, column=1, sticky='n')
            self.vrccans.append(
                Canvas(lf5, width=30, height=30, bd=0, highlightthickness=0))
            self.vrccans[ix].grid(row=8 + 2 * ix,
                                  column=0,
                                  sticky='n',
                                  columnspan=2)

        self.cccan = Canvas(lf5,
                            width=30,
                            height=30,
                            bd=0,
                            highlightthickness=0)
        self.cccan.grid(column=0, row=17, sticky='n', columnspan=2)

        self.ccla = Label(lf5, text="comp'y")
        self.ccla.grid(column=0, row=18, sticky='n')

        self.ccl = Label(lf5, text="")
        self.ccl.grid(column=1, row=18, sticky='n')

        al0 = Label(lf1, text='alpha')
        al0.grid(column=0, row=10, sticky='s')

        self.acan = Canvas(lf1,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.acan.grid(column=1,
                       row=10,
                       sticky='new',
                       padx=self.sliderlength // 2)
        self.acan.bind("<Configure>", self.resize_acan)

        asc = TtkScale(lf1,
                       self.scale_l,
                       from_=0,
                       to=255,
                       variable=self.avar,
                       orient='horizontal',
                       command=self.ahandle,
                       tickinterval=20)
        asc.grid(column=1, row=11, sticky='new')

        asb = Spinbox(lf1,
                      from_=0,
                      to=255,
                      textvariable=self.avar,
                      validate='key',
                      validatecommand=(vcmdsb, '%d', '%P', '%S', 255),
                      command=self.ahandle,
                      width=5)
        asb.grid(column=2, row=11, sticky='nw')
        asb.bind('<KeyRelease>', self.checksba)

        ael = Label(lf1, text=' ')
        ael.grid(column=2, row=12, sticky='s')

        draw_gradient(self.rcan, (0, 0, 0), (255, 0, 0), width=self.canvas_w)
        draw_gradient(self.gcan, (255, 0, 0), (255, 0, 255),
                      width=self.canvas_w)
        draw_gradient(self.bcan, (255, 0, 0), (255, 255, 0),
                      width=self.canvas_w)
        draw_agradient(self.acan, (127, 127, 127), (255, 0, 0),
                       width=self.canvas_w)

        lf4 = LabelFrame(self.fr0, text='hsv')
        lf4.grid(column=2, row=0, sticky='news')
        lf4.columnconfigure(1, weight=1)

        hl0 = Label(lf4, text='hue  ')
        hl0.grid(column=0, row=0, sticky='s')

        self.hcan = Canvas(lf4,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.hcan.grid(column=1,
                       row=0,
                       sticky='sew',
                       padx=self.sliderlength // 2)
        self.hcan.bind("<Configure>", self.resize_hcan)

        hsc = TtkScale(lf4,
                       self.scale_l,
                       from_=0,
                       to=360,
                       variable=self.hvar,
                       orient='horizontal',
                       command=self.hhandle,
                       tickinterval=30)
        hsc.grid(column=1, row=1, sticky='new')

        vcmdsb = root.register(sb_okay)

        hsb = Spinbox(lf4,
                      from_=0,
                      to=360,
                      textvariable=self.hvar,
                      validate='key',
                      validatecommand=(vcmdsb, '%P', '%S', 360),
                      command=self.hhandle,
                      width=5)
        hsb.grid(column=2, row=1, sticky='nw')
        hsb.bind('<KeyRelease>', self.checksbh)

        hel = Label(lf4)
        hel.grid(column=2, row=2)

        sl0 = Label(lf4, text='sat  ')
        sl0.grid(column=0, row=3)

        self.scan = Canvas(lf4,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.scan.grid(column=1,
                       row=3,
                       sticky='sew',
                       padx=self.sliderlength // 2)
        self.scan.bind("<Configure>", self.resize_scan)

        ssc = TtkScale(lf4,
                       self.scale_l,
                       from_=0,
                       to=100,
                       variable=self.svar,
                       orient='horizontal',
                       command=self.shandle,
                       tickinterval=10)
        ssc.grid(column=1, row=4, sticky='new')

        ssb = Spinbox(lf4,
                      from_=0,
                      to=100,
                      textvariable=self.svar,
                      validate='key',
                      validatecommand=(vcmdsb, '%P', '%S', 100),
                      command=self.shandle,
                      width=5)
        ssb.grid(column=2, row=4, sticky='nw')
        ssb.bind('<KeyRelease>', self.checksb100)

        sel = Label(lf4)
        sel.grid(column=2, row=5)

        vl0 = Label(lf4, text='value')
        vl0.grid(column=0, row=6, sticky='s')

        self.vcan = Canvas(lf4,
                           width=self.canvas_w,
                           height=self.canvas_h,
                           bd=0,
                           highlightthickness=0)
        self.vcan.grid(column=1,
                       row=6,
                       sticky='new',
                       padx=self.sliderlength // 2)
        self.vcan.bind("<Configure>", self.resize_vcan)

        vsc = TtkScale(lf4,
                       self.scale_l,
                       from_=0,
                       to=100,
                       variable=self.vvar,
                       orient='horizontal',
                       command=self.vhandle,
                       tickinterval=10)
        vsc.grid(column=1, row=7, sticky='new')

        vsb = Spinbox(lf4,
                      from_=0,
                      to=100,
                      textvariable=self.vvar,
                      validate='key',
                      validatecommand=(vcmdsb, '%P', '%S', 100),
                      command=self.vhandle,
                      width=5)
        vsb.grid(column=2, row=7, sticky='nw')
        vsb.bind('<KeyRelease>', self.checksb100)

        vel = Label(lf4)
        vel.grid(column=2, row=8)

        # assume initial setting 0,100,100 hsv
        to_colour = hsv_to_rgb(*(0, 100, 100))

        hue_gradient(self.hcan, width=self.canvas_w)
        draw_gradient(self.scan, (255, 255, 255),
                      to_colour,
                      width=self.canvas_w)
        draw_gradient(self.vcan, (0, 0, 0), to_colour, width=self.canvas_w)

        self.can_hsv = can_hsv = Canvas(lf4,
                                        width=self.wheel_w,
                                        height=self.wheel_w,
                                        bg='#d9d9d9')
        can_hsv.grid(column=0, row=9, columnspan=3, pady=25, sticky='n')
        self.hsv_gamut = PhotoImage(file='../figures/colour_wheel.png')
        can_hsv.create_image(0, 0, anchor='nw', image=self.hsv_gamut)
        self.ring = circle(can_hsv,
                           307,
                           158,
                           self.ring_radius,
                           width=self.ring_width,
                           outline='#555555',
                           activeoutline='black',
                           tags='ring')

        can_hsv.bind('<Button-1>', self.click_ring)
        can_hsv.tag_bind('ring', '<B1-Motion>', self.drag_ring)

        self.related(0, 100, 100, 255, 0, 0)
Beispiel #41
0
def _gui():
  try:
    from tkinter import Tk, ttk, filedialog, messagebox, StringVar, IntVar
    from tkinter.ttk import Button, Entry, Frame, Label, LabelFrame, Notebook, Radiobutton, Style
  except:
    sys.exit("Unable to load tkinter. Aborting.")
  
  def _check_single(): #check the input and accordingly give the output... for the f_single tab
    if txt_f_single_entry.get()=="":
      lbl_f_single_result.config(text="", style="TLabel")
    elif check_afm(txt_f_single_entry.get()):
      lbl_f_single_result.config(text="Έγκυρο ΑΦΜ.", style="valid.TLabel")
    else:
      lbl_f_single_result.config(text="Άκυρο ΑΦΜ.", style="invalid.TLabel")
  
  def _select_input_file():
    strv_f_file_input.set(filedialog.askopenfilename(title="Άνοιγμα αρχείου"))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
#TODO a much better mechanism to enable / disable btn_f_file_submit is needed.
  def _select_output_file():
    strv_f_file_output.set(filedialog.asksaveasfilename(title="Αποθήκευση ως..."))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
  
  def _check_file():#TODO this could / should be merged with the TUI version...
    input_filepath = strv_f_file_input.get()
    output_filepath = strv_f_file_output.get()
    filter_output = intvar_filter_sel.get()
    try:
      input_file = open(input_filepath, "r")
      output_file = open(output_filepath, "w")
    except:
      messagebox.showerror(title="Σφάλμα", message="Αδυναμία διαχείρησης των αρχείων που ορίσατε.\n\nΠαρακαλώ επιβεβαιώστε πως το αρχείο με τα δεδομένα υπάρχει, πως έχετε δικαιώματα ανάγνωσης, και πως έχετε δικαιώματα εγγραφής στον κατάλογο εξαγωγής των αποτελεσμάτων.")
      return
    counter = {True:0, False:0}
    for entry in input_file:
      validation = check_afm(entry.strip())
      counter[validation]+=1
      if filter_output == 3 and validation == False:
        output_file.write(entry)
      elif filter_output == 2 and validation == True:
        output_file.write(entry)
      elif filter_output == 1:
        output_file.write(entry.strip() + "\t" + str(validation) + "\n\r")
    lbl_f_file_result.config(text="Σύνολο: "+str(counter[True]+counter[False])+"\nΈγκυρα: "+str(counter[True])+"\nΆκυρα: "+str(counter[False]))

  #create the window
  main_window = Tk()
  main_window.title("Έλεγχος εγκυρότητας Α.Φ.Μ. (v 2.0)")
  main_window.geometry("600x180")
  main_window.minsize(600,180)

  #fool arround with styling
  style = ttk.Style()
  style.configure("valid.TLabel", background="green")
  style.configure("empty.TLabel", background="white")
  style.configure("invalid.TLabel", background="red")
  style.configure("TNotebook", padding = 10)
  
  #create the Notebook
  tabs = Notebook(main_window)
  f_single = Frame(tabs)
  f_file = Frame(tabs)
  tabs.add(f_single, text="Μεμονομένα Α.Φ.Μ.")
  tabs.add(f_file, text="Λίστα από αρχείο")#add state="disabled" prior to git push until ready
  tabs.pack(anchor="nw")
  
  #add some widgets in f_single tab
  lbl_f_single_instructions = Label(f_single, text="Εισάγετε έναν ΑΦΜ για έλεγχο")
  lbl_f_single_instructions.grid(column=0, row=0)

  lbl_f_single_result = Label(f_single, text="", width=10, justify="center")
  lbl_f_single_result.grid(column=1, row=0, rowspan=2, sticky="ewns")

  txt_f_single_entry = Entry(f_single, width=11)
  txt_f_single_entry.focus()
  txt_f_single_entry.bind("<KeyRelease>", lambda e: _check_single() )
  txt_f_single_entry.grid(column=0,row=1)

  #btn_f_single_submit = Button(f_single, text="Έλεγχος", command=_check_single)
  #btn_f_single_submit.grid(column=0,row=2)
    
  #add some widgets in f_file tab
  lbl_f_file_finput = Label(f_file, text="Άνοιγμα...")
  lbl_f_file_finput.grid(column=0, row=0)
  strv_f_file_input = StringVar()
  txt_f_file_finput = Entry(f_file, textvariable = strv_f_file_input)
  txt_f_file_finput.grid(column=1, row=0)
  btn_f_file_finput = Button(f_file, text="...", width=3, command=_select_input_file)
  btn_f_file_finput.grid(column=2, row=0, sticky="W")
  
  lbl_f_file_foutput = Label(f_file, text="Αποθήκευση ως...")
  lbl_f_file_foutput.grid(column=0, row=1)
  strv_f_file_output = StringVar()
  txt_f_file_foutput = Entry(f_file, textvariable = strv_f_file_output)
  txt_f_file_foutput.grid(column=1, row=1)
  btn_f_file_foutput = Button(f_file, text="...", width=3, command=_select_output_file)
  btn_f_file_foutput.grid(column=2, row=1, sticky="W")
  
  lf_filter = LabelFrame(f_file, text="Επιστροφή")
  lf_filter.grid(column=3, row=0, rowspan=2, sticky="ewns")
  intvar_filter_sel = IntVar()
  rb_filter_all = Radiobutton(lf_filter, text="Όλων", variable=intvar_filter_sel, value=1) #TODO maybe add command
  rb_filter_all.pack(anchor="w")
  rb_filter_all.invoke()
  rb_filter_true = Radiobutton(lf_filter, text="Έγκυρων", variable=intvar_filter_sel, value=2)
  rb_filter_true.pack(anchor="w")
  rb_filter_false = Radiobutton(lf_filter, text="Άκυρων", variable=intvar_filter_sel, value=3)
  rb_filter_false.pack(anchor="w")
  
  lf_result = LabelFrame(f_file, text="Σύνοψη")
  lf_result.grid(column=4, row=0, rowspan=2, sticky="ewns")
  lbl_f_file_result = Label(lf_result, text="", width=12)#TODO bring results
  lbl_f_file_result.pack()
  
  btn_f_file_submit = Button(f_file, text="Επεξεργασία", state="disabled", command=_check_file)
  btn_f_file_submit.grid(column=0, row=2, columnspan=3)
  
  btn_main_exit = Button(main_window, text="Έξοδος", command=sys.exit)
  btn_main_exit.pack(anchor="se")

  main_window.mainloop()
Beispiel #42
0
    def _create_text_tab(self, nb):
        self.dir0 = 1
        self.dir1 = 1
        # populate the third frame with other widgets
        fr = Frame(nb, name='fr')

        lF = LabelFrame(fr, text="Slider")
        fr1 = Frame(lF)
        fr1.grid(row=0, column=0, sticky='nsew')
        from_ = 100
        to = 0
        value = 0
        step = 10
        fontSize = 9
        self.scvar = IntVar()
        scRange = self.any_number_range(from_, to, step)
        scLen = len(scRange[1]) * (fontSize + 10)
        self.sc = Scale(fr1,
                        from_=from_,
                        to=to,
                        variable=self.scvar,
                        orient='vertical',
                        length=scLen,
                        command=self.v_scale)
        self.sc.set(value)
        l1 = Label(fr1, textvariable=self.scvar, width=5)
        l1.grid(row=0, column=0, padx=5, pady=5)
        self.sc.grid(row=0, column=1, padx=5, pady=5)
        fr4 = Frame(fr1)
        fr4.grid(row=0, column=2)
        sc_split = '\n'.join(scRange[0].split())
        lb = Label(fr1, text=sc_split, font=('Courier New', str(fontSize)))
        lb.grid(row=0, column=2, padx=5, pady=5)

        fr2 = Frame(lF, name='fr2')
        fr2.grid(row=0, column=1, sticky='nsew')
        self.schvar = IntVar()
        a = 0
        b = 100
        schRange = self.any_number_range(a, b, s=10)
        schLen = Font().measure(schRange[0])
        self.sch = Scale(fr2,
                         from_=a,
                         to=b,
                         length=schLen,
                         variable=self.schvar,
                         orient='horizontal',
                         command=self.h_scale)

        self.sch.set(0)
        l2 = Label(fr2, textvariable=self.schvar)
        l2.grid(row=1, column=1, pady=2)
        self.sch.grid(row=2, column=1, padx=5, pady=5, sticky='nsew')
        l3 = Label(fr2, text=schRange[0], font=('Courier New', str(fontSize)))
        l3.grid(row=3, column=1, padx=5, pady=5)
        lF.grid(row=0, column=0, sticky='nesw', pady=5, padx=5)

        lF1 = LabelFrame(fr, text="Progress", name='lf')
        pb1var = IntVar()
        pb2var = IntVar()
        self.pbar = Progressbar(lF1,
                                variable=pb1var,
                                length=150,
                                mode="indeterminate",
                                name='pb1',
                                orient='horizontal')
        self.pb2 = Progressbar(lF1,
                               variable=pb2var,
                               length=150,
                               mode='indeterminate',
                               name='pb2',
                               orient='vertical')
        self.pbar["value"] = 25
        self.h_progress()
        self.v_progress()
        self.pbar.grid(row=1, column=0, padx=5, pady=5, sticky='nw')
        self.pb2.grid(row=1, column=1, padx=5, pady=5, sticky='nw')
        l3 = Label(lF1, textvariable=pb1var)
        l3.grid(row=0, column=0, pady=2, sticky='nw')
        l4 = Label(lF1, textvariable=pb2var)
        l4.grid(row=0, column=1, pady=2, sticky='nw')

        sg1 = Sizegrip(fr)
        sg1.grid(row=2, column=2, sticky='e')

        lF1.grid(row=1, column=0, sticky='nesw', pady=5, padx=5)

        # add to notebook (underline = index for short-cut character)
        nb.add(fr, text='Sliders & Others', underline=0)
Beispiel #43
0
class Page1(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.style = Style()

        self.time_frame = LabelFrame(self, text='Time Setting')
        self.hour_label = Label(self.time_frame, text='Hours')
        self.hour_box = Spinbox(self.time_frame, from_=0, to=24)

        self.minute_label = Label(self.time_frame, text='Minutes')
        self.minute_box = Spinbox(self.time_frame, from_=0, to=60)

        self.second_label = Label(self.time_frame, text='Seconds')
        self.second_box = Spinbox(self.time_frame, from_=0, to=60)

        self.break_label = Label(self.time_frame, text='Time During Sessions')
        self.break_var = IntVar()
        self.break_var.set(4)
        self.break_radio_button_3 = Radiobutton(self.time_frame,
                                                text='3 min',
                                                variable=self.break_var,
                                                value=3)
        self.break_radio_button_4 = Radiobutton(self.time_frame,
                                                text='4 min',
                                                variable=self.break_var,
                                                value=4)
        self.break_radio_button_5 = Radiobutton(self.time_frame,
                                                text='5 min',
                                                variable=self.break_var,
                                                value=5)
        self.break_radio_button_6 = Radiobutton(self.time_frame,
                                                text='6 min',
                                                variable=self.break_var,
                                                value=6)
        self.break_radio_button_7 = Radiobutton(self.time_frame,
                                                text='7 min',
                                                variable=self.break_var,
                                                value=7)

        self.name_label = Label(self.time_frame, text='Task Name')
        self.name_entry = Entry(self.time_frame)

        self.reminder_label = Label(self.time_frame, text='Reminder')
        self.reminder_entry = Entry(self.time_frame)

        self.generate_button = Button(self,
                                      text='Generate Task',
                                      command=self.create_task)
        self.save_button = Button(self,
                                  text='Save Configuration',
                                  command=self.save_config)
        self.load_button = Button(self,
                                  text='Load Configuration',
                                  command=self.load_config)
        self.clear_button = Button(self, text='Clear', command=self.clear)

        # GRIDDING OPERATIONS
        self.hour_label.grid(row=1, column=0)
        self.hour_box.grid(row=1, column=1)
        self.minute_label.grid(row=1, column=2)
        self.minute_box.grid(row=1, column=3)
        self.second_label.grid(row=1, column=4)
        self.second_box.grid(row=1, column=5)

        self.break_label.grid(row=2, column=0)
        self.break_radio_button_3.grid(row=2, column=1)
        self.break_radio_button_4.grid(row=2, column=2)
        self.break_radio_button_5.grid(row=2, column=3)
        self.break_radio_button_6.grid(row=2, column=4)
        self.break_radio_button_7.grid(row=2, column=5)

        self.name_label.grid(row=3, column=0)
        self.name_entry.grid(row=3, column=1, columnspan=5, sticky='ew')
        self.reminder_label.grid(row=4, column=0)
        self.reminder_entry.grid(row=4, column=1, columnspan=5, sticky='ew')

        self.generate_button.grid(row=1, column=0, sticky='snew')
        self.save_button.grid(row=2, column=0, sticky='snew')
        self.load_button.grid(row=3, column=0, sticky='snew')
        self.clear_button.grid(row=4, column=0, sticky='snew')

        self.time_frame.grid(row=0, column=0)
        self.grid(row=0, column=0)

    def create_task(self):
        # Task signature: (task_name, task_duration, break_duration, task_reminder=None)
        hours = self.hour_box.get()
        minutes = self.minute_box.get()
        seconds = self.second_box.get()
        break_time = self.break_var.get()
        if hours and seconds and minutes:
            total_time = int(hours) * 3600 + int(minutes) * 60 + int(seconds)
            return Task(self.name_entry.get(), total_time, break_time)
        elif hours == 's':
            return Task('sample task', 5, 3 / 60)

    def save_config(self):
        with open('config.pickle', 'wb+') as config:
            pickle.dump(self.create_task(), config)

    def load_config(self):
        with open('config.pickle', 'rb') as config:
            unpickled_task = pickle.load(config)
            Task.tasks.append(unpickled_task)

    def clear(self):
        self.name_entry.delete(0, 'end')
        self.reminder_entry.delete(0, 'end')
        self.hour_box.set('')
        self.minute_box.set('')
        self.second_box.set('')
Beispiel #44
0
class ChIPSeqFrame( PipelineFrame ) :
    def __init__(self, pipepanel, pipeline_name, *args, **kwargs) :
        PipelineFrame.__init__(self, pipepanel, pipeline_name, *args, **kwargs)
        self.info = None
        
        eframe = self.eframe = LabelFrame(self,text="Options") 
        #,fg=textLightColor,bg=baseColor)
        eframe.grid( row=5, column=1, sticky=W, columnspan=7, padx=10, pady=5 )
        
        label = Label(eframe,text="Pipeline")#,fg=textLightColor,bg=baseColor)
        label.grid(row=3,column=0,sticky=W,padx=10,pady=5)
        Pipelines=["ChIPSeq"]
        Pipeline = self.Pipeline = StringVar()
        Pipeline.set(Pipelines[0])
        
        om = OptionMenu(eframe, Pipeline, *Pipelines, command=self.option_controller)
        om.config()#bg = widgetBgColor,fg=widgetFgColor)
        om["menu"].config()#bg = widgetBgColor,fg=widgetFgColor)
        #om.pack(side=LEFT,padx=20,pady=5)
        om.grid(row=3,column=1,sticky=W,padx=10,pady=5)

        label.grid(row=6, column=0, columnspan=5, sticky=W, padx=10, pady=5)
        self.add_info(eframe)
    
    
    '''
    def set_data_directory( self ):
        fname = askdirectory( initialdir = USER_HOME, 
                             title="Select Data Directory")
        self.datapath.set(fname)                                    
        #count number
        self.data_count['text'] = str(
            len([fn for fn in listdir(fname) if fn.endswith(filetype) or fn.endswith('.fastq')] )
        ) 
        print( "Found", self.data_count['text'], filetype, "files!" )
    '''
    
    
    def add_info( self, parent ) :
        if not self.info :
            self.info = LabelFrame(parent, text='Peak Call Info')
            self.info_text = Text( self.info,
                             width=50,
                             height=8,
                             #bg=projectBgColor,
                             #fg=projectFgColor,
                             font=("nimbus mono bold","11")
                            )

            self.info_save_button = Button(self.info, 
                                            text="Save", 
                                            command = self.writeinfo )
            self.info_load_button = Button(self.info,
                                            text="Load",
                                            command = self.readinfo )
            
            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.info_load_button.grid( row=5, column=5, padx=10, pady=5 )
            self.info_save_button.grid( row=5, column=6, padx=10, pady=5 )
            self.info_text.grid( row=1,  rowspan=3, 
                                 column=1,  columnspan=7,
                                 padx=5, pady=5 )

        self.info.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
        
            
    def writeinfo( self ) :
        self.writepaste( 'peakcallinfo.csv', self.info_text )
    
    def readinfo( self ) :
        self.readpaste( 'peakcallinfo.csv', self.info_text )