Ejemplo n.º 1
0
    def merge_region(self):
        """Merges the optimized residues with the memorized ones."""
        residues = [r for r in self.model]
        if self.model_passive:
            # apply old residue numbers
            print '\nRestoring original numeration in the optimized region.'
            for num, resi in zip(self.model_resnumbers, residues):
                #print resi, num
                #self.model.renumber_residue(resi.identifier, num)
                resi.change_number(num)
            self.model = ModernaStructure('residues',residues)
            # do the superposition
            print '\nSuperimposing the optimized part onto the rest of the model.'
            all_atoms = self.model.get_all_atoms()
            sup = ModernaSuperimposer(moved_atoms = all_atoms)
            sup.get_atoms([self.stem5, self.stem3], BACKBONE_ATOMS, 'fixed')
            resi5, resi3 = self.model[self.residues[0]], self.model[self.residues[1]]
            sup.get_atoms([resi5, resi3], BACKBONE_ATOMS, 'moved')
            sup.superimpose()

            # merge residues
            print '\nMerging the optimized part with the rest of the model.'
            resi = [r for r in self.model]
            for r in self.model_passive:
                if r.identifier not in self.residues:
                    resi.append(r)
            self.model = RnaModel(None, None, self.options.chain_name, 'residues', resi)
Ejemplo n.º 2
0
def create_model(template=None, alignment=None, model_chain_name=None):
    """*create_model(template=None, alignment=None, model_chain_name=None)*
  
Creates a RNA structure model.
Produces a RnaModel object that can be saved
in a variable (see example).

If no arguments are given, an empty RNAModel is created.
If both a Template and an Alignment are given as arguments,
the complete model is built automatically.
The chain id that the model should have can be specified optionally.

:Arguments:
    * Template object (optional)
    * Alignment object (optional)
    * chain id of the model to be built
    """
    if template: template = validate_template(template)
    if alignment: alignment = validate_alignment(alignment)
    
    model = RnaModel(template=template, alignment=alignment, model_chain_name=model_chain_name, data_type=None, data=None)
    if template and alignment:
        if not match_template_with_alignment(template,alignment):
            raise ModernaError("""Template and alignment sequences do not match!
The model cannot be built automatically.
Template : %s
Alignment: %s
"""%(template.get_sequence(),alignment.template_seq))
        model.create_model()
        match_alignment_with_model(alignment,model)
    return model
Ejemplo n.º 3
0
 def setUp(self):
     """
     fragment attached at 5' end of model.
     """
     self.m = RnaModel(data_type='file',data=MINI_TEMPLATE, seq=Sequence("GCGGAUUUALCUCAG"))
     self.s1 = ModernaStructure('file', SMALL_FRAGMENT, seq=Sequence("GCGG"))
     self.s2 = ModernaStructure('file',SMALL_FRAGMENT, seq=Sequence("GCGG"))
Ejemplo n.º 4
0
 def test_insert_all_fragments_retain_template(self):
     """The template sequence should not change."""
     m2 = RnaModel(template=self.t,
                   alignment=self.a,
                   model_chain_name='A',
                   data_type='file',
                   data=MINI_TEMPLATE)
     m2.insert_all_fragments()
     self.assertEqual(self.t.get_sequence(), self.seq_before)
Ejemplo n.º 5
0
    def test_5p_extension(self):
        a = read_alignment("""> target
AAAAAAAAAAGCGGAUUUALCUCAG
> template
----------GCGGAUUUALCUCAG
        """)
        m = RnaModel(None, a, data_type='file', data=MINI_TEMPLATE)
        m.add_missing_5p()
        self.assertEqual(m.get_sequence(), a.target_seq)
Ejemplo n.º 6
0
    def test_model_with_5p3p_ends(self):
        a = read_alignment('''> target
CAUGCGGAYYYALCUCAGGUA
> mini_template
---GCGGAUUUALCUCAG---
''')
        m = RnaModel(self.t, a)
        m.create_model()
        self.assertEqual(m.get_sequence(), Sequence('CAUGCGGAYYYALCUCAGGUA'))
