示例#1
0
    def write_tlsout_file(self, chain, cpartition):
        """Writes the TLSOUT file for the segmentation.
        """
        basename = "%s_CHAIN%s_NTLS%d" % (self.struct_id, chain.chain_id,
                                          cpartition.num_tls_segments())
        tlsout_path = "%s.tlsout" % (basename)

        struct_id = self.struct_id
        chain_id = chain.chain_id

        tls_file = TLS.TLSFile()
        tls_file.set_file_format(TLS.TLSFileFormatTLSOUT())

        for tls in cpartition.iter_tls_segments():
            ## don't write out bypass edges
            if tls.method != "TLS":
                continue

            tls_desc = TLS.TLSGroupDesc()
            tls_file.tls_desc_list.append(tls_desc)
            tls_desc.set_tls_group(tls.tls_group)
            for frag_id1, frag_id2 in tls.iter_segment_ranges():
                tls_desc.add_range(chain_id, frag_id1, chain_id, frag_id2,
                                   "ALL")

        tls_file.save(open(tlsout_path, "w"))

        return tlsout_path
示例#2
0
def main(pdb_path, tls_out_path, calc_tls):

    struct = FileIO.LoadStructure(file=pdb_path)

    ## calculate one set of TLS tensors from all the amino acid atoms
    if calc_tls == True:
        tls = TLS.TLSGroup()

        for res in struct.iter_amino_acids():
            for atm in res.iter_atoms():
                tls.append(atm)

        tls.origin = tls.calc_centroid()
        tls.calc_tls_tensors()
        print_TLSGroup(tls)

    else:
        tls_file = TLS.TLSFile()

        ## get TLS groups from REMARK statments in PDB file
        if tls_out_path == None:
            tls_file.set_file_format(TLS.TLSFileFormatPDB())
            try:
                tls_file.load(open(pdb_path, "r"), pdb_path)
            except IOError, e:
                print "[Error] %s: %s" % (str(e), pdb_path)

        ## or get TLS groups from REFMAC TLSOUT file
        else:
示例#3
0
def LoadStructure(struct_source):
    """Loads Structure, chooses a unique struct_id string.
    Also, search the REMARK records for TLS group records.  If they
    are found, then add the TLS group ADP magnitude to the B facors of
    the ATOM records.
    """
    ## determine the argument type
    if isinstance(struct_source, str):
        file_path = struct_source
        console.kvformat("LOADING STRUCTURE", file_path)
        fobj = open(file_path, "r")
    elif hasattr(struct_source, "__iter__") and hasattr(struct_source, "seek"):
        console.kvformat("LOADING STRUCTURE", str(struct_source))
        fobj = struct_source
    else:
        raise ValueError

    ## load struct
    struct = FileIO.LoadStructure(file = fobj, distance_bonds = True)

    console.kvformat("HEADER", struct.header)
    console.kvformat("TITLE", struct.title)
    console.kvformat("EXPERIMENTAL METHOD", struct.experimental_method)
    
    ## set the structure ID
    if conf.globalconf.struct_id is not None:
        struct_id = conf.globalconf.struct_id
    else:
        struct_id = struct.structure_id
        conf.globalconf.struct_id = struct_id
    struct.structure_id = struct_id

    console.endln()

    ## if there are REFMAC5 TLS groups in the REMARK records of
    ## the PDB file, then add those in
    tls_file = TLS.TLSFile()
    tls_file.set_file_format(TLS.TLSFileFormatPDB())

    ## return to the beginning of the file and read the REMARK/TLS records
    fobj.seek(0)
    tls_file.load(fobj)

    if len(tls_file.tls_desc_list) > 0:
        console.stdoutln("ADDING TLS GROUP Bequiv TO ATOM TEMPERATURE FACTORS")
        console.stdoutln("    NUM TLS GROUPS: %d" % (len(tls_file.tls_desc_list)))

        ## assume REFMAC5 groups where Utotal = Utls + Biso(temp_factor)
        for tls_desc in tls_file.tls_desc_list:
            tls_group = tls_desc.construct_tls_group_with_atoms(struct)
            console.stdoutln("    TLS GROUP: %s" % (tls_group.name))
            for atm, Utls in tls_group.iter_atm_Utls():
                bresi = atm.temp_factor
                atm.temp_factor = bresi + (Constants.U2B * numpy.trace(Utls) / 3.0)
                atm.U = (Constants.B2U * bresi * numpy.identity(3, float)) + Utls

        console.endln()

    return struct
示例#4
0
    def fit_to_chain(self, chain):
        """Re-sets all derived information in the TLSSegment.
        """
        ## cut segment from chain using segment ranges
        segments = []
        for frag_id1, frag_id2 in self.segment_ranges:
            segments.append(chain[frag_id1:frag_id2])
        self.segments = segments

        ## put all atoms in the segment into a new TLSGroup instance
        tls_group = TLS.TLSGroup()
        for segment in self.segments:
            for atm in segment.iter_all_atoms():
                if atm.include is True:
                    tls_group.append(atm)
        self.tls_group = tls_group

        if len(self.tls_group) != self.num_atoms():
            console.stderrln(
                "fit_to_chain: EEK! (%s) len(self.tls_group)=%d != self.num_atoms()=%d"
                % (self, len(self.tls_group), self.num_atoms()))
            raise SystemExit

        ## fit the TLS group parameters
        try:
            self.fit_tls_parameters(chain)
        except:
            print console.formatExceptionInfo()

        ## helpful additions
        tls_info = self.tls_group.calc_tls_info()
        itls_info = TLS.calc_itls_center_of_reaction(self.tls_group.itls_T,
                                                     self.tls_group.itls_L,
                                                     self.tls_group.itls_S,
                                                     self.tls_group.origin)

        self.tls_info = tls_info
        self.itls_info = itls_info

        if conf.globalconf.tls_model in ["ISOT", "NLISOT"]:
            self.tls_group.model = "ISOT"
            self.model_tls_info = itls_info
        elif conf.globalconf.tls_model in ["ANISO", "NLANISO"]:
            self.tls_group.model = "ANISO"
            self.model_tls_info = tls_info

        try:
            self.rmsd_b = tls_calcs.calc_rmsd_tls_biso(self.tls_group)
        except:
            print console.formatExceptionInfo()
示例#5
0
def refmac_pure_tls_prep(xyzin, tlsin_list, wilson, xyzout, tlsout):
    """Use TLS model (without Uiso) for each atom. Output xyzout with the 
    B-factors reset to either the Bmean or the Wilson B value.
    """
    ## load structure
    struct = FileIO.LoadStructure(fil=xyzin)

    ## load and construct TLS groups
    tls_group_list = []
    tls_file = TLS.TLSFile()
    tls_file.set_file_format(TLS.TLSFileFormatPureTLSOUT())
    tls_file_format = TLS.TLSFileFormatPureTLSOUT()
    for tlsin in tlsin_list:
        tls_desc_list = tls_file_format.load(open(tlsin, "r"))
        for tls_desc in tls_desc_list:
            tls_file.tls_desc_list.append(tls_desc)
            tls_group = tls_desc.construct_tls_group_with_atoms(struct)
            tls_group.tls_desc = tls_desc
            tls_group_list.append(tls_group)

    ## set the extra Uiso for each atom
    for tls_group in tls_group_list:

        Bmean = 0.0
        sum_Biso = 0.0
        num_atms = 0
        for atm, Utls in tls_group.iter_atm_Utls():
            num_atms += 1
            sum_Biso += atm.temp_factor

