view commons/pyRepetUnit/convCoord/ConvMapChr2Chunk.py @ 18:94ab73e8a190

Uploaded
author m-zytnicki
date Mon, 29 Apr 2013 03:20:15 -0400
parents
children
line wrap: on
line source

from copy import deepcopy
from commons.core.sql.TableMapAdaptator import TableMapAdaptator
from commons.core.coord.Map import Map
import os

class ConvMapChr2Chunk(object):

    def __init__(self, db, table, chunk_table, outtable):
        self._tablename = table
        self._chunk_table = chunk_table
        self._db = db
        self._outtable = outtable
        
    def convert(self):
        """
        Convert a 'set' table format.
        """
        temp_file=str(os.getpid()) + ".on_chunk"
        fout=open(temp_file,'w')

        str_mask = "SELECT * FROM "+\
            self._chunk_table + " WHERE chr='%s' AND ("+\
            "(%d BETWEEN LEAST(start,end) AND GREATEST(start,end))"+\
            " OR (%d BETWEEN LEAST(start,end) AND GREATEST(start,end))"+\
            " OR (%d <= LEAST(start,end) AND %d >= GREATEST(start,end)));"
                            
        iTMA = TableMapAdaptator(self._db, self._tablename)
        chr_list = iTMA.getSeqNameList()

        for chr in chr_list:        
            mlist = iTMA.getMapListFromChr(chr)  
            for m in mlist:
                sql_cmd = str_mask%(m.seqname,m.getMin(),m.getMax(),m.getMin(),m.getMax())
                self._db.execute(sql_cmd)
                res = self._db.fetchall()
                for i in res:
                    chunk = Map(i[0],i[1],int(i[2]),int(i[3]))
                
                    new_m = deepcopy(m)
                    new_m.seqname = chunk.name
 
                    if (m.start > chunk.start and m.start < chunk.end):
                        new_m.start = m.start - chunk.start + 1 
                    if (m.end > chunk.start and m.end < chunk.end):
                        new_m.end = m.end - chunk.start + 1
                                                   
                    if m.isOnDirectStrand():
                        if m.start <= chunk.start:
                            new_m.start = 1
                        if m.end >= chunk.end:
                            new_m.end = chunk.end - chunk.start + 1
                    else:
                        if m.end <= chunk.start:
                            new_m.end = 1
                        if m.start >= chunk.end:
                            new_m.start = chunk.end - chunk.start + 1
                            
                    new_m.write(fout)
 
        fout.close()
    
        self._db.createTable(self._outtable, "map", temp_file)
    
        os.remove(temp_file)