Ejemplo n.º 7
0
 def setUp(self):
     self.m = RnaModel(data_type='file',
                       data=MINI_TEMPLATE,
                       seq=Sequence("GCGGAUUUALCUCAG"))
     self.s1 = ModernaStructure('file',
                                SMALL_FRAGMENT,
                                seq=Sequence("GCGG"))
     self.s2 = ModernaStructure('file',
                                SMALL_FRAGMENT,
                                seq=Sequence("GCGG"))
Ejemplo n.º 8
0
    def test_model_with_hydro_template(self):
        """If the template contains hydrogens, modifications should be added."""
        t = Template(RNA_HYDRO, 'file', 'B')
        a = read_alignment("""> 3tra_A.pdb Z73314.1/2358-2429
UPA
> 1qru_B.pdb X55374.1/1-72
CAA
""")
        m = RnaModel(t, a)
        m.create_model()
        self.assertEqual(m.get_sequence(), Sequence('UPA'))
Ejemplo n.º 9
0
    def test_model_with_alignment_adjustment(self):
        """Introduces small corrections on alignment."""
        a = read_alignment("""> target
ACUGUGAYUA[UACCU#P-G
> template with small errors.
GCG7A----U.UAGCUCA_G
        """)
        t = Template(MINI_TEMPLATE, 'file')
        match_template_with_alignment(t, a)
        m = RnaModel(t, a)
        m.create_model()
        self.assertEqual(m.get_sequence(), Sequence("ACUGUGAYUA[UACCU#PG"))
Ejemplo n.º 10
0
    def test_number_gap(self):
        """Builds model with numbering gap in the template."""
        a = read_alignment("""> target
CCGACCUUCGGCCACCUGACAGUCCUGUGCGGGAAACCGCACAGGACUGUCAACCAGGUAAUAUAACCACCGGGAAACGGUGGUUAUAUUACCUGGUACGCCUUGACGUGGGGGAAACCCCACGUCAAGGCGUGGUGGCCGAAGGUCGG
> template
CCGACCUUCGGCCACCUGACAGUCCUGUGCGG----CCGCACAGGACUGUCAACCAGGUAAUAUAACCACCGG----CGGUGGUUAUAUUACCUGGUACGCCUUGACGUGGGG----CCCCACGUCAAGGCGUGGUGGCCGAAGGUCGG
""")
        t = Template(JMB_TEMPLATE, 'file')
        clean_structure(t)
        m = RnaModel(t, a)
        m.create_model()
        self.assertEqual(m.get_sequence().seq_without_breaks, a.target_seq)
Ejemplo n.º 11
0
 def test_fill_doublegap(self):
     """Should insert fragments into correct sites."""
     # prepare model
     t = Template(DOUBLEGAP, 'file', 'A')
     m = RnaModel()
     for r in t:
         m.copy_residue(r)
     # insert first fragment
     struc = ModernaStructure('file', FRAGMENT1)
     f1 = ModernaFragment53(struc, anchor5=m['20'], anchor3=m['24'], \
         new_sequence=Sequence('AUA'), keep=keep_first_last)
     m.insert_fragment(f1)
     resids = [r.identifier for r in m]
     expected_resids1 = [
         '18', '19', '20', '21', '21A', '23', '24', '27', '28', '29', '30',
         '31', '32', '33', '34', '35'
     ]
     self.assertEqual(resids, expected_resids1)
     # insert second fragment
     struc = ModernaStructure('file', FRAGMENT2)
     f2 = ModernaFragment53(struc, anchor5=m['23'], anchor3=m['28'], \
         new_sequence=Sequence('AUUA'), keep=keep_first_last)
     m.insert_fragment(f2)
     resids = [r.identifier for r in m]
     expected_resids2 = [
         '18', '19', '20', '21', '21A', '23', '24', '24A', '24B', '27',
         '28', '29', '30', '31', '32', '33', '34', '35'
     ]
     self.assertEqual(resids, expected_resids2)