## EAM Aug 2011: num_atms goes to zero if there are atom selection problems.
## The output files will contain empty groups, but at least it doesn't crash.
        if num_atms > 0:
            Bmean = sum_Biso / num_atms

        ## reset the TLS tensor values in the TLSDesc object so they can be
        ## saved
        tls_group.tls_desc.set_tls_group(tls_group)

        ## reset atm.temp_factor to the Bmean for this TLS group
        for atm, Utls in tls_group.iter_atm_Utls():
            atm.temp_factor = Bmean
            atm.temp_factor = wilson

    ## save the new xyzout file with temp_factors reset to "wilson" value
    FileIO.SaveStructure(fil=xyzout, struct=struct)

    ## save the REFMAC-format file, but without T, L, S, and ORIGIN values
    tls_file.save(open(tlsout, "w"))
示例#6
0
文件: tls_calcs.py 项目: masci/mmLib
def calc_mean_biso_tls(chain, cpartition):
    """Calculates the mean B value per residue in the chain (as calculated in 
    the chain optimization). It also performs a Skittles evaluation of the
    junctions between the "C" and "N" atoms of neighbouring residues.
    """
    chain_id = chain.chain_id
    num_tls = cpartition.num_tls_segments()
    num_res = chain.count_fragments()
    biso = numpy.zeros(num_res, float)

    for i, tls in enumerate(cpartition.iter_tls_segments()):
        tls_group = tls.tls_group

        T = tls_group.itls_T # float(3)
        L = tls_group.itls_L # array(3,3)
        S = tls_group.itls_S # array(3): S[0], S[1], S[2]
        O = tls_group.origin # array(3)

        for frag in tls.iter_fragments():
            n = 0
            b_sum_tls = 0.0

            for atm in frag.iter_all_atoms():
                if atm.include is False:
                    continue

                n += 1
                b_sum_tls += Constants.U2B * TLS.calc_itls_uiso(
                    T, L, S, atm.position - O)

            if n > 0:
                biso[frag.ifrag] = b_sum_tls / n

    return biso
示例#7
0
    def write_data_file(self):
        nrows = len(self.cpartition.chain)
        ncols = self.cpartition.num_tls_segments() + 1
        tbl = table.StringTable(nrows, ncols, "?")

        frag_id_iter = itertools.imap(lambda frag: frag.fragment_id, self.cpartition.chain.iter_fragments())
        tbl.set_column(0, 0, frag_id_iter)
        
        for itls, tls in enumerate(self.cpartition.iter_tls_segments()):
            tls_group = tls.tls_group

            T = tls_group.itls_T
            L = tls_group.itls_L
            S = tls_group.itls_S
            O = tls_group.origin

            for frag in tls.iter_fragments():
                atm = frag.get_atom("CA")
                if atm is None:
                    continue
                i = frag.ifrag
                b_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
                tbl[i, itls + 1] = atm.temp_factor - b_tls

        open(self.txt_path, "w").write(str(tbl))
示例#8
0
def calc_mean_biso_tls(chain, cpartition):
    """Calculated the mean B value per residue in the chain
    as calculated in the chain optimization.
    """
    num_res = chain.count_fragments()
    biso = numpy.zeros(num_res, float)

    for i, tls in enumerate(cpartition.iter_tls_segments()):
        tls_group = tls.tls_group

        T = tls_group.itls_T
        L = tls_group.itls_L
        S = tls_group.itls_S
        O = tls_group.origin

        for frag in tls.iter_fragments():
            n = 0
            b_sum_tls = 0.0

            for atm in frag.iter_all_atoms():
                if atm.include is False:
                    continue

                n += 1
                b_sum_tls += Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)

            if n > 0:
                biso[frag.ifrag] =  b_sum_tls / n

    return biso
示例#9
0
def calc_mean_biso_tls(chain, cpartition):
    """Calculates the mean B value per residue in the chain (as calculated in 
    the chain optimization). It also performs a Skittles evaluation of the
    junctions between the "C" and "N" atoms of neighbouring residues.
    """
    chain_id = chain.chain_id
    num_tls = cpartition.num_tls_segments()
    num_res = chain.count_fragments()
    biso = numpy.zeros(num_res, float)

    for i, tls in enumerate(cpartition.iter_tls_segments()):
        tls_group = tls.tls_group

        T = tls_group.itls_T  # float(3)
        L = tls_group.itls_L  # array(3,3)
        S = tls_group.itls_S  # array(3): S[0], S[1], S[2]
        O = tls_group.origin  # array(3)

        for frag in tls.iter_fragments():
            n = 0
            b_sum_tls = 0.0

            for atm in frag.iter_all_atoms():
                if atm.include is False:
                    continue

                n += 1
                b_sum_tls += Constants.U2B * TLS.calc_itls_uiso(
                    T, L, S, atm.position - O)

            if n > 0:
                biso[frag.ifrag] = b_sum_tls / n

    return biso
示例#10
0
文件: gnuplots.py 项目: salotz/mmLib
    def write_data_file(self):
        """Generate the data file and return the filename.
        """
        nrows = len(self.cpartition.chain)
        ncols = 1 + 3 * self.cpartition.num_tls_segments()
        tbl = table.StringTable(nrows, ncols, "?")

        mpred = lambda f: f.fragment_id
        frag_id_iter = itertools.imap(mpred, self.cpartition.chain.iter_fragments())
        tbl.set_column(0, 0, frag_id_iter)

        for itls, tls in enumerate(self.cpartition.iter_tls_segments()):
            tls_group = tls.tls_group
            tls_info = tls.model_tls_info
            O = tls_info["COR"]

            for frag in tls.iter_fragments():
                ## FIXME: This should be able to handle either one
                atm = frag.get_atom("CA")  ## for amino acids
                # atm = frag.get_atom("P") ## for nucleic acids
                if atm is None:
                    continue

                # if frag.get_atom("CA") is not None:
                #    atm = frag.get_atom("CA")
                #    console.stdoutln("CA_ATOM: %s" % str(atm))

                # elif frag.get_atom("P") is not None:
                #    atm = frag.get_atom("P")

                i = frag.ifrag

                for n, Lx_val, Lx_vec, Lx_rho, Lx_pitch in [
                    (0, "L1_eigen_val", "L1_eigen_vec", "L1_rho", "L1_pitch"),
                    (1, "L2_eigen_val", "L2_eigen_vec", "L2_rho", "L2_pitch"),
                    (2, "L3_eigen_val", "L3_eigen_vec", "L3_rho", "L3_pitch"),
                ]:

                    Lval = tls_info[Lx_val]
                    Lvec = tls_info[Lx_vec]
                    Lrho = tls_info[Lx_rho]
                    Lpitch = tls_info[Lx_pitch]

                    if numpy.allclose(Lval, 0.0):
                        continue

                    dvec = TLS.calc_LS_displacement(O, Lval, Lvec, Lrho, Lpitch, atm.position, conf.ADP_PROB)
                    tbl[i, 1 + 3 * itls + n] = AtomMath.length(dvec)

        flatfile_write(
            "LibrationAnalysis: data", "LIAN", "DATA", str(tbl), self.chain.chain_id, self.cpartition.num_tls_segments()
        )

        open(self.txt_path, "w").write(str(tbl))
