def get(self, loc, strand="+"): """ **Purpose** get the data between location 'loc' **Arguments** loc (Required) a valid location or string location. strand (Optional, default = "+") strand, but only valid for stranded tracks **Returns** an 'array('i', [0, 1, 2 ... n])' contiginous array """ try: if loc["chr"]: pass except TypeError: # probably a location string. try to cooerce loc = location(loc=loc) left_most_block = int(abs(math.floor(loc["left"] / self.block_size))) right_most_block = int( abs(math.ceil((loc["right"] + 1) / self.block_size))) blocks_required = [ "%s:%s" % (loc["chr"], b) for b in range(left_most_block * self.block_size, right_most_block * self.block_size, self.block_size) ] ret_array = array('i', []) for blockID in blocks_required: # this is the span location of the block block_loc = location(chr=blockID.split(":")[0], left=blockID.split(":")[1], right=int(blockID.split(":")[1]) + self.block_size - 1) # check if the block already exists if self.__has_block(blockID): # it does, get it. block = self.__get_block(blockID) this_block_array_data = block # get back the usable data else: # block not in db, fake a block instead. this_block_array_data = array( 'i', [0 for x in range(self.block_size)]) #print "b", block #print self.__get_block(blockID) # modify the data for pos in range(self.block_size): # iterate through the array. local_pos = block_loc["left"] + pos # see add_location for details if local_pos < (loc["right"] + 1): # still within block if local_pos >= loc["left"] and local_pos <= ( loc["right"] + 1): # within the span to increment. ret_array.append(this_block_array_data[pos]) return (ret_array)
def send_head(self): """ Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. """ path, query = self.translate_get(self.path) print(path, query) if query: if "loc" in query and query["loc"]: self.update_app(query["loc"]) elif "chr" in query and "left" in query and "right" in query: self.update_app(loc=location(chr=query["chr"], left=query["left"], right=query["right"])) f = None if os.path.isdir(path): if not self.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(301) self.send_header("Location", self.path + "/") self.end_headers() return (None) for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: # No index, serve a directory listing self.send_error(404, "File not found") ctype = self.guess_type(path) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open(path, 'rb') except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f
def getLocation(self): """ **Purpose** get the current view genome location **Arguments** None **Returns** returns a <location> """ return (location(chr=self.chromosome, left=self.lbp, right=self.rbp))
def OnGotoLocationEdit(self, event): try: loc_value = self.textGoToLoc.GetValue() # do a few simple tidy ups so I can load into loc. loc_value = loc_value.replace(",", "") loc = location(loc=loc_value) if loc: self.draw.setLocation(loc=loc) else: raise TypeError except (TypeError, IndexError): # colour the textBox Red; pass self._updateDisplay() event.Skip()
def _updateDisplay(self, loc=None, redrawDisplay=True, event=None): """ (Internal) update the gui forms and changeable elements. redrawDisplay will not redraw the gui, it just redraws the gDrawPanel """ if loc: self.draw.setLocation(loc=loc) self.lastValidLocation = self.draw.getLocation() if redrawDisplay: self.draw.forceRedraw() # text boxes. self.textGoToLoc.SetValue( str( location(chr=self.draw.chromosome, left=self.draw.lbp, right=self.draw.rbp)))
def get_all_bookmarks(self): """ **Purpose** returns a list of all of the bookmarks in the db. **Arguments** None **Results** returns a list of dictionaries of the form [{"location": <location>, "notes": <string>} .. n] """ self.__cursor.execute("SELECT * FROM marks") # sensibly format: return [{ "loc": location(loc=i[1]), "notes": i[5] } for i in self.__cursor.fetchall()]
def update_app(self, loc=None): assert loc, "no location!" cf.draw.setLocation(loc=location(loc=loc)) cf.draw.exportImage( os.path.join(sys.path[0], "htdocs/tmp/last_image.png"))
""" This should be how to use the chipFish from the command line. And output svgs etc. """ import os from app import app from glbase_wrapper import location a = app() a.startup(os.path.expanduser("~/Projects/AP2aGCM/trks/track_list.txt")) oh = open(os.path.expanduser("~/Projects/AP2aGCM/trks/For raw signal.txt"), "rU") for lin in oh: tt = lin.strip().split("\t") print(tt) if tt[0] != "gname": a.draw.setLocation(loc=location(loc=tt[1]).expand(10000)) a.draw.exportImage( os.path.expanduser("~/Projects/AP2aGCM/trks/%s_%s.png" % (tt[0], str(tt[1].replace(":", "-")))), type="png")
def OnPaint(self, event, cairo_context=None): """ **Event** Call to get Cairo to paint, this is done automatically if bound to a Panel. You do not need to call this explicitly. If you pass a Cairo Context cairo will paint to that rather than generate a context for the gui. """ # try to get cairo: if not cairo_context: try: dc = wx.PaintDC( self.panel) # make each time OnPaint is called. #dc = wx.AutoBufferedPaintDC(self) # not clear why this doesn't work ... self.size = dc.GetSizeTuple() self.setViewPortSize(self.size[0], self.size[1]) cairo_context = wx.lib.wxcairo.ContextFromDC(dc) except: raise ErrorCairoAcquireDevice self.ctx = cairo_context draw_modes_dict = { "gene": self.__drawGene, "lncRNA": self.__drawGene, "microRNA": self.__drawGene, "graph": self.__drawTrackGraph, "graph_split_strand": self.__drawTrackGraph_split_strand, "bar": self.__drawTrackBar, "spot": self.__drawTrackSpot } self.delta = self.rbp - self.lbp self.deltaf = float(self.delta) self.bps_per_pixel = self.delta / float(self.w) self.curr_loc = location(chr=self.chromosome, left=self.lbp, right=self.rbp) # kill all the colission boxes self.__col_boxs = [] # blank the screen: self.__setPenColour(opt.graphics.screen_colour) self.ctx.rectangle(0, 0, self.fullw, self.h) self.ctx.fill() if opt.draw.double_lines_for_genome: self.__drawChr(None) # get the new paintQ: # draw the genome: genome_items = self.genome.getAllDrawableFeaturesInRange(self.curr_loc) for item in genome_items: draw_modes_dict[item["type"]](item) # collect the data for the tracks and draw them on the screen. for track in self.tracks: # basic data: draw_data = { "type": track["type"], "track_location": track["track_location"], "name": track["data"].name } if track["type"] == "graph": draw_data["array"] = track["data"].get_data( "graph", location(loc=self.curr_loc), resolution=self.bps_per_pixel, read_extend=50) elif track["type"] == "bar": draw_data["array"] = track["data"].get_data( "bar", location(loc=self.curr_loc), resolution=self.bps_per_pixel, read_extend=0) elif track["type"] == "spot": draw_data["array"] = track["data"].get_data( "spot", location(loc=self.curr_loc)) elif track["type"] == "graph_split_strand": draw_data["array"] = track["data"].get_data( "graph", location(loc=self.curr_loc), strand=True, resolution=self.bps_per_pixel, read_extend=0) # and draw: colbox = draw_modes_dict[draw_data["type"]](draw_data) # add a collision item if if colbox: self.__col_boxs.append(bbox(colbox, track, "track")) self.__col_boxs.append(bbox(self.__drawRuler(), None, "ruler")) if opt.draw.scale_bar: self.__drawScaleBar() # any further (internal) drawing goes here. if opt.debug.draw_collision_boxes: self.__debug_draw_col_boxes() return (True)
def OnInit(self): """ (Event) Executed on the initialisation of the form. Main entry point for chipFish. """ # errors should be put into a log; if not opt.generic.debug: sys.stderr = self # silence errors. sys.stdout = self print( "chipFish (c) 2009, oAxiom, %s" % (time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()))) # log. #load locale: self.locale = locale("en-gb") # load the gui self.res = xrc.XmlResource('gui_parent.xrc') # load the mainFrame self.main = self.res.LoadFrame(None, "mainFrame") # load the locale into the gui: self.locale.load_main_gui(self.main) # -------------------------------------------------------------- # These are user state variables, currently hard coded # but later must go freefrom. # set up and load the genome # (In future this will load the initial state here) self.g = glload("data/mm8_refGene.glb") self.draw = gDraw.gDraw( self.g) # drawer must have access to the genome format_chip_lists = {"loc": {"code": "location(loc=column[0])"}} self.draw.bindTrack( peaklist(filename="data/Matches_ESEsrrb_esrrf_5bp_soxf.bed", format=format_bed)) self.draw.bindTrack( peaklist(filename="../../Final Peak Lists/ESEsrrb_peaks.csv", format=format_chip_lists)) self.draw.bindTrack( peaklist(filename="../../Final Peak Lists/ESSox2_peaks.csv", format=format_chip_lists)) self.draw.bindTrack( peaklist(filename="../../Final Peak Lists/ESOct4_peaks.csv", format=format_chip_lists)) #self.draw.bindTrack(peaklist(filename="../../Final Peak Lists/ESNanog_peaks.csv", format=format_chip_lists)) #self.draw.bindTrack(peaklist(filename="../../Final Peak Lists/ESKlf4_peaks.csv", format=format_chip_lists)) #self.draw.bindTrack(peaklist(filename="../../Final Peak Lists/ESp300_peaks.csv", format=format_chip_lists)) self.draw.bindTrack( track(filename="data/NSMash1_new.trk", name="NS5 Mash1 ChIP-seq")) #self.draw.bindTrack(track(filename="data/SpMash1_new.trk", name="Spinal Cord Mash1 ChIP-seq")) #self.draw.bindTrack(track(filename="data/TcMash1_new.trk", name="Telencephalon Mash1 ChIP-seq")) #self.draw.bindTrack(track(filename="data/NS_H3K4me3.trk", name="NS5 H3K4me3")) #self.draw.bindTrack(track(filename="data/NS_H3K27me3.trk", name="NS5 H3K27me3"), track_type="bar") #self.draw.bindTrack(track(filename="data/NS_H3K36me3.trk", name="NS5 H3K36me3"), track_type="bar") #self.draw.bindTrack(track(filename="data/ES_H3K4me3.trk", name="ES H3K4me3")) #self.draw.bindTrack(track(filename="data/ES_H3K36me3.trk", name="ES H3K4me3"), track_type="bar") #self.draw.bindTrack(track(filename="data/MEF_H3K4me3.trk", name="MEF H3K4me3")) self.draw.setLocation( loc=location(loc="chr17:15061372-15127565") ) # Interesting view of the ChIP-seq (Dll1?) chr17:15,064,087-15,088,782 # end of user hard-coded segments. # -------------------------------------------------------------- self.__rebind_bookmarks( "mm8") # I have to bodge this as self.g has a mangled name. self.__userdata = userconfig() # bind the gPanel; sizer = wx.BoxSizer(wx.VERTICAL) self.gui_panel = wx.xrc.XRCCTRL(self.main, "gui_panel") gDrawPanel = wx.xrc.XRCCTRL(self.main, "gDrawPanel") self.draw.bindPanel(gDrawPanel) # bind the drawPanel to gDraw draw_panel = self.draw.getPanel() sizer.Add(draw_panel, 2, wx.EXPAND, 0) # add the panel to the gui gDrawPanel.SetSizer(sizer) # add it to the GUI # bind events to the GUI. self.Bind(wx.EVT_LEFT_DOWN, self.__mouseLeftDown, draw_panel) self.Bind(wx.EVT_LEFT_UP, self.__mouseLeftUp, draw_panel) self.Bind(wx.EVT_BUTTON, self.OnViewLeft, xrc.XRCCTRL(self.main, "butViewLeft")) self.Bind(wx.EVT_BUTTON, self.OnViewRight, xrc.XRCCTRL(self.main, "butViewRight")) self.Bind(wx.EVT_BUTTON, self.OnViewBigRight, xrc.XRCCTRL(self.main, "butViewBigRight")) self.Bind(wx.EVT_BUTTON, self.OnViewBigLeft, xrc.XRCCTRL(self.main, "butViewBigLeft")) self.Bind(wx.EVT_BUTTON, self.OnButZoomIn, xrc.XRCCTRL(self.main, "butZoomIn")) self.Bind(wx.EVT_BUTTON, self.OnButZoomOut, xrc.XRCCTRL(self.main, "butZoomOut")) self.Bind(wx.EVT_BUTTON, self.OnGotoLocationEdit, xrc.XRCCTRL(self.main, "butGoToLoc")) # menu events should get by ID: ID_ABOUT self.Bind(wx.EVT_MENU, self.OnMenuAbout, id=xrc.XRCID("about")) self.Bind(wx.EVT_MENU, self.OnMenuQuit, id=xrc.XRCID("quit")) self.Bind(wx.EVT_MENU, self.OnMenuAddBookmark, id=xrc.XRCID("bookmarkThisLocation")) self.Bind(wx.EVT_MENU, self.OnMenuExportAsPng, id=xrc.XRCID("exportCurrentViewAsPng")) self.Bind(wx.EVT_MENU, self.OnMenuFindGene, id=xrc.XRCID("findGene")) # get changable elements from the gui and store them locally. # (See _updateDisplay()) self.textGoToLoc = wx.xrc.XRCCTRL(self.main, "textGoToLoc") #print "textGoToLoc", self.textGoToLoc self.main.Show() self.main.Maximize(True) # force a redraw: #self._updateDisplay() print("End %s" % time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())) return (True)
def startup(self, tracklist=None): """ startup the server. Use this to get started proper and change genomes etc. **Arguments** tracklist A text file containing the path to the track files Not Implemented """ self.draw = gDraw.gDraw() if tracklist: # Although it doesn't really make much sense not to supply a tracklist oh = open(tracklist, "rt") track_path = os.path.dirname(tracklist) mode = None for line in oh: if not line.strip(): # tolerate empty lines in spec sheet continue if "#" in line[0]: continue if ":" in line: # The order of the following modes is important - for example, "bed:" will also # collect "macs_bed" so "macs_bed" must go first. # There can only be one mode # Gods, just do strip() and regex it!?!?!!!! if "kde_track:" in line: # Must go before "track" mode = "kde_track" elif "split_track" in line: mode = "split_track" elif "track:" in line: mode = "track" elif "macs_bed:" in line: # must go before bed mode = "macs_bed" elif "bed:" in line: mode = "bed" elif "genome:" in line: mode = "genome" elif "flat:" in line: mode = "flat" elif 'genome_sql:' in line: mode = 'genome_sql' elif 'repeat_sql:' in line: mode = 'repeat_sql' else: raise ErrorUnrecognisedTrackMode(mode) # process options options = self.__do_options(line.split(":")[-1], mode) elif mode: path = os.path.expanduser(track_path) tt = line.strip().split() name = os.path.expanduser(tt[0]) track_opts = {} if len(tt) > 1: track_opts = self.__do_options_per_track(tt[1]) if "abs_path" in options and options["abs_path"] == "True": tail, head = os.path.split(name) # The path will be relative to the path, not relative to chipFish. Which could be anywhere # path = os.path.expanduser( os.path.normpath(os.path.join(track_path, tail))) name = head #print path, name if name: options = copy.deepcopy(options) options.update(track_opts) per_track_options = {} if len( tt ) > 1 and '=' in line: # see if it has valid per track options; per_track_options = self.__do_options_per_track( ' '.join(tt[1:])) label = None if 'label' in per_track_options: label = per_track_options['label'] if mode == "flat": self.draw.bindTrack( flat_track(filename=os.path.join(path, name)), track_type="graph", options=options, label=label) elif mode == "bed": self.draw.bindTrack(genelist(filename=os.path.join( path, name), format=format.bed), options=options, label=label) elif mode == "macs_bed": f = format.minimal_bed f["skiplines"] = 1 # Changes in recent version of macs bed. self.draw.bindTrack(genelist(filename=os.path.join( path, name), format=f), options=options, label=label) elif mode == "genome": # must be a glb # First see if I can get it out of the pre-packaged genomes: try: g = genomes() if name in g: print(name) self.draw.bindTrack(g.get_genome(name)) continue except AssertionError: # Okay, that did'nt work. see If I can get a file in this dir: self.draw.bindTrack( glload(os.path.join(path, name))) continue # Okay, assume the user knows what they are doing and just grab the file they asked for: self.draw.bindTrack(glload(name), track_type="genome") elif mode == "repeat_sql": self.draw.bindTrack( genome_sql(filename=os.path.join(path, name)), track_type='repeats') elif mode == "genome_sql": self.draw.bindTrack( genome_sql(filename=os.path.join(path, name)), track_type='genome_sql') oh.close() self.draw.setViewPortSize(opt.draw.view_port_width) self.draw.setLocation( loc=location(loc="chr1:172724244-172859108" )) # Load a dummy location, my favourite gene Stat3
""" **Purpose** returns a list of all of the bookmarks in the db. **Arguments** None **Results** returns a list of dictionaries of the form [{"location": <location>, "notes": <string>} .. n] """ self.__cursor.execute("SELECT * FROM marks") # sensibly format: return [{ "loc": location(loc=i[1]), "notes": i[5] } for i in self.__cursor.fetchall()] def del_bookmark(self, location, notes): pass if __name__ == "__main__": # to go into a test suite later. b = bookmarks("mm8") b.add_bookmark(location(loc="chr17:15064087-15088782"), "Dll1") b.add_bookmark(location(loc="chr17:15064087-15088782"), "Dll3") print(b._get_all_bookmarks())
for blockID in self.cache: self.__commit_block(blockID, self.cache[blockID]) self.cache = {} self.cacheQ = [] self.__connection.commit() # commit all the __commit_block() c = self.__connection.cursor() c.execute("VACUUM") self.__connection.commit() if __name__ == "__main__": # a few testers to see how it works. t = track(filename="data/test.trk", new=True) t.add_location(location(loc="chr1:1-30")) t.add_location(location(loc="chr1:1-30")) t.add_location(location(loc="chr1:10-22")) t.add_location(location(loc="chr1:10-21")) t.add_location(location(loc="chr1:10-20")) t.add_location(location(loc="chr1:10-19")) t.add_location(location(loc="chr1:11-21")) t.add_location(location(loc="chr1:12-22")) t.add_location(location(loc="chr1:24-25")) t.add_location(location(loc="chr1:25-26")) t.add_location(location(loc="chr1:26-27")) t.add_location(location(loc="chr1:26-26")) t.add_location(location(loc="chr1:27-27")) t.add_location(location(loc="chr1:1-100"), strand="+") t.add_location(location(loc="chr1:26-100"), strand="+")