Ejemplo n.º 12
0
def load_model(data, chain_name='A',data_type='file',template=None,alignment=None):
    """*load_model(file_path, chain_name='A', data_type='file', template=None, alignment=None)*
    
Loads a structure model that has been built previously,
or any PDB struture that is then to be modified.
Produces a RnaModel object that can be saved in a variable.
Each model in ModeRNA contains only one chain.
Multi-chain structures can be modeled by using more than one
Template/Alignment/RNAModel at a time.

By default, RNAModels are created by reading files.
They can also be created from BioPython PDB objects
(precisely Bio.PDB.Structure.Structure and Bio.PDB.Chain.Chain objects)

:Arguments:
    * path+filename of a PDB structure file; or a Structure or Chain object from BioPython.
    * chain id (by default 'A')
    * data type ('file' by default; if set to 'structure' or 'chain', Bio.PDB objects are read)
    * Template object to be used for this model (optional)
    * Alignment object to be used for this model (optional)
    """
    if data_type == 'file': data = validate_filename(data)
    elif data_type == 'residues': data = validate_resi_list(data)
    if template: template = validate_template(template)
    if alignment: alignment = validate_alignment(alignment)
    return RnaModel(template=template, alignment=alignment, model_chain_name=chain_name, data_type=data_type, data=data)
Ejemplo n.º 13
0
    def test_doublegap_model(self):
        """Should create a model filling two gaps"""
        a = read_alignment('''> target
GGGAUAGUUCCAGABU#A
> template
GGGA-AG--CCAGABU#A
''')
        t = Template(DOUBLEGAP, 'file', 'A')
        m = RnaModel(t, a)
        m.apply_alignment()
        m.insert_all_fragments()
        m.fix_backbone()
        self.assertEqual(m.get_sequence(), Sequence('GGGAUAGUUCCAGABU#A'))
Ejemplo n.º 14
0
 def setUp(self):
     self.s = ModernaStructure('file', MINI_TEMPLATE)
     self.t = Template(MINI_TEMPLATE, 'file')
     self.m = RnaModel(None, None, 'A', 'file', MINI_TEMPLATE)
     self.f = ModernaFragment53(self.s,
                                anchor5=self.m['1'],
                                anchor3=self.m['14'])
     self.struc = PDBParser().get_structure('test_struc', MINI_TEMPLATE)
Ejemplo n.º 15
0
 def extract_region(self):
     self.model.renumber_chain()
     """Cuts out the residues for optimization and keeps the rest in memory."""
     if self.residues:
         print '\nExtracting the region to be optimized (%s-%s) from the model.'%(self.residues[0], self.residues[1])
         print '\t.. total residues in model                    : %4i'%len(self.model)
         self.model_passive = self.model.find_residues_not_in_range(self.residues[0], self.residues[1])
         print '\t.. residues not participating in optimization : %4i (+2 for superposition afterwards)'%(len(self.model_passive)-2)
         print '\t   '+','.join([r.identifier for r in self.model_passive])
         self.model = RnaModel(None, None, self.options.chain_name, 'residues', self.model[self.residues[0]:self.residues[1]])
         # memorize residue numbers because MMTK screws them
         self.model_resnumbers = [r.identifier for r in self.model]
         print '\t.. residues participating in optimization     : %4i'%len(self.model)
         print '\t   '+','.join([r.identifier for r in self.model])
         # keeps duplicate versions of the residues indicated by self.residues,
         # so they can be superimposed later
         self.stem5,  self.stem3 = self.model[self.residues[0]], self.model[self.residues[1]]
     else:
         self.struc_to_optimize = self.model
Ejemplo n.º 16
0
 def test_gaps_in_target(self):
     """Moderna should model gaps in the target, too."""
     a = read_alignment(ALIGN_TARGET_GAP)
     m = RnaModel(self.t, a)
     m.apply_alignment()
     m.insert_all_fragments()
     self.assertEqual(
         m.get_sequence().seq_with_modifications.replace('_', ''),
         '..CUGACCU#P')