示例#11
0
def IsotropicADPDataSmoother(chain, num_smooth=1):
    """Experimental data smoothing of temperature factors
    """
    console.endln()
    console.stdoutln("SMOOTHING CHAIN %s ADPs" % (chain.chain_id))
    conesole.kvformat("SMOOTH WINDOW", 2 * num_smooth + 1)

    num_frags = len(chain)

    smooth_uiso = dict()
    ifrag_start = num_smooth
    ifrag_end = num_frags - num_smooth - 1

    for ifrag in xrange(ifrag_start, ifrag_end + 1):
        smooth_frag = chain[ifrag]
        frag1 = chain[ifrag - num_smooth]
        frag2 = chain[ifrag + num_smooth]

        IT, IL, IS, IOrigin = IsotropicFitSegmentOutlierRejection(
            chain, frag1.fragment_id, frag2.fragment_id)

        for atm, uiso in TLS.iter_itls_uiso(smooth_frag.iter_all_atoms(), IT,
                                            IL, IS, IOrigin):
            smooth_uiso[atm] = uiso

        if ifrag == ifrag_start:
            for i in range(ifrag_start):
                smooth_frag = chain[i]
                for atm, uiso in TLS.iter_itls_uiso(
                        smooth_frag.iter_all_atoms(), IT, IL, IS, IOrigin):
                    smooth_uiso[atm] = uiso
        elif ifrag == ifrag_end:
            for i in range(ifrag_end + 1, num_frags):
                smooth_frag = chain[i]
                for atm, uiso in TLS.iter_itls_uiso(
                        smooth_frag.iter_all_atoms(), IT, IL, IS, IOrigin):
                    smooth_uiso[atm] = uiso

    for atm, uiso in smooth_uiso.iteritems():
        atm.temp_factor = Constants.U2B * uiso
        atm.U = numpy.identity(3, float) * uiso
示例#12
0
def IsotropicADPDataSmoother(chain, num_smooth = 1):
    """Experimental data smoothing of temperature factors.
    """
    console.endln()
    console.stdoutln("SMOOTHING CHAIN %s ADPs" % (chain.chain_id))
    console.kvformat("SMOOTH WINDOW", 2 * num_smooth + 1)

    num_frags = len(chain)

    smooth_uiso = dict()
    ifrag_start = num_smooth
    ifrag_end = num_frags - num_smooth - 1

    for ifrag in xrange(ifrag_start, ifrag_end + 1):
        smooth_frag = chain[ifrag]
        frag1 = chain[ifrag - num_smooth]
        frag2 = chain[ifrag + num_smooth]

        IT, IL, IS, IOrigin = IsotropicFitSegmentOutlierRejection(
            chain, frag1.fragment_id, frag2.fragment_id)

        for atm, uiso in TLS.iter_itls_uiso(smooth_frag.iter_all_atoms(), 
                                            IT, IL, IS, IOrigin):
            smooth_uiso[atm] = uiso

        if ifrag == ifrag_start:
            for i in range(ifrag_start):
                smooth_frag = chain[i]
                for atm, uiso in TLS.iter_itls_uiso(smooth_frag.iter_all_atoms(),
                                                    IT, IL, IS, IOrigin):
                    smooth_uiso[atm] = uiso
        elif ifrag == ifrag_end:
            for i in range(ifrag_end + 1, num_frags):
                smooth_frag = chain[i]
                for atm, uiso in TLS.iter_itls_uiso(smooth_frag.iter_all_atoms(),
                                                    IT, IL, IS, IOrigin):
                    smooth_uiso[atm] = uiso

    for atm, uiso in smooth_uiso.iteritems():
        atm.temp_factor = Constants.U2B * uiso
        atm.U = numpy.identity(3, float) * uiso
示例#13
0
def phenix_prep(xyzin, phenix_tlsin_list, phenix_tlsout):
    """PHENIX input file. Tells 'phenix.refine' what the TLS groups are.
    """
    ## load structure
    struct = FileIO.LoadStructure(fil=xyzin)

    ## load and construct TLS groups
    tls_group_list = []
    tls_file = TLS.TLSFile()
    tls_file.set_file_format(TLS.TLSFileFormatPHENIX())
    tls_file_format = TLS.TLSFileFormatPHENIX()
    for tlsin in phenix_tlsin_list:
        tls_desc_list = tls_file_format.load(open(tlsin, "r"))
        for tls_desc in tls_desc_list:
            tls_file.tls_desc_list.append(tls_desc)
            tls_group = tls_desc.construct_tls_group_with_atoms(struct)
            tls_group.tls_desc = tls_desc
            tls_group_list.append(tls_group)

    ## now save the PHENIX file in phenix.refine format
    tls_file.save(open(phenix_tlsout, "w"))
示例#14
0
    def fit_to_chain(self, chain):
        """Re-sets all derived information in the TLSSegment.
        """
        ## cut segment from chain using segment ranges
        segments = []
        for frag_id1, frag_id2 in self.segment_ranges:
            segments.append(chain[frag_id1:frag_id2])
        self.segments = segments

        ## put all atoms in the segment into a new TLSGroup instance
        tls_group = TLS.TLSGroup()
        for segment in self.segments:
            for atm in segment.iter_all_atoms():
                if atm.include is True:
                    tls_group.append(atm)
        self.tls_group = tls_group

        if len(self.tls_group) != self.num_atoms():
            console.stderrln(
                "fit_to_chain: EEK! (%s) len(self.tls_group)=%d != self.num_atoms()=%d" % (
                self, len(self.tls_group), self.num_atoms()))
            raise SystemExit

        ## fit the TLS group parameters
        try:
            self.fit_tls_parameters(chain)
        except:
            print console.formatExceptionInfo()

        ## helpful additions
        tls_info  = self.tls_group.calc_tls_info()
        itls_info = TLS.calc_itls_center_of_reaction(
            self.tls_group.itls_T,
            self.tls_group.itls_L,
            self.tls_group.itls_S,
            self.tls_group.origin)

        self.tls_info = tls_info
        self.itls_info = itls_info

        if conf.globalconf.tls_model in ["ISOT", "NLISOT"]:
            self.tls_group.model = "ISOT"
            self.model_tls_info = itls_info
        elif conf.globalconf.tls_model in ["ANISO", "NLANISO"]:
            self.tls_group.model = "ANISO"
            self.model_tls_info = tls_info

        try:
            self.rmsd_b = tls_calcs.calc_rmsd_tls_biso(self.tls_group)
        except:
            print console.formatExceptionInfo()
示例#15
0
def ResidualInfo(chain, range, tlsdict):
    IT, IL, IS, IO = tls_calcs.isotlsdict2tensors(tlsdict)

    num_atoms = 0
    weight_sum = 0.0
    msd_sum = 0.0
    atomiter = iter_fragment_atoms(chain.iter_fragments(*range))
    for atm, uiso_tls in TLS.iter_itls_uiso(atomiter, IT, IL, IS, IO):
        num_atoms += 1
        delta = atm.temp_factor - (Constants.U2B * uiso_tls)
        msd_sum += atm.occupancy * delta**2
        weight_sum += atm.occupancy
    msd = msd_sum / weight_sum
    return msd
示例#16
0
def ResidualInfo(chain, range, tlsdict):
    IT, IL, IS, IO = tls_calcs.isotlsdict2tensors(tlsdict)

    num_atoms = 0
    weight_sum = 0.0
    msd_sum = 0.0
    atomiter = iter_fragment_atoms(chain.iter_fragments(*range))
    for atm, uiso_tls in TLS.iter_itls_uiso(atomiter, IT, IL, IS, IO):
        num_atoms += 1
        delta = atm.temp_factor - (Constants.U2B * uiso_tls)
        msd_sum += atm.occupancy * delta**2
        weight_sum += atm.occupancy
    msd = msd_sum / weight_sum
    return msd