Ejemplo n.º 17
0
class ModernaFragment5Tests(TestCase):
    """fragment attached at 3' end of model"""
    def setUp(self):
        self.m = RnaModel(data_type='file',
                          data=MINI_TEMPLATE,
                          seq=Sequence("GCGGAUUUALCUCAG"))
        self.s1 = ModernaStructure('file',
                                   SMALL_FRAGMENT,
                                   seq=Sequence("GCGG"))
        self.s2 = ModernaStructure('file',
                                   SMALL_FRAGMENT,
                                   seq=Sequence("GCGG"))

    def test_attributes(self):
        five = ModernaFragment5(self.s1, anchor5=self.m['15'])
        self.assertEqual(len(five.anchor_residues), 1)
        self.assertEqual(len(five.nonanchor_residues), 3)
        self.assertTrue(str(five))

    def test_add_on_3_end(self):
        """Model sequence should change accordingly."""
        five = ModernaFragment5(self.s1, anchor5=self.m['15'])
        self.m.insert_fragment(five)
        self.assertEqual(self.m.get_sequence(), Sequence("GCGGAUUUALCUCAGCGG"))
        self.assertTrue(five.rmsd <= 1.00)

    def test_add_on_3_end_replace(self):
        """Model sequence should change accordingly."""
        five_overwrite = ModernaFragment5(self.s2, anchor5=self.m['9'])
        self.m.insert_fragment(five_overwrite)
        self.assertEqual(self.m.get_sequence(), Sequence("GCGGAUUUACGG"))
        self.assertTrue(five_overwrite.rmsd <= 1.00, 0)
Ejemplo n.º 18
0
class ModernaFragment3Tests(TestCase):
    def setUp(self):
        """
        fragment attached at 5' end of model.
        """
        self.m = RnaModel(data_type='file',
                          data=MINI_TEMPLATE,
                          seq=Sequence("GCGGAUUUALCUCAG"))
        self.s1 = ModernaStructure('file',
                                   SMALL_FRAGMENT,
                                   seq=Sequence("GCGG"))
        self.s2 = ModernaStructure('file',
                                   SMALL_FRAGMENT,
                                   seq=Sequence("GCGG"))

    def test_attributes(self):
        """Attributes of fragment are accessible."""
        three = ModernaFragment3(self.s1, anchor3=self.m['1'])
        self.assertEqual(len(three.anchor_residues), 1)
        self.assertEqual(len(three.nonanchor_residues), 3)
        self.assertTrue(str(three))

    def test_add_on_5_end(self):
        """Model sequence should change accordingly."""
        three = ModernaFragment3(self.s1, anchor3=self.m['1'])
        self.m.insert_fragment(three)
        self.assertEqual(self.m.get_sequence(), Sequence("GCGGCGGAUUUALCUCAG"))
        self.assertTrue(three.rmsd <= 1.00)

    def test_add_on_5_end_exact(self):
        """Model sequence should change accordingly."""
        # exactly fitting example replacing original residues.
        three_overwrite = ModernaFragment3(self.s2, anchor3=self.m['6'])
        self.m.insert_fragment(three_overwrite)
        self.assertEqual(self.m.get_sequence(), Sequence("GCGUUUALCUCAG"))
        self.assertTrue(three_overwrite.rmsd <= 1.00)

    def test_add_discontinuous(self):
        """Tries to add a helix to an end."""
        helix = ModernaStructure('file', 'test_data/rna_structures/helix.pdb')
        helix_frag = ModernaFragment3(helix, anchor3=self.m['1'], strict=False)
        self.m.insert_fragment(helix_frag)
        self.assertEqual(self.m.get_sequence(),
                         Sequence('CCGACCUUCGGCC_GGUGGCCGAAGGGCGGAUUUALCUCAG'))
Ejemplo n.º 19
0
 def test_create_model_with_gaps(self):
     """Should create the model automatically."""
     a = read_alignment(ALIGN_1B23_1QF6)
     t = Template(RNA_1B23, 'file', 'R')
     m = RnaModel(t, a)
     m.apply_alignment()
     m.insert_all_fragments()
     self.assertEqual(
         m.get_sequence().seq_with_modifications.replace('_', ''),
         'GCCGAUAUAGCUCAGDDGGDAGAGCAGCGCAUUCGUEAUGCGAAG7UCGUAGGTPCGACUCCUAUUAUCGGCACCA'
     )
Ejemplo n.º 20
0
 def test_eliminate_middle(self):
     """Builds a fragment to shorten the connection between two anchor pairs"""
     helix = ModernaStructure('file', HELIX, 'A')
     helix = RnaModel(data_type='residues',
                      data=helix['1':'10'] + helix['71':'80'])
     frag = ModernaFragment2D(self.motif, \
                     anchor5=helix['2'], anchor3=helix['79'], \
                     anchor5_upper=helix['8'], anchor3_upper=helix['73'], \
                     frag5_upper=self.motif['196'], frag3_upper=self.motif['217'], \
                     new_sequence=Sequence('C'), \
                     model=helix)
     finsert = FragmentInserter()
     finsert.prepare_fragment(frag, helix)
     frag.fix_backbone()
     self.assertEqual(frag.struc.get_sequence(), Sequence('AAAA_UUUCU'))
class FragmentInserterTests(TestCase):
    """
    Tests for the FragmentInserter class
    """
    def setUp(self):
        self.m = RnaModel(data_type='file',data=MINI_TEMPLATE, seq=Sequence("GCGGAUUUALCUCAG"))
        self.s1 = ModernaStructure('file', SMALL_FRAGMENT, seq=Sequence("GCGG"))
        #self.s2 = ModernaStructure('file',SMALL_FRAGMENT, seq=Sequence("GCGG"))
        #self.s3 = ModernaStructure('file', MINI_TEMPLATE, seq=Sequence("GCGGAUUUALCUCAG"))

    def test_insert(self):
        """Inserts fragment into a model"""
        f1 = ModernaFragment53(self.s1, anchor5=self.m['10'],anchor3=self.m['13'])
        finsert = FragmentInserter()
        finsert.insert_fragment(f1, self.m)
        self.assertEqual(self.m.get_sequence(),Sequence("GCGGAUUUALCGCAG"))
Ejemplo n.º 22
0
    def test_long_5p_extension(self):
        a = read_alignment("""> target
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGCGGAUUUALCUCAG
> template
----------------------------------------GCGGAUUUALCUCAG
        """)
        # first number == 1 should not work
        m = RnaModel(None, a, data_type='file', data=MINI_TEMPLATE)
        self.assertRaises(RenumeratorError, m.add_missing_5p)
        # first number == 100 should work
        m = RnaModel(None, a, data_type='file', data=MINI_TEMPLATE)
        renumber_chain(m, 100)
        m.add_missing_5p()
        self.assertEqual(m.get_sequence(), a.target_seq)
Ejemplo n.º 23
0
    def test_oppositegap_model(self):
        """Should create a model with close gaps in the other respective sequence"""
        a = read_alignment('''> target
GGGAGAGCRUUAG-BU#A
> template
GGGAGAGCR--AGABU#A
''')
        t = Template(OPPOSITEGAP, 'file', 'A')
        m = RnaModel(t, a)
        m.apply_alignment()
        m.insert_all_fragments()
        self.assertEqual(
            m.get_sequence().seq_with_modifications.replace('_', ''),
            'GGGAGAGCRUUAGBU#A')
Ejemplo n.º 24
0
 def test_insert_eliminate(self):
     """Inserts a 2D fragment into a model."""
     helix = load_model(HELIX, 'A')
     helix = RnaModel(None, None, 'A', 'residues',
                      helix['1':'8'] + helix['73':'80'])
     mf = ModernaFragment2D(self.motif, \
                     anchor5=helix['7'], anchor3=helix['74'], \
                     anchor5_upper=helix['8'], anchor3_upper=helix['73'], \
                     frag5_upper=self.motif['196'], frag3_upper=self.motif['217'], \
                     new_sequence=Sequence('C'), \
                     model=helix)
     helix.insert_fragment(mf)
     self.assertEqual(helix.get_sequence(), Sequence('AAAAAAAA_UCUUUUUUU'))
     self.assertEqual(helix.get_secstruc(), '(((((((().)))))))')
Ejemplo n.º 25
0
    def test_model_with_close_gaps(self):
        t = Template('test_data/rna_structures/2du3_excerpt.ent', 'file', 'D')
        a = read_alignment('''> 1qru_B.pdb X55374.1/1-72
GCA-UUCCG
> 2du3_D.pdb
CUUUA-CCC
''')
        m = RnaModel()
        copy_some_residues([t['944'], t['946'], t['947']], m)
        lc = find_fragment(m, '946', '947', Sequence('U'))
        insert_fragment(m, lc[0])
        lc = find_fragment(m, '944', '946', Sequence(''))
        insert_fragment(m, lc[0])
        return  #TODO: remove
        # generate model
        m = RnaModel(t, a)
        m.create_model()