示例#17
0
def main(tlsin, struct_in, struct_out):
    struct = FileIO.LoadStructure(file=struct_in)

    ## make the TLS groups
    fil = open(tlsin, "r")
    tls_file = TLS.TLSFile()
    tls_file.set_file_format(TLS.TLSFileFormatTLSOUT())
    tls_file.load(fil)

    tls_group_list = []
    for tls_desc in tls_file.tls_desc_list:
        tls = tls_desc.construct_tls_group_with_atoms(struct)
        tls.tls_desc = tls_desc
        tls_group_list.append(tls)
        print tls.origin

    for tls in tls_group_list:
        for atm, Utls in tls.iter_atm_Utls():
            atm.U = Utls + (Constants.B2U * atm.temp_factor *
                            numpy.identity(3, float))
            atm.temp_factor = Constants.U2B * (numpy.trace(atm.U) / 3.0)

    ## save the struct
    FileIO.SaveStructure(file=struct_out, struct=struct)
示例#18
0
def calc_residue_mean_rmsd(chain, cpartition):
    """Calculates the mean RMSD value per residue in a given chain.
    """
    num_tls = cpartition.num_tls_segments()
    num_res = chain.count_fragments()

    #struct_id = cpartition.struct_id ## TODO: Find out how to get this

    cmtx = numpy.zeros((num_tls, num_res), float)

    i_ntls = 0
    for i, tls in enumerate(cpartition.iter_tls_segments()):
        tls_group = tls.tls_group

        T = tls_group.itls_T  # float(3)
        L = tls_group.itls_L  # array(3,3)
        S = tls_group.itls_S  # array(3): S[0], S[1], S[2]
        O = tls_group.origin  # array(3)

        for j, frag in enumerate(chain):
            ## NOTE: j = res_num, frag = Res(ALA,23,A)

            ## calculate a atom-normalized rmsd deviation for each residue
            num_atoms = 0
            msd_sum = 0.0

            for atm in frag.iter_all_atoms():
                if atm.include == False:
                    continue

                num_atoms += 1

                b_iso_tls = Constants.U2B * TLS.calc_itls_uiso(
                    T, L, S, atm.position - O)
                delta = atm.temp_factor - b_iso_tls
                msd_sum += delta**2

            if num_atoms > 0:
                msd = msd_sum / num_atoms
                rmsd = math.sqrt(msd)

                ## set the cross prediction matrix
                cmtx[i, j] = rmsd

    return cmtx
示例#19
0
文件: tls_calcs.py 项目: masci/mmLib
def calc_residue_mean_rmsd(chain, cpartition):
    """Calculates the mean RMSD value per residue in a given chain.
    """
    num_tls = cpartition.num_tls_segments()
    num_res = chain.count_fragments()

    #struct_id = cpartition.struct_id ## TODO: Find out how to get this

    cmtx = numpy.zeros((num_tls, num_res), float)

    i_ntls = 0
    for i, tls in enumerate(cpartition.iter_tls_segments()):
        tls_group = tls.tls_group

        T = tls_group.itls_T # float(3)
        L = tls_group.itls_L # array(3,3)
        S = tls_group.itls_S # array(3): S[0], S[1], S[2]
        O = tls_group.origin # array(3)

        for j, frag in enumerate(chain):
            ## NOTE: j = res_num, frag = Res(ALA,23,A)

            ## calculate a atom-normalized rmsd deviation for each residue
            num_atoms = 0
            msd_sum = 0.0

            for atm in frag.iter_all_atoms():
                if atm.include == False:
                    continue

                num_atoms += 1

                b_iso_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
                delta = atm.temp_factor - b_iso_tls
                msd_sum += delta**2

            if num_atoms > 0:
                msd = msd_sum / num_atoms
                rmsd = math.sqrt(msd)

                ## set the cross prediction matrix
                cmtx[i,j] = rmsd

    return cmtx
示例#20
0
def calc_rmsd_tls_biso(tls_group):
    """Calculate the RMSD of the tls_group using the isotropic TLS model.
    """
    T = tls_group.itls_T
    L = tls_group.itls_L
    S = tls_group.itls_S
    O = tls_group.origin

    msd_sum = 0.0
    
    for atm, uiso_tls in TLS.iter_itls_uiso(iter(tls_group), T, L, S, O):
        msd_sum += (Constants.U2B*uiso_tls - atm.temp_factor)**2
        
    if len(tls_group)>0:
        msd = msd_sum / len(tls_group)
        rmsd = math.sqrt(msd)
    else:
        rmsd = 0.0

    return rmsd
示例#21
0
def IsotropicFitSegmentOutlierRejection(chain, frag_id1, frag_id2):
    segment = chain[frag_id1:frag_id2]
    atoms = list(segment.iter_all_atoms())

    orig_num_atoms = len(atoms)
    rejected = 0

    while True:
        tls_analyzer = tlsmdmodule.TLSModelAnalyzer()
        xlist = atom_selection.chain_to_xmlrpc_list(iter(atoms))
        tls_analyzer.set_xmlrpc_chain(xlist)

        tlsdict = tls_analyzer.isotropic_fit_segment(frag_id1, frag_id2)
        IT, IL, IS, IOrigin = tls_calcs.isotlsdict2tensors(tlsdict)

        num_atoms = 0
        msd_sum = 0.0
        atm_deltab = []

        for atm, uiso in TLS.iter_itls_uiso(iter(atoms), IT, IL, IS, IOrigin):
            num_atoms += 1
            deltab = atm.temp_factor - (Constants.U2B * uiso)
            msd_sum += deltab**2
            atm_deltab.append((deltab, atm))

        sigma = math.sqrt((msd_sum / num_atoms))
        sigma2 = 2.0 * sigma

        outliers = 0
        for deltab, atm in atm_deltab:
            if abs(deltab) > sigma2:
                atoms.remove(atm)
                outliers += 1

        rejected += outliers

        if outliers == 0 or (num_atoms - outliers) < 10:
            console.stdoutln("SEGMENT %s-%s %d->%d" %
                             (frag_id1, frag_id2, orig_num_atoms,
                              orig_num_atoms - rejected))
            return IT, IL, IS, IOrigin
示例#22
0
def tlsdict2tensors(tlsdict):
    """Convert the result dictionaries returned by tlsmdmodule to NumPy
    tensors.
    """
    origin = numpy.array([tlsdict["x"], tlsdict["y"], tlsdict["z"]], float)

    T = numpy.array([[tlsdict["t11"], tlsdict["t12"], tlsdict["t13"]],
                     [tlsdict["t12"], tlsdict["t22"], tlsdict["t23"]],
                     [tlsdict["t13"], tlsdict["t23"], tlsdict["t33"]]], float)

    L = numpy.array([[tlsdict["l11"], tlsdict["l12"], tlsdict["l13"]],
                     [tlsdict["l12"], tlsdict["l22"], tlsdict["l23"]],
                     [tlsdict["l13"], tlsdict["l23"], tlsdict["l33"]]], float)

    s11, s22, s33 = TLS.calc_s11_s22_s33(tlsdict["s2211"], tlsdict["s1133"])

    S = numpy.array([[s11, tlsdict["s12"], tlsdict["s13"]],
                     [tlsdict["s21"], s22, tlsdict["s23"]],
                     [tlsdict["s31"], tlsdict["s32"], s33]], float)

    return T, L, S, origin