Ejemplo n.º 26
0
 def test_fill_gap_numbering(self):
     """Should insert fragment with correct numbering."""
     t = Template(DOUBLEGAP, 'file', 'A')
     m = RnaModel()
     for r in t:
         m.copy_residue(r)
     struc = ModernaStructure('file', FRAGMENT1)
     f1 = ModernaFragment53(struc,
                            anchor5=m['20'],
                            anchor3=m['24'],
                            new_sequence=Sequence('AUA'))
     m.insert_fragment(f1)
     resids = [r.identifier for r in m]
     expected_resids1 = [
         '18', '19', '20', '20A', '20B', '20C', '24', '27', '28', '29',
         '30', '31', '32', '33', '34', '35'
     ]
     self.assertEqual(resids, expected_resids1)
Ejemplo n.º 27
0
class ModelMinimization:
    """
    Main class for minimizing models
    """
    def __init__(self, options, temp_path):
        self.options = options
        # structure
        print 'Loading model from %s, chain %s'%(options.input_file, options.chain_name)
        self.model = load_model(options.input_file, options.chain_name)
        self.model_passive = None
        self.stem5,  self.stem3 = None, None
        self.sequence_before = self.model.get_sequence()
        self.model_resnumbers = []
        # parameters
        self.residues = None
        if options.residues:
            self.residues = options.residues.split('-')
        self.cycles = int(options.cycles)
        self.output_name = options.output_file
        self.modifications = []
        self.restraints = []
        self.mmtk_output_file = 'mmtk_output.pdb'
        self.temp_pdb_file = temp_path

    def model_to_tempfile(self):
        """writes model to temporary file."""
        self.model.write_pdb_file(self.temp_pdb_file)
        self.model = None

    def tempfile_to_model(self):
        """Reads model from temporary file."""
        self.model = load_model(self.temp_pdb_file, self.options.chain_name)

    def extract_region(self):
        self.model.renumber_chain()
        """Cuts out the residues for optimization and keeps the rest in memory."""
        if self.residues:
            print '\nExtracting the region to be optimized (%s-%s) from the model.'%(self.residues[0], self.residues[1])
            print '\t.. total residues in model                    : %4i'%len(self.model)
            self.model_passive = self.model.find_residues_not_in_range(self.residues[0], self.residues[1])
            print '\t.. residues not participating in optimization : %4i (+2 for superposition afterwards)'%(len(self.model_passive)-2)
            print '\t   '+','.join([r.identifier for r in self.model_passive])
            self.model = RnaModel(None, None, self.options.chain_name, 'residues', self.model[self.residues[0]:self.residues[1]])
            # memorize residue numbers because MMTK screws them
            self.model_resnumbers = [r.identifier for r in self.model]
            print '\t.. residues participating in optimization     : %4i'%len(self.model)
            print '\t   '+','.join([r.identifier for r in self.model])
            # keeps duplicate versions of the residues indicated by self.residues,
            # so they can be superimposed later
            self.stem5,  self.stem3 = self.model[self.residues[0]], self.model[self.residues[1]]
        else:
            self.struc_to_optimize = self.model

    def merge_region(self):
        """Merges the optimized residues with the memorized ones."""
        residues = [r for r in self.model]
        if self.model_passive:
            # apply old residue numbers
            print '\nRestoring original numeration in the optimized region.'
            for num, resi in zip(self.model_resnumbers, residues):
                #print resi, num
                #self.model.renumber_residue(resi.identifier, num)
                resi.change_number(num)
            self.model = ModernaStructure('residues',residues)
            # do the superposition
            print '\nSuperimposing the optimized part onto the rest of the model.'
            all_atoms = self.model.get_all_atoms()
            sup = ModernaSuperimposer(moved_atoms = all_atoms)
            sup.get_atoms([self.stem5, self.stem3], BACKBONE_ATOMS, 'fixed')
            resi5, resi3 = self.model[self.residues[0]], self.model[self.residues[1]]
            sup.get_atoms([resi5, resi3], BACKBONE_ATOMS, 'moved')
            sup.superimpose()

            # merge residues
            print '\nMerging the optimized part with the rest of the model.'
            resi = [r for r in self.model]
            for r in self.model_passive:
                if r.identifier not in self.residues:
                    resi.append(r)
            self.model = RnaModel(None, None, self.options.chain_name, 'residues', resi)


    def remove_modifications(self):
        """Memorizes modified nucleotides for later, and then removes them."""
        print '\nRemoving modified bases from the model.'
        for resi in self.model.get_modified_residues():
            resi=self.model[resi]
            modi = (resi.identifier, resi.long_abbrev)
            print '\t.. %s at position %s'%modi
            self.modifications.append(modi)
        self.model.remove_all_modifications()
        # check for O3 atoms
        for resi in self.model:
            if resi.child_dict.has_key(' O3P'):
                raise OptimizationError('O3P atoms cannot be handled by MMTK!')


    def change_atom_names(self, forth=False, back=False):
        """Replaces atom and residue names so that MMTK can iterpret them."""
        print '\nReplacing names in temporary PDB file (%s)'%((forth and 'ModeRNA->MMTK') or (back and 'MMTK->ModeRNA'))
        if forth: nameset = FORTH_SET
        elif back: nameset = BACK_SET
        else: raise OptimizationError("Invalid options for changing atom names.")
        # replace residue and atom names
        out = []
        for line in open(self.temp_pdb_file):
            if line.startswith('ATOM') or line.startswith('HETATM'):
                resiname = nameset.replace_residue_name(line[17:20])
                atomname = nameset.replace_atom_name(line[12:16])
                line = line[:12]+atomname+line[16:17]+resiname+line[20:]
            if len(line)>13 and line[13]!='H': # discard hydrogens
                out.append(line)
        open(self.temp_pdb_file, 'w').writelines(out)


    def create_restraints(self, chain):
        """If a residue range was specified, these residues are cut out, and """
        if self.residues:
            print '\t.. building restraints'
            first_resi = chain[0]
            last_resi = chain[-1]

            # distances between the two terminal residues
            dist_po = (self.stem5['P'] - self.stem3["O3'"])/10.0
            restraints = HarmonicDistanceRestraint(first_resi.phosphate.P, last_resi.sugar.O_3, dist_po, 10000.)
            dist_co = (self.stem5["O5'"] - self.stem3["O3'"])/10.0
            restraints += HarmonicDistanceRestraint(first_resi.sugar.O_5, last_resi.sugar.C_3, dist_co, 10000.)
            dist_cc = (self.stem5["C5'"] - self.stem3["C4'"])/10.0
            restraints += HarmonicDistanceRestraint(first_resi.sugar.C_5, last_resi.sugar.C_4, dist_cc, 10000.)

            # angles between the two terminal residues
            angle_cpo = calc_angle(self.stem5["C4'"].get_vector(), self.stem3["P"].get_vector(), self.stem3["O3'"].get_vector())
            #angle_cpo = calc_angle(self.stem3["P"].coord-self.stem5["C4'"].coord, self.stem3["P"].coord-self.stem3["O3'"].coord)
            restraints += HarmonicAngleRestraint(first_resi.sugar.C_4, last_resi.phosphate.P, last_resi.sugar.O_3, angle_cpo, 100000.)
            angle_pco1 = calc_angle(self.stem5["P"].get_vector(), self.stem3["C4'"].get_vector(), self.stem3["O3'"].get_vector())
            restraints += HarmonicAngleRestraint(first_resi.phosphate.P, last_resi.sugar.C_4, last_resi.sugar.O_3, angle_pco1, 10000.)
            angle_pco2 = calc_angle(self.stem5["P"].get_vector(), self.stem5["C4'"].get_vector(), self.stem3["O3'"].get_vector())
            restraints += HarmonicAngleRestraint(first_resi.phosphate.P, first_resi.sugar.C_4, last_resi.sugar.O_3, angle_pco2, 10000.)
            angle_pcc = calc_angle(self.stem5["P"].get_vector(), self.stem5["C4'"].get_vector(), self.stem3["C4'"].get_vector())
            restraints += HarmonicAngleRestraint(first_resi.phosphate.P, first_resi.sugar.C_4, last_resi.sugar.C_4, angle_pcc, 10000.)
            # torsion between the two terminal residues
            # THESE PRODUCE SEGMENTATION FAULTS - THE OTHERS MUST SUFFICE
            # restraints += HarmonicDihedralRestraint(first_resi.phosphate.P, first_resi.sugar.C_4, last_resi.phosphate.P, last_resi.sugar.C_4, 1.0, 10.)
            #restraints += HarmonicDihedralRestraint(first_resi.phosphate.P, first_resi.sugar.C_4, last_resi.sugar.C_4, last_resi.sugar.O_3, 0.0, 100000.)
            #restraints += HarmonicDihedralRestraint(first_resi.sugar.C_4, first_resi.sugar.O_3, last_resi.phosphate.P, last_resi.sugar.C_4, 0.0, 100000.)
            #restraints += HarmonicDihedralRestraint(first_resi.sugar.C_4, first_resi.sugar.O_3, last_resi.sugar.C_4, last_resi.sugar.O_3, 0.0, 100000.)

            return restraints

    def optimize(self):
        """Run the optimization with MMTK"""
        print '\n-------------------------------------------------------------------------------'
        print '\n MMTK Optimization starts...'

        print '\t.. building universe'
        configuration = PDBConfiguration(self.temp_pdb_file)
        # Construct the nucleotide chain object. This also constructs positions
        # for the missing hydrogens, using geometrical criteria.
        chain = configuration.createNucleotideChains()[0]
        universe = InfiniteUniverse()
        universe.addObject(chain)

        restraints = self.create_restraints(chain)

        # define force field
        print '\t.. setting up force field'
        if restraints:
            ff = Amber94ForceField() + restraints
        else:
            ff = Amber94ForceField()
        universe.setForceField(ff)

        # do the minimization
        print '\t.. starting minimization with %i cycles'%self.cycles
        minimizer = ConjugateGradientMinimizer(universe)
        minimizer(steps = self.cycles)
        # write the intermediate output
        print '\t.. writing MMTK output to %s'% self.temp_pdb_file
        if self.model_passive:
            print '\t   (please note that MMTK applies a different numeration of residues.\n\t    The original one will be restored in the final output).'
        universe.writeToFile(self.mmtk_output_file)
        open(self.temp_pdb_file, 'w').write(open(self.mmtk_output_file).read())
        print '\n-------------------------------------------------------------------------------'

    def add_modifications(self):
        """Restores modifications on the model."""
        print "\nAdding modifications back to the model:"
        for position, modif in self.modifications:
            print "\t.. adding %s in position %s"%(modif, position)
            self.model[position].add_modification(modif)
        # check if sequence stayed the same
        print '\nSequence before optimization'
        print self.sequence_before
        print 'Sequence after optimization'
        print self.model.get_sequence()

    def write_result(self):
        """Creates the output file."""
        print "\nWriting final output to: %s"%self.output_name
        self.model.write_pdb_file(self.output_name)
Ejemplo n.º 28
0
 def test_load_model(self):
     """A model should be loadable from a file."""
     m = RnaModel(None, None, 'A', 'file', MINI_TEMPLATE)
     self.assertEqual(len(m), 15)
Ejemplo n.º 29
0
 def setUp(self):
     self.a = read_alignment(MINI_ALIGNMENT)
     self.t = Template(MINI_TEMPLATE, seq=Sequence("GCGGAUUUALCUCAG"))
     self.m = RnaModel(self.t, self.a)
     self.seq_before = self.t.get_sequence()
     self.br = BaseRecognizer()
Ejemplo n.º 30
0
 def test_gap_optimization_example_2(self):
     t = Template('test_data/gaps/mini_1h4s_T_gap2.pdb', 'file', 'T')
     a = read_alignment('test_data/gaps/ali_gap2.fasta')
     m = RnaModel(t, a)
     m.create_model()