示例#23
0
    def write_data_file(self):
        """Generate the data file and return the filename.
        """
        nrows = len(self.cpartition.chain)
        ncols = 1 + 3 * self.cpartition.num_tls_segments()
        tbl = table.StringTable(nrows, ncols, "?")

        mpred = lambda f: f.fragment_id
        frag_id_iter = itertools.imap(mpred, self.cpartition.chain.iter_fragments())
        tbl.set_column(0, 0, frag_id_iter)

        for itls, tls in enumerate(self.cpartition.iter_tls_segments()):
            tls_group = tls.tls_group
            tls_info = tls.model_tls_info
            O = tls_info["COR"]

            for frag in tls.iter_fragments():
                atm = frag.get_atom("CA")
                if atm is None:
                    continue

                i = frag.ifrag

                for n, Lx_val, Lx_vec, Lx_rho, Lx_pitch in [
                    (0, "L1_eigen_val", "L1_eigen_vec", "L1_rho", "L1_pitch"),
                    (1, "L2_eigen_val", "L2_eigen_vec", "L2_rho", "L2_pitch"),
                    (2, "L3_eigen_val", "L3_eigen_vec", "L3_rho", "L3_pitch") ]:

                    Lval   = tls_info[Lx_val]
                    Lvec   = tls_info[Lx_vec]
                    Lrho   = tls_info[Lx_rho]
                    Lpitch = tls_info[Lx_pitch]

                    if numpy.allclose(Lval, 0.0):
                        continue

                    dvec = TLS.calc_LS_displacement(O, Lval, Lvec, Lrho, Lpitch, atm.position, settings.ADP_PROB)
                    tbl[i, 1 + 3*itls + n] = AtomMath.length(dvec)

        open(self.txt_path, "w").write(str(tbl))
示例#24
0
def IsotropicFitSegmentOutlierRejection(chain, frag_id1, frag_id2):
    segment = chain[frag_id1:frag_id2]
    atoms = list(segment.iter_all_atoms())

    orig_num_atoms = len(atoms)
    rejected = 0

    while True:
        tls_analyzer = tlsmdmodule.TLSModelAnalyzer()
        xlist = atom_selection.chain_to_xmlrpc_list(iter(atoms))
        tls_analyzer.set_xmlrpc_chain(xlist)

        tlsdict = tls_analyzer.isotropic_fit_segment(frag_id1, frag_id2)
        IT, IL, IS, IOrigin = tls_calcs.isotlsdict2tensors(tlsdict)

        num_atoms = 0
        msd_sum = 0.0
        atm_deltab = []

        for atm, uiso in TLS.iter_itls_uiso(iter(atoms), IT, IL, IS, IOrigin):
            num_atoms += 1;
            deltab = atm.temp_factor - (Constants.U2B * uiso)
            msd_sum += deltab**2
            atm_deltab.append((deltab, atm))

        sigma = math.sqrt((msd_sum / num_atoms))
        sigma2 = 2.0 * sigma

        outliers = 0
        for deltab, atm in atm_deltab:
            if abs(deltab) > sigma2:
                atoms.remove(atm)
                outliers += 1

        rejected += outliers

        if outliers == 0 or (num_atoms - outliers) < 10:
            console.stdoutln("SEGMENT %s-%s %d->%d" % (
                frag_id1, frag_id2, orig_num_atoms, orig_num_atoms - rejected))
            return IT, IL, IS, IOrigin
示例#25
0
def calc_residue_mean_rmsd(chain, cpartition):
    num_tls = cpartition.num_tls_segments()
    num_res = chain.count_fragments()

    cmtx = numpy.zeros((num_tls, num_res), float)

    for i, tls in enumerate(cpartition.iter_tls_segments()):
        tls_group = tls.tls_group

        T = tls_group.itls_T
        L = tls_group.itls_L
        S = tls_group.itls_S
        O = tls_group.origin

        for j, frag in enumerate(chain):
            ## calculate a atom-normalized rmsd deviation for each residue
            num_atoms = 0
            msd_sum = 0.0

            for atm in frag.iter_all_atoms():
                if atm.include == False:
                    continue

                num_atoms += 1
                b_iso_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
                delta = atm.temp_factor - b_iso_tls
                msd_sum += delta**2

            if num_atoms > 0:
                msd = msd_sum / num_atoms
                rmsd = math.sqrt(msd)

                ## set the cross prediction matrix
                cmtx[i,j] = rmsd

    return cmtx
示例#26
0
文件: tls_calcs.py 项目: masci/mmLib
def tlsdict2tensors(tlsdict):
    """Convert the result dictionaries returned by tlsmdmodule to NumPy
    tensors.
    """
    origin = numpy.array([tlsdict["x"], tlsdict["y"], tlsdict["z"]], float)

    T = numpy.array(
        [ [tlsdict["t11"], tlsdict["t12"], tlsdict["t13"]],
          [tlsdict["t12"], tlsdict["t22"], tlsdict["t23"]],
          [tlsdict["t13"], tlsdict["t23"], tlsdict["t33"]] ], float)
    
    L = numpy.array(
        [ [tlsdict["l11"], tlsdict["l12"], tlsdict["l13"]],
          [tlsdict["l12"], tlsdict["l22"], tlsdict["l23"]],
          [tlsdict["l13"], tlsdict["l23"], tlsdict["l33"]] ], float)
    
    s11, s22, s33 = TLS.calc_s11_s22_s33(tlsdict["s2211"], tlsdict["s1133"]) 
        
    S = numpy.array(
        [ [       s11, tlsdict["s12"], tlsdict["s13"]],
          [tlsdict["s21"],        s22, tlsdict["s23"]],
          [tlsdict["s31"], tlsdict["s32"],       s33] ], float)

    return T, L, S, origin
示例#27
0
文件: gnuplots.py 项目: salotz/mmLib
    def write_data_file(self):
        nrows = len(self.cpartition.chain)
        ncols = self.cpartition.num_tls_segments() + 1
        tbl = table.StringTable(nrows, ncols, "?")

        frag_id_iter = itertools.imap(lambda frag: frag.fragment_id, self.cpartition.chain.iter_fragments())
        tbl.set_column(0, 0, frag_id_iter)

        for itls, tls in enumerate(self.cpartition.iter_tls_segments()):
            tls_group = tls.tls_group

            T = tls_group.itls_T
            L = tls_group.itls_L
            S = tls_group.itls_S
            O = tls_group.origin

            for frag in tls.iter_fragments():
                ## FIXME: This should be able to handle either one
                atm = frag.get_atom("CA")  ## for amino acids
                # atm = frag.get_atom("P") ## for nucleic acids
                if atm is None:
                    continue
                i = frag.ifrag
                b_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
                tbl[i, itls + 1] = atm.temp_factor - b_tls

        open(self.txt_path, "w").write(str(tbl))

        flatfile_write(
            "CA_TLS_Differance_Plot: data",
            "CTDP",
            "DATA",
            str(tbl),
            self.chain.chain_id,
            self.cpartition.num_tls_segments(),
        )
示例#28
0
def main(path, opt_dict):
    struct = FileIO.LoadStructure(file=path)

    tls_group_list = []

    ## make the TLS groups
    if opt_dict.has_key("-t"):

        try:
            fil = open(opt_dict["-t"], "r")
        except IOError:
            print "[ERROR]: TLSIN File not found %s" % (opt_dict["-t"])
            sys.exit(-1)

        tls_file = TLS.TLSFile()
        tls_file.set_file_format(TLS.TLSFileFormatTLSOUT())
        tls_file.load(fil)

        for tls_desc in tls_file.tls_desc_list:
            tls = tls_desc.construct_tls_group_with_atoms(struct)
            tls.tls_desc = tls_desc
            tls_group_list.append(tls)

    else:
        ## create one TLS group per chain by default
        for chain in struct.iter_chains():
            if chain.count_amino_acids() < 10:
                continue

            try:
                chain_id1 = chain.chain_id
                frag_id1 = chain[0].fragment_id
                frag_id2 = chain[-1].fragment_id
            except IndexError:
                continue

            tls_desc = TLS.TLSGroupDesc()
            tls_desc.add_range(chain_id1, frag_id1, chain_id1, frag_id2, "ALL")
            tls = tls_desc.construct_tls_group_with_atoms(struct)
            tls_group_list.append(tls)
            tls.tls_desc = tls_desc

            print "Creating TLS Group: %s" % (tls.name)

    ## fit TLS groups and write output
    tls_file = TLS.TLSFile()
    tls_file.set_file_format(TLS.TLSFileFormatTLSOUT())

    ## preform a LSQ fit if necessary
    for tls in tls_group_list:

        print "[TLS GROUP  %s]" % (tls.name)

        ## if the TLS group is null, then perform a LSQ-TLS fit
        if tls.is_null():
            print "Null Group: Running TLS-LSQ"

            if len(tls) < 20:
                print "ERROR: Not Enough Atoms in TLS Group."
                continue

            tls.origin = tls.calc_centroid()
            lsq_residual = tls.calc_TLS_least_squares_fit()
            tls.shift_COR()

        tls.tls_desc.set_tls_group(tls)
        tls_file.tls_desc_list.append(tls.tls_desc)

    if opt_dict.has_key("-o"):
        print "Saving TLSIN: %s" % (opt_dict["-o"])
        tls_file.save(open(opt_dict["-o"], "w"))

    ## write out a PDB file with 0.0 tempature factors for all
    ## atoms in TLS groups
    if opt_dict.has_key("-p"):

        for tls in tls_group_list:
            for atm, Utls in tls.iter_atm_Utls():
                if opt_dict.has_key("-s"):
                    atm.temp_factor = 0.0
                    atm.U = None
                else:
                    atm.temp_factor = Constants.U2B * numpy.trace(Utls) / 3.0
                    atm.U = Utls

        ## save the struct
        print "Saving XYZIN: %s" % (opt_dict["-p"])
        FileIO.SaveStructure(file=opt_dict["-p"], struct=struct)
示例#29
0
def main(path, opt_dict):
    struct = FileIO.LoadStructure(file = path)

    tls_group_list = []

    ## make the TLS groups
    if opt_dict.has_key("-t"):

        try:
            fil = open(opt_dict["-t"], "r")
        except IOError:
            print "ERROR: TLSIN File not found %s" % (opt_dict["-t"])
            sys.exit(-1)
        
        tls_file = TLS.TLSFile()
        tls_file.set_file_format(TLS.TLSFileFormatTLSOUT())
        tls_file.load(fil)
        
        for tls_desc in tls_file.tls_desc_list:
            #tls = tls_desc.generate_tls_group(struct) ## old def
            tls = tls_desc.construct_tls_group_with_atoms(struct)
            tls.tls_desc = tls_desc
            tls_group_list.append(tls)
            print tls.name

    else:
        tls_desc = TLS.TLSGroupDesc()
        tls_desc.add_range("A", "1", "A", "25", "ALL")
        tls_group = tls_desc.construct_tls_group_with_atoms(struct)
        tls_group_list.append(tls_group)
        tls_group.tls_desc = tls_desc

        tls_group.origin = tls_group.calc_centroid()
        tls_group.T = rt_random(T1)
        tls_group.L, tls_group.S = rt_random2(L1, S1)

        tls_desc = TLS.TLSGroupDesc()
        tls_desc.add_range("A", "26", "A", "35", "ALL")
        tls_group = tls_desc.construct_tls_group_with_atoms(struct)
        tls_group_list.append(tls_group)
        tls_group.tls_desc = tls_desc

        tls_group.origin = tls_group.calc_centroid()
        tls_group.T = rt_random(T2)
        tls_group.L, tls_group.S = rt_random2(L2, S1)
        
        tls_desc = TLS.TLSGroupDesc()
        tls_desc.add_range("A", "36", "A", "52", "ALL")
        tls_group = tls_desc.construct_tls_group_with_atoms(struct)
        tls_group_list.append(tls_group)
        tls_group.tls_desc = tls_desc

        tls_group.origin = tls_group.calc_centroid()
        tls_group.T = rt_random(T3)
        tls_group.L, tls_group.S = rt_random2(L3, S1)

    for atm in struct.iter_all_atoms():
        atm.U = None

    ## write out ideal TLS ANISOU records
    if opt_dict.has_key("-p"):
        for tls_group in tls_group_list:
            for atm, Utls in tls_group.iter_atm_Utls():
                atm.temp_factor = Constants.U2B * (numpy.trace(Utls) / 3.0)
                atm.U = Utls
                
        ## save the struct
        FileIO.SaveStructure(file = opt_dict["-p"], struct = struct)
示例#30
0
def refmac5_prep(xyzin, tlsin_list, xyzout, tlsout):
    """Use TLS model + Uiso for each atom.  Output xyzout with the
    residual Uiso only.
    """
    ## load structure
    struct = FileIO.LoadStructure(fil = xyzin)

    ## load and construct TLS groups
    tls_group_list = []
    tls_file = TLS.TLSFile()
    tls_file.set_file_format(TLS.TLSFileFormatTLSOUT())
    tls_file_format = TLS.TLSFileFormatTLSOUT()
    for tlsin in tlsin_list:
        tls_desc_list = tls_file_format.load(open(tlsin, "r"))
        for tls_desc in tls_desc_list:
            tls_file.tls_desc_list.append(tls_desc)
            tls_group = tls_desc.construct_tls_group_with_atoms(struct)
            tls_group.tls_desc = tls_desc
            tls_group_list.append(tls_group)

    ## set the extra Uiso for each atom
    for tls_group in tls_group_list:

        ## minimal/maximal amount of Uiso which has to be added
        ## to the group's atoms to to make Uiso == Uiso_tls
        min_Uiso = 0.0
        max_Uiso = 0.0

        for atm, Utls in tls_group.iter_atm_Utls():
            tls_tf = numpy.trace(Utls) / 3.0
            ref_tf = numpy.trace(atm.get_U()) / 3.0
                
            if ref_tf > tls_tf:
                max_Uiso = max(ref_tf - tls_tf, max_Uiso)
            else:
                min_Uiso = max(tls_tf - ref_tf, min_Uiso)

        ## reduce the TLS group T tensor by min_Uiso so that
        ## a PDB file can be written out where all atoms
        ## Uiso == Uiso_tls

        ## we must rotate the T tensor to its primary axes before
        ## subtracting min_Uiso magnitude from it
        (T_eval, TR) = numpy.linalg.eig(tls_group.T)
        T = numpy.dot(TR, numpy.dot(tls_group.T, numpy.transpose(TR)))

        assert numpy.allclose(T[0,1], 0.0)
        assert numpy.allclose(T[0,2], 0.0)
        assert numpy.allclose(T[1,2], 0.0)

        T[0,0] = T[0,0] - min_Uiso
        T[1,1] = T[1,1] - min_Uiso
        T[2,2] = T[2,2] - min_Uiso

        ## now take some of the smallest principal component of T and
        ## move it into the individual atomic temperature factors
        min_T    = min(T[0,0], min(T[1,1], T[2,2]))
        sub_T    = min_T * 0.50
        add_Uiso = min_T - sub_T
        
        T[0,0] = T[0,0] - sub_T
        T[1,1] = T[1,1] - sub_T
        T[2,2] = T[2,2] - sub_T
        
        ## rotate T back to original orientation
        tls_group.T = numpy.dot(
            numpy.transpose(TR),
            numpy.dot(T, TR))

        ## reset the TLS tensor values in the TLSDesc object so they can be saved
        tls_group.tls_desc.set_tls_group(tls_group)
        
        ## set atm.temp_factor
        for atm, Utls in tls_group.iter_atm_Utls():
            tls_tf = numpy.trace(Utls) / 3.0
            ref_tf = numpy.trace(atm.get_U()) / 3.0

            if ref_tf > tls_tf:
                atm.temp_factor = ((add_Uiso) + ref_tf - tls_tf)*Constants.U2B
                atm.U = None
            else:
                atm.temp_factor = (add_Uiso) * Constants.U2B
                atm.U = None

    FileIO.SaveStructure(fil = xyzout, struct = struct)
    tls_file.save(open(tlsout, "w"))
示例#31
0
    def make_script(self):
        tls = self.tls

        ## generate data and png paths
        basename  = "%s_CHAIN%s_TLS%s_BoBc" % (
            self.chain.struct.structure_id,
            self.chain.chain_id,
            tls.filename_label())

        self.set_basename(basename)

        ## write out the data file
        tls_group = tls.tls_group

        T = tls_group.itls_T
        L = tls_group.itls_L
        S = tls_group.itls_S
        O = tls_group.origin

        ## create a histogram of (Uiso - Utls_iso)
        bdiff_min = 0.0
        bdiff_max = 0.0

        for atm in tls_group:
            b_iso_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
            bdiff = atm.temp_factor - b_iso_tls

            bdiff_min = min(bdiff_min, bdiff)
            bdiff_max = max(bdiff_max, bdiff)

        ## compute the bin width and range to bin over
        brange    = (bdiff_max - bdiff_min) + 2.0
        num_bins  = int(brange)
        bin_width = brange / float(num_bins)
        bins      = [0 for n in xrange(num_bins)]

        ## name the bins with their mean value
        bin_names = []
        for n in xrange(num_bins):
            bin_mean = bdiff_min + (float(n) * bin_width) + (bin_width / 2.0)
            bin_names.append(bin_mean)

        ## count the bins
        for atm in tls_group:
            b_iso_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
            bdiff = atm.temp_factor - b_iso_tls
            bin = int((bdiff - bdiff_min)/ bin_width)
            bins[bin] += 1

        ## write out the gnuplot input file
        fil = open(self.txt_path, "w")
        fil.write("## Histogram of atoms in the TLS group binned by\n")
        fil.write("## the difference of their isotropic temperature factors\n")
        fil.write("## from the isotropic values predicted from the TLS model.\n")
        fil.write("##\n")
        fil.write("## Structure ----------------: %s\n" % (self.chain.struct.structure_id))
        fil.write("## Chain --------------------: %s\n" % (self.chain.chain_id))
        fil.write("## TLS Group Residue Range --: %s\n" % (tls.display_label()))

        for i in xrange(len(bins)):
            fil.write("%f %d\n" % (bin_names[i], bins[i]))

        fil.close()

        ## modify script template
        script = _UISO_VS_UTLSISO_HISTOGRAM_TEMPLATE
        script = script.replace("<txtfile>", self.txt_path)

        title = "Histogram of Observed B_{iso} - B_{tls} for TLS Group %s" % (tls.display_label())
        script = script.replace("<title>", title)
        script = script.replace("<rgb>", tls.color.rgbs)

        return script
示例#32
0
        print_TLSGroup(tls)

    else:
        tls_file = TLS.TLSFile()

        ## get TLS groups from REMARK statments in PDB file
        if tls_out_path == None:
            tls_file.set_file_format(TLS.TLSFileFormatPDB())
            try:
                tls_file.load(open(pdb_path, "r"), pdb_path)
            except IOError, e:
                print "[Error] %s: %s" % (str(e), pdb_path)

        ## or get TLS groups from REFMAC TLSOUT file
        else:
            tls_file.set_file_format(TLS.TLSFileFormatTLSOUT())
            try:
                tls_file.load(open(tls_out_path, "r"), tls_out_path)
            except IOError, e:
                print "[Error] %s: %s" % (str(e), tls_out_path)

        ## print the TLS groups
        tls_group_list = tls_file.construct_tls_groups_with_atoms(struct)

        for tls_group in tls_group_list:
            print_TLSGroup(tls_group)
            print


if __name__ == "__main__":
示例#33
0
    def raster3d_render_tls_graph_path(self, chain, cpartition):
        """Render TLS visualizations using Raster3D.
        """
        basename = "%s_CHAIN%s_NTLS%d" % (self.struct_id, chain.chain_id,
                                          cpartition.num_tls_segments())
        png_path = "%s.png" % (basename)
        console.stdoutln("Raster3D: rendering %s..." % (basename))

        struct_id = self.struct_id
        driver = R3DDriver.Raster3DDriver()

        ## XXX: Size hack: some structures have too many chains,
        ## or are just too large
        show_chain = {}
        for chx in self.struct.iter_chains():
            if chx.chain_id == chain.chain_id:
                show_chain[chx.chain_id] = True
                continue

            if chx.count_amino_acids() >= 100:
                show_chain[chx.chain_id] = False
                continue

            show_chain[chx.chain_id] = True
        ## end size hack

        ## got target chain?
        if self.tlsmd_analysis.target_chain != None:
            for atm in self.tlsmd_analysis.target_chain.iter_all_atoms():
                atm.orig_position = atm.position
                atm.position = chain.target_chain_sresult.transform(
                    atm.position)

        viewer = Viewer.GLViewer()
        gl_struct = viewer.glv_add_struct(self.struct)

        ## orient the structure with the super-spiffy orientation algorithm
        ## which hilights the chain we are examining
        ori = calc_orientation(self.struct, chain)
        viewer.glo_update_properties(R=ori["R"],
                                     cor=ori["centroid"],
                                     zoom=ori["hzoom"],
                                     near=ori["near"],
                                     far=ori["far"],
                                     width=ori["pwidth"],
                                     height=ori["pheight"],
                                     bg_color="White")

        ## turn off axes and unit cell visualization
        gl_struct.glo_update_properties_path("gl_axes/visible", False)
        gl_struct.glo_update_properties_path("gl_unit_cell/visible", False)

        ## setup base structural visualization
        for gl_chain in gl_struct.glo_iter_children():
            if not isinstance(gl_chain, Viewer.GLChain):
                continue

            ## chain is hidden
            if show_chain.get(gl_chain.chain.chain_id, False) == False:
                gl_chain.properties.update(visible=False)
                continue

            if gl_chain.chain.chain_id == chain.chain_id:

                if gl_chain.chain.has_amino_acids():
                    gl_chain.properties.update(lines=False,
                                               trace=True,
                                               trace_radius=0.25,
                                               trace_color="0.80,0.80,0.80")
                elif gl_chain.chain.has_nucleic_acids():
                    gl_chain.properties.update(lines=False,
                                               ball_stick=True,
                                               ball_stick_radius=0.25,
                                               color="0.80,0.80,0.80")
            else:
                if gl_chain.chain.has_amino_acids():
                    gl_chain.properties.update(lines=False,
                                               trace=True,
                                               trace_radius=0.25,
                                               trace_color="0.80,0.80,0.80")
                elif gl_chain.chain.has_nucleic_acids():
                    gl_chain.properties.update(hetatm_visible=True,
                                               trace=True,
                                               trace_radius=0.35,
                                               trace_color="0.80,0.80,0.80",
                                               ball_stick=True,
                                               ball_stick_radius=0.25,
                                               color="0.60,0.60,0.70")
                else:
                    gl_chain.properties.update(visible=True,
                                               ball_stick=True,
                                               ball_stick_radius=0.25,
                                               cpk=False)

        ## add the TLS group visualizations
        has_amino_acids = cpartition.chain.has_amino_acids()
        has_nucleic_acids = cpartition.chain.has_nucleic_acids()

        for tls in cpartition.iter_tls_segments():
            if tls.method != "TLS":
                continue

            if self.tlsmd_analysis.target_chain is not None:
                if tls.rmsd_pre_alignment <= 0.8:
                    continue
                if (tls.rmsd_pre_alignment - tls.sresult.rmsd) < 0.5:
                    continue

            tls_name = "TLS_%s" % (tls.filename_label())
            gl_tls_group = TLS.GLTLSGroup(oatm_visible=False,
                                          side_chain_visible=False,
                                          hetatm_visible=True,
                                          adp_prob=settings.ADP_PROB,
                                          L_axis_scale=2.0,
                                          L_axis_radius=0.20,
                                          both_phases=True,
                                          tls_group=tls.tls_group,
                                          tls_info=tls.model_tls_info,
                                          tls_name=tls_name,
                                          tls_color=tls.color.name)

            gl_struct.glo_add_child(gl_tls_group)

            if tls.superposition_vscrew != None:
                gl_tls_group.properties.update(
                    COR_vector=tls.superposition_vscrew)

            ## set width of trace according to the group's translationral tensor trace
            mtls_info = tls.model_tls_info
            tiso = (mtls_info["Tr1_eigen_val"] + mtls_info["Tr2_eigen_val"] +
                    mtls_info["Tr3_eigen_val"]) / 3.0

            ## too big usually for good visualization -- cheat and scale it down
            radius = 0.30

            if has_amino_acids:
                gl_tls_group.gl_atom_list.properties.update(
                    trace_radius=radius)

            elif has_nucleic_acids:
                gl_tls_group.gl_atom_list.properties.update(
                    oatm_visible=True,
                    side_chain_visible=True,
                    trace=True,
                    trace_radius=0.25,
                    ball_stick=True,
                    ball_stick_radius=radius)

            gl_tls_group.glo_update_properties(time=0.25)

        ## got target chain?
        if self.tlsmd_analysis.target_chain is not None:
            gl_chain = Viewer.GLChain(chain=self.tlsmd_analysis.target_chain)
            gl_chain.properties.update(oatm_visible=False,
                                       side_chain_visible=False,
                                       hetatm_visible=True,
                                       lines=False,
                                       ball_stick=False,
                                       trace=True,
                                       trace_radius=0.25,
                                       trace_color="0.40,0.40,0.40")
            gl_struct.glo_add_child(gl_chain)

        driver.glr_set_render_png_path(png_path)
        viewer.glv_render_one(driver)

        ## got target chain?
        if self.tlsmd_analysis.target_chain != None:
            for atm in self.tlsmd_analysis.target_chain.iter_all_atoms():
                atm.position = atm.orig_position
                del atm.orig_position

        return "", png_path
示例#34
0
文件: gnuplots.py 项目: salotz/mmLib
    def make_script(self):
        console.debug_stdoutln(">gnuplots.py->UIso_vs_UtlsIso_Histogram()")
        tls = self.tls

        ## generate data and png paths
        basename = "%s_CHAIN%s_TLS%s_BoBc" % (self.chain.struct.structure_id, self.chain.chain_id, tls.filename_label())

        self.set_basename(basename)

        ## write out the data file
        tls_group = tls.tls_group

        T = tls_group.itls_T
        L = tls_group.itls_L
        S = tls_group.itls_S
        O = tls_group.origin

        ## create a histogram of (Uiso - Utls_iso)
        bdiff_min = 0.0
        bdiff_max = 0.0

        for atm in tls_group:
            b_iso_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
            bdiff = atm.temp_factor - b_iso_tls

            bdiff_min = min(bdiff_min, bdiff)
            bdiff_max = max(bdiff_max, bdiff)

        ## compute the bin width and range to bin over
        brange = (bdiff_max - bdiff_min) + 2.0
        num_bins = int(brange)
        bin_width = brange / float(num_bins)
        bins = [0 for n in xrange(num_bins)]

        ## name the bins with their mean value
        bin_names = []
        for n in xrange(num_bins):
            bin_mean = bdiff_min + (float(n) * bin_width) + (bin_width / 2.0)
            bin_names.append(bin_mean)

        ## count the bins
        for atm in tls_group:
            b_iso_tls = Constants.U2B * TLS.calc_itls_uiso(T, L, S, atm.position - O)
            bdiff = atm.temp_factor - b_iso_tls
            bin = int((bdiff - bdiff_min) / bin_width)
            bins[bin] += 1

        ## write out the gnuplot input file
        fil = open(self.txt_path, "w")
        fil.write("## Histogram of atoms in the TLS group binned by\n")
        fil.write("## the difference of their isotropic temperature factors\n")
        fil.write("## from the isotropic values predicted from the TLS model.\n")
        fil.write("##\n")
        fil.write("## Structure ----------------: %s\n" % (self.chain.struct.structure_id))
        fil.write("## Chain --------------------: %s\n" % (self.chain.chain_id))
        fil.write("## TLS Group Residue Range --: %s\n" % (tls.display_label()))

        job_dir = os.path.join(conf.TLSMD_WORK_DIR, conf.globalconf.job_id, "ANALYSIS")
        if os.path.basename(os.getcwd()) != "ANALYSIS":
            flatfile = open("../%s.dat" % conf.globalconf.job_id, "a+")
        else:
            flatfile = open("%s.dat" % conf.globalconf.job_id, "a+")
        flatfile.write("\nCCCC UIso_vs_UtlsIso_Histogram\n")
        flatfile.write("%s %s,%s.0 <DATA>\n" % ("UVUH", self.chain.chain_id, self.cpartition.num_tls_segments()))

        for i in xrange(len(bins)):
            fil.write("%f %d\n" % (bin_names[i], bins[i]))
            flatfile.write("%f %d\n" % (bin_names[i], bins[i]))

        flatfile.write("%s %s,%s.0 </DATA>\n" % ("UVUH", self.chain.chain_id, self.cpartition.num_tls_segments()))
        flatfile.close()

        fil.close()

        ## modify script template
        script = _UISO_VS_UTLSISO_HISTOGRAM_TEMPLATE
        script = script.replace("<txtfile>", self.txt_path)

        title = "Histogram of Observed B_{iso} - B_{tls} for TLS Group %s" % (tls.display_label())
        script = script.replace("<title>", title)
        script = script.replace("<rgb>", tls.color.rgbs)

        flat_script = script.replace("\n", ";")
        flatfile_write(
            "UIso_vs_UtlsIso_Histogram: script",
            "UVUH",
            "SCRIPT",
            flat_script,
            self.chain.chain_id,
            self.cpartition.num_tls_segments(),
        )

        return script