Beispiel #1
0
    def __init__(self,
                 references,
                 clones_list,
                 transforms,
                 label='',
                 strength=10.0,
                 ca_only=False):
        """Constructor
        @param references Can be one of the following inputs:
               IMP Hierarchy, PMI System/State/Molecule/TempResidue,
               or a list/set of them
        @param clones_list List of lists of the above
        @param transforms Transforms moving each selection to the first
               selection
        @param label Label for output
        @param strength            The elastic bond strength
        @param ca_only Optionally select so only CAlpha particles are used
        """

        refs = IMP.pmi.tools.input_adaptor(references, flatten=True)
        self.mdl = refs[0].get_model()
        self.rs = IMP.RestraintSet(self.mdl, "Symmetry")
        self.weight = 1
        self.label = label
        if len(clones_list) != len(transforms):
            raise Exception(
                'Error: There should be as many clones as transforms')

        harmonic = IMP.core.Harmonic(0., strength)
        for tmp_clones, trans in zip(clones_list, transforms):
            clones = IMP.pmi.tools.input_adaptor(tmp_clones, flatten=True)
            if len(clones) != len(refs):
                raise Exception("Error: len(references)!=len(clones)")
            pair_score = IMP.core.TransformedDistancePairScore(harmonic, trans)
            for p0, p1 in zip(refs, clones):
                if not ca_only or (IMP.atom.Atom(p0).get_atom_type()
                                   == IMP.atom.AtomType("CA")
                                   and IMP.atom.Atom(p1).get_atom_type()
                                   == IMP.atom.AtomType("CA")):
                    r = IMP.core.PairRestraint(
                        self.mdl, pair_score,
                        [p0.get_particle_index(),
                         p1.get_particle_index()])
                    self.rs.add_restraint(r)
        print('created symmetry network with',
              self.rs.get_number_of_restraints(), 'restraints')
Beispiel #2
0
    def test_xyz_particles(self):
        m = IMP.Model()
        ps = []
        hs = []
        for i in range(10):
            p = IMP.Particle(m)
            h = IMP.atom.Hierarchy.setup_particle(p)
            d = IMP.core.XYZR.setup_particle(p)
            IMP.atom.Mass.setup_particle(p, 1.0)
            d.set_coordinates(
                IMP.algebra.get_random_vector_in(
                    IMP.algebra.Sphere3D((0, 0, 0), 10)))
            d.set_radius(1)
            ps.append(p)
            hs.append(h)

        srbm = IMP.pmi.TransformMover(m, 1, 0.5)

        #origin point
        origin = IMP.Particle(m)
        d = IMP.core.XYZR.setup_particle(origin)
        d.set_coordinates((0, 0, 0))
        d.set_radius(1)

        rs = IMP.RestraintSet(m)
        ts1 = IMP.core.Harmonic(10, 10)
        dr = IMP.core.DistanceRestraint(m, ts1, ps[0], origin)

        for p in ps:
            srbm.add_xyz_particle(IMP.core.XYZ(p))
        smv = IMP.core.SerialMover([srbm])
        mc = IMP.core.MonteCarlo(m)
        mc.set_scoring_function([dr])
        mc.set_return_best(False)
        mc.set_kt(1.0)
        mc.add_mover(smv)

        rh = RMF.create_rmf_file("test_transform_mover_xyz.rmf3")
        IMP.rmf.add_hierarchies(rh, hs)

        for n in range(10):
            mc.optimize(1)
            IMP.rmf.save_frame(rh)

        del rh
Beispiel #3
0
    def __init__(
        self,
        representation,
        handleparticles_tuples,
        compositeparticles_tuple_list,
        cut_off=5.0,
        lam=1.0,
        plateau=0.0,
        resolution=None,
            label="None"):

        # composite particles: all particles beside the handle
        self.label = label
        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, 'cr')

        self.handleparticles = []
        for s in handleparticles_tuples:
            self.handleparticles += IMP.pmi.tools.select_by_tuple(representation, s,
                                                             resolution=resolution, name_is_ambiguous=True)
        self.compositeparticles=[]
        compositeparticle_list = []
        for list in compositeparticles_tuple_list:
            tmplist = []
            for s in list:
                tmplist += IMP.pmi.tools.select_by_tuple(
                    representation, s,
                    resolution=resolution, name_is_ambiguous=True)
            compositeparticle_list.append(tmplist)
            self.compositeparticles+=tmplist


        ln = IMP.pmi.CompositeRestraint(
            self.m,
            self.handleparticles,
            cut_off,
            lam,
            True,
            plateau)

        for ps in compositeparticle_list:
            # composite particles is a list of list of particles
            ln.add_composite_particle(ps)

        self.rs.add_restraint(ln)
Beispiel #4
0
    def __init__(self,
                 representation,
                 selection_tuple,
                 distance=3.78,
                 strength=10.0,
                 jitter=None):
        """Constructor
        @param representation
        @param selection_tuple Requested selection
        @param distance Resting distance for restraint
        @param strength Bond constant
        @param jitter Defines the +- added to the optimal distance in the harmonic well restraint
                      used to increase the tolerance
        """
        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, "Bonds")
        self.weight = 1
        self.label = "None"
        self.pairslist = []

        particles = IMP.pmi.tools.select_by_tuple(
            representation,
            selection_tuple,
            resolution=1)

        if not jitter:
            ts = IMP.core.Harmonic(distance, strength)
        else:
            ts = IMP.core.HarmonicWell(
                (distance - jitter, distance + jitter), strength)

        for ps in IMP.pmi.tools.sublist_iterator(particles, 2, 2):
            pair = []
            if len(ps) != 2:
                raise ValueError("wrong length of pair")
            for p in ps:
                if not IMP.atom.Residue.get_is_setup(p):
                    raise TypeError("not a residue")
                else:
                    pair.append(p)
            print("ResidueBondRestraint: adding a restraint between %s %s" % (pair[0].get_name(), pair[1].get_name()))
            self.rs.add_restraint(
                IMP.core.DistanceRestraint(self.m, ts, pair[0], pair[1]))
            self.pairslist.append(IMP.ParticlePair(pair[0], pair[1]))
            self.pairslist.append(IMP.ParticlePair(pair[1], pair[0]))
Beispiel #5
0
    def test_some_scores(self):
        pdb_fn = self.get_input_file_name('helix2.pdb')

        mdl = IMP.Model()
        mh = IMP.atom.read_pdb(pdb_fn, mdl, IMP.atom.NonWaterPDBSelector())
        ps = IMP.atom.Selection(
            mh, atom_type=IMP.atom.AtomType("CA")).get_selected_particles()
        strength = 10.0
        rs = IMP.RestraintSet(mdl, "ElasticNetwork")
        for pidx in itertools.combinations(range(len(ps)), 2):
            pair = [ps[pidx[0]], ps[pidx[1]]]
            distance = IMP.algebra.get_distance(
                IMP.core.XYZ(pair[0]).get_coordinates(),
                IMP.core.XYZ(pair[1]).get_coordinates())
            ts = IMP.core.Harmonic(distance, strength)
            rs.add_restraint(IMP.core.DistanceRestraint(ts, pair[0], pair[1]))
        mdl.add_restraint(rs)
        print(rs.evaluate(False))
Beispiel #6
0
    def __init__(
        self,
        representation,
        images,
        resolution=None):

        self.weight=1.0
        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, 'em2d')
        self.label = "None"

        # IMP.atom.get_by_type
        particles = IMP.pmi.tools.select(
            representation,
            resolution=resolution)

        em2d = None
        self.rs.add_restraint(em2d)
Beispiel #7
0
 def test_decomposition_4(self):
     """Test cache with decomposition with nested sets"""
     (m, ps, r, pst, ik, cache) = self._create_stuff()
     rs = IMP.RestraintSet(m, 1.0, "outer")
     rs.set_maximum_score(2)
     rs.add_restraint(r)
     r.set_weight(3)
     cache.add_restraints([rs])
     subset = IMP.domino.Subset(ps)
     rsb = cache.get_restraints(subset,
                                [IMP.domino.Subset([p]) for p in ps])
     self.assertEqual(len(rsb), 1)
     slc = cache.get_slice(rsb[0], subset)
     self.assertEqual(len(slc), len(ps))
     aslc = slc.get_sliced(IMP.domino.Assignment(range(len(ps))))
     self.assertEqual(len(aslc), len(ps))
     score = cache.get_score(rsb[0], aslc)
     self.assert_(score > 1000)
Beispiel #8
0
 def init_model_NOEs_marginal(self,
                              prot,
                              seqfile,
                              tblfile,
                              name='NOE',
                              verbose=True,
                              sequence_match=(1, 1)):
     """read TBL file and store NOE restraints, using the marginal of the
     lognormal with one sigma and one gamma, for the whole dataset.
     - prot: protein hierarchy
     - seqfile: a file with 3-letter sequence
     - tblfile: a TBL file with the restraints
     - name: an optional name for the restraintset
     - verbose: be verbose (default True)
     - sequence_match : (noe_start, sequence_start)
     Returns: data_rs
     """
     # likelihood
     rs = IMP.RestraintSet(self._m, 1.0, name)
     # use the TBLReader to parse the TBL file.
     sequence = IMP.isd.utils.read_sequence_file(
         seqfile, first_residue_number=sequence_match[1])
     tblr = IMP.isd.TBLReader.TBLReader(sequence,
                                        sequence_match=sequence_match)
     restraints = tblr.read_distances(tblfile, 'NOE')['NOE']
     ln = IMP.isd.MarginalNOERestraint()
     for i, restraint in enumerate(restraints):
         if verbose and i % 100 == 0:
             print("\r%d" % i, end=' ')
             sys.stdout.flush()
         # a restraint is (contributions, dist, upper, lower, volume)
         # where contributions is a tuple of contributing pairs
         # and a pair is (c1, c2), where c1 is of the form (resno, atname)
         # residue numbers start at 0
         pairs = [(self.find_atom(i, prot).get_particle(),
                   self.find_atom(j, prot).get_particle())
                  for (i, j) in restraint[0]]
         pairs = IMP.container.ListPairContainer(pairs)
         ln.add_contribution(pairs, restraint[4])
     rs.add_restraint(ln)
     if verbose:
         print("\r%d NOE contributions added" % (len(restraints)))
     self._m.add_restraint(rs)
     return rs
Beispiel #9
0
 def test_global_min2(self):
     """Testing finding minima with rigid bodies"""
     m = IMP.Model()
     rbs = [self._create_rb("1", m), self._create_rb("2", m)]
     trs = [
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(0, 0,
                                                                   0))),
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(2, 0,
                                                                   0))),
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(4, 0,
                                                                   0)))
     ]
     ps = IMP.core.HarmonicSphereDistancePairScore(0, 1)
     r = IMP.core.PairRestraint(
         m, ps,
         (rbs[0].get_rigid_members()[0], rbs[1].get_rigid_members()[0]))
     r.set_name("restraint")
     rs = IMP.RestraintSet(m)
     rs.add_restraint(r)
     r.set_maximum_score(.5)
     pst = IMP.domino.ParticleStatesTable()
     pstate = IMP.domino.RigidBodyStates(trs)
     pst.set_particle_states(rbs[0], pstate)
     pst.set_particle_states(rbs[1], pstate)
     rg = IMP.domino.get_restraint_graph(rs, pst)
     # rg.show_dotty()
     print("ig")
     ig = IMP.domino.get_interaction_graph([rs], pst)
     # IMP.show_graphviz(ig)
     print("dg")
     IMP.set_log_level(IMP.VERBOSE)
     dg = IMP.get_dependency_graph(m)
     # IMP.show_graphviz(dg)
     print("jt")
     jt = IMP.domino.get_junction_tree(ig)
     # jt.show_dotty()
     s = IMP.domino.DominoSampler(m, pst)
     s.set_restraints([rs])
     s.set_log_level(IMP.VERBOSE)
     cg = s.create_sample()
     self.assertEqual(cg.get_number_of_configurations(), 4)
Beispiel #10
0
    def __init__(self,
                 ps,
                 dmap,
                 resolution,
                 origin=None,
                 voxel_size=None,
                 weight=1.0,
                 label=""):
        """Constructor
        @param ps The particles to restrain. Currently these must be atomic particles.
        @param map_fn The EM density map to fit to
        @param resolution Map resolution
        @param origin In case you need to tell IMP the correct origin
        @param voxel_size In case you need to tell IMP the angstroms per pixel
        @param weight The data weight
        @param label Extra PMI label
        """
        print('FitRestraint: setup')
        #print('\tmap_fn',map_fn)
        print('\tresolution',resolution)
        print('\tvoxel_size',voxel_size)
        print('\torigin',origin)
        print('\tweight',weight)

        # some parameters
        self.mdl = ps[0].get_model()
        self.label = label
        self.dmap = dmap #IMP.em.read_map(map_fn,IMP.em.MRCReaderWriter())
        #dh = self.dmap.get_header()
        #dh.set_resolution(resolution)
        if voxel_size:
            self.dmap.update_voxel_size(voxel_size)
        if origin is not None:
            if type(origin)==IMP.algebra.Vector3D:
                self.dmap.set_origin(origin)
            elif type(origin)==list:
                self.dmap.set_origin(*origin)
            else:
                print('FitRestraint did not recognize format of origin')
                exit()
        fr = IMP.em.FitRestraint(ps,self.dmap)
        self.rs = IMP.RestraintSet(self.mdl,weight,"FitRestraint")
        self.rs.add_restraint(fr)
        self.set_weight(weight)
Beispiel #11
0
    def __init__(self,
                 representation,
                 tuple_selection1,
                 tuple_selection2,
                 distancemin,
                 distancemax,
                 resolution=1.0,
                 kappa=1.0):
        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, 'distance')

        #ts = IMP.core.Harmonic(distance,kappa)

        ts1 = IMP.core.HarmonicUpperBound(distancemax, kappa)
        ts2 = IMP.core.HarmonicLowerBound(distancemin, kappa)

        # IMP.atom.get_by_type
        particles1 = IMP.pmi.tools.select(representation,
                                          resolution=resolution,
                                          name=tuple_selection1[2],
                                          residue=tuple_selection1[0])
        particles2 = IMP.pmi.tools.select(representation,
                                          resolution=resolution,
                                          name=tuple_selection2[2],
                                          residue=tuple_selection2[0])

        for p in particles1:
            print p.get_name()

        for p in particles2:
            print p.get_name()

        if len(particles1) > 1:
            print "DistanceRestraint error: more than one particle selected"
            exit()
        if len(particles2) > 1:
            print "DistanceRestraint error: more than one particle selected"
            exit()

        self.rs.add_restraint(
            IMP.core.DistanceRestraint(ts1, particles1[0], particles2[0]))
        self.rs.add_restraint(
            IMP.core.DistanceRestraint(ts2, particles1[0], particles2[0]))
Beispiel #12
0
 def test_refcount_director_restraints(self):
     """Refcounting should prevent director Restraints from being deleted"""
     dirchk = IMP.test.DirectorObjectChecker(self)
     m = IMP.Model("ref count dir restraints")
     rs = IMP.RestraintSet(m)
     IMP.set_log_level(IMP.VERBOSE)
     r = DummyRestraint(m)
     r.python_member = 'test string'
     rs.add_restraint(r)
     # Since C++ now holds a reference to r, it should be safe to delete the
     # Python object (director objects should not be freed while C++ holds
     # a reference)
     del r
     newr = rs.get_restraint(0)
     self.assertEqual(newr.python_member, 'test string')
     # Make sure that all director objects are cleaned up
     dirchk.assert_number(1)
     del newr, m, rs
     dirchk.assert_number(0)
Beispiel #13
0
 def test_global_min3(self):
     """Testing splitting restraints with rigid bodies and interestings scores"""
     m = IMP.Model()
     rbs = [
         self._create_rb("1", m, 4),
         self._create_rb("2", m, 4),
         self._create_rb("3", m, 4)
     ]
     trs = [
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(0, 0,
                                                                   0))),
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(2, 0,
                                                                   0))),
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(4, 0,
                                                                   0)))
     ]
     lps = IMP.core.SphereDistancePairScore(
         IMP.core.HarmonicUpperBound(0, 1))
     ps = IMP.core.KClosePairsPairScore(lps, IMP.core.RigidMembersRefiner())
     pl = IMP.container.ListPairContainer(m, [(rbs[0], rbs[1]),
                                              (rbs[1], rbs[2])])
     r = IMP.container.PairsRestraint(ps, pl)
     r.set_name("restraint")
     rs = IMP.RestraintSet(m)
     rs.add_restraint(r)
     r.set_maximum_score(.5)
     dg = IMP.get_dependency_graph(m)
     # dg.show_dotty()
     pst = IMP.domino.ParticleStatesTable()
     pstate = IMP.domino.RigidBodyStates(trs)
     pst.set_particle_states(rbs[0], pstate)
     pst.set_particle_states(rbs[1], pstate)
     pst.set_particle_states(rbs[2], pstate)
     #occ= IMP.domino.OptimizeRestraints(m.get_root_restraint_set(), pst)
     rc = IMP.domino.RestraintCache(pst)
     rc.add_restraints([rs])
     allr = rc.get_restraints()
     for r in allr:
         print(r.get_name())
     self.assertEqual(len(allr), 3)
Beispiel #14
0
    def __init__(self, representation,
                 hierarchies=None,
                 other_hierarchies=None,
                 resolution=None, kappa=1.0):

        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, 'excluded_volume')
        self.weight = 1.0
        self.kappa = kappa

        self.label = "None"
        self.cpc = None

        ssps = IMP.core.SoftSpherePairScore(self.kappa)
        lsa = IMP.container.ListSingletonContainer(self.m)

        particles = IMP.pmi.tools.select(
            representation,
            resolution=resolution,
            hierarchies=hierarchies)

        lsa.add_particles(particles)

        if other_hierarchies is None:
            rbcpf = IMP.core.RigidClosePairsFinder()
            self.cpc = IMP.container.ClosePairContainer(lsa, 0.0, rbcpf, 10.0)
            evr = IMP.container.PairsRestraint(ssps, self.cpc)

        else:
            other_lsa = IMP.container.ListSingletonContainer(self.m)
            other_particles = IMP.pmi.tools.select(
                representation,
                resolution=resolution,
                hierarchies=other_hierarchies)
            other_lsa.add_particles(particles)
            self.cpc = IMP.container.CloseBipartitePairContainer(
                lsa,
                other_lsa,
                0.0,
                10.0)
            evr = IMP.container.PairsRestraint(ssps, self.cpc)

        self.rs.add_restraint(evr)
Beispiel #15
0
 def create_restraints_for_rmf(self):
     """ create dummy harmonic restraints for each XL but don't add to model
     Makes it easy to see each contribution to each XL in RMF
     """
     dummy_mdl = IMP.Model()
     hps = IMP.core.HarmonicDistancePairScore(self.length, 1.0)
     dummy_rs = []
     for nxl in range(self.rs.get_number_of_restraints()):
         xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
             self.rs.get_restraint(nxl))
         rs = IMP.RestraintSet(dummy_mdl, 'atomic_xl_' + str(nxl))
         for ncontr in range(xl.get_number_of_contributions()):
             ps = xl.get_contribution(ncontr)
             dr = IMP.core.PairRestraint(
                 hps, [self.mdl.get_particle(p) for p in ps],
                 'xl%i_contr%i' % (nxl, ncontr))
             rs.add_restraint(dr)
             dummy_rs.append(MyGetRestraint(rs))
     return dummy_rs
Beispiel #16
0
    def __init__(self,
                 root,
                 map_fn,
                 resolution,
                 origin=None,
                 voxel_size=None,
                 weight=1.0,
                 label="",
                 selection_dict=None):
        """ create a FitRestraint. can provide rigid bodies instead of individual particles """

        print('FitRestraint: setup')
        print('\tmap_fn', map_fn)
        print('\tresolution', resolution)
        print('\tvoxel_size', voxel_size)
        print('\torigin', origin)
        print('\tweight', weight)

        # some parameters
        self.mdl = root.get_model()
        self.label = label
        self.dmap = IMP.em.read_map(map_fn, IMP.em.MRCReaderWriter())
        dh = self.dmap.get_header()
        dh.set_resolution(resolution)
        if voxel_size:
            self.dmap.update_voxel_size(voxel_size)
        if type(origin) == IMP.algebra.Vector3D:
            self.dmap.set_origin(origin)
        elif type(origin) == list:
            self.dmap.set_origin(*origin)
        else:
            print('FitRestraint did not recognize format of origin')
            exit()
        if selection_dict:
            ps = IMP.atom.Selection(root,
                                    **selection_dict).get_selected_particles()
        else:
            ps = IMP.atom.get_leaves(root)
        fr = IMP.em.FitRestraint(ps, self.dmap)
        self.rs = IMP.RestraintSet(self.mdl, weight, "FitRestraint")
        self.rs.add_restraint(fr)
        self.set_weight(weight)
Beispiel #17
0
    def __init__(
        self,
        representation,
        selection_tuple,
        anglemin=100.0,
        anglemax=140.0,
            strength=10.0):
        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, "Angles")
        self.weight = 1
        self.label = "None"
        self.pairslist = []

        particles = IMP.pmi.tools.select_by_tuple(
            representation,
            selection_tuple,
            resolution=1)

        ts = IMP.core.HarmonicWell(
            (self.pi * anglemin / 180.0,
             self.pi * anglemax / 180.0),
            strength)

        for ps in IMP.pmi.tools.sublist_iterator(particles, 3, 3):
            triplet = []
            if len(ps) != 3:
                print "ResidueAngleRestraint: wrong length of triplet"
                exit()
            for p in ps:
                if not IMP.atom.Residue.get_is_setup(p):
                    print "ResidueAngleRestraint: not a residue"
                    exit()
                else:
                    triplet.append(p)
            print "ResidueAngleRestraint: adding a restraint between %s %s %s" % (triplet[0].get_name(), triplet[1].get_name(), triplet[2].get_name())
            self.rs.add_restraint(
                IMP.core.AngleRestraint(ts,
                                        triplet[0],
                                        triplet[1],
                                        triplet[2]))
            self.pairslist.append(IMP.ParticlePair(triplet[0], triplet[2]))
            self.pairslist.append(IMP.ParticlePair(triplet[2], triplet[0]))
Beispiel #18
0
 def test_delete_model_accessor_2(self):
     "Python Restraints from vector accessors should survive model deletion"
     refcnt = IMP.test.RefCountChecker(self)
     m = IMP.Model("restraint survival")
     rs = IMP.RestraintSet(m)
     r = IMP._ConstRestraint(m, [], 1)
     rs.add_restraint(r)
     del r
     # Now create new Python Restraint r from a C++ vector accessor
     # These accessors call specific methods in the SWIG wrapper which
     # are modified by typemaps in our interface.
     r = rs.get_restraints()[0]
     # Python reference r plus C++ reference from m
     self.assertEqual(r.get_ref_count(), 2)
     del m, rs
     # Now only the Python reference r should survive
     self.assertEqual(r.get_ref_count(), 1)
     refcnt.assert_number(1)
     del r
     refcnt.assert_number(0)
Beispiel #19
0
 def test_delete_model_iterator(self):
     """Python Restraints from iterators should survive model deletion"""
     refcnt = IMP.test.RefCountChecker(self)
     m = IMP.Model("python restraint survival")
     rs = IMP.RestraintSet(m)
     r = IMP._ConstRestraint(m, [], 1)
     rs.add_restraint(r)
     del r
     # Now create new Python Restraint r from C++ iterator
     # This calls swig::from() internally, which is modified by template
     # specialization in our SWIG interface.
     r = rs.get_restraints()[0]
     # Python reference r plus C++ reference from m
     self.assertEqual(r.get_ref_count(), 2)
     del m, rs
     # Now only the Python reference r should survive
     self.assertEqual(r.get_ref_count(), 1)
     refcnt.assert_number(1)
     del r
     refcnt.assert_number(0)
Beispiel #20
0
    def __init__(self, objects, kappa=10.0, resolution=1.0, label="None"):

        self.weight = 1.0
        self.kappa = kappa
        self.label = label
        if self.label == "None":
            self.label = str(selection_tuples)  # noqa: F821

        hiers = []

        for obj in objects:
            hiers.append(
                IMP.pmi.tools.input_adaptor(obj, resolution, flatten=True))
            self.m = hiers[0][0].get_model()

        cr = ConnectivityNetworkRestraint(self.m)
        for hs in hiers:
            cr.add_particles([h.get_particle() for h in hs])
        self.rs = IMP.RestraintSet(self.m, label)
        self.rs.add_restraint(cr)
Beispiel #21
0
 def test_rescaling(self):
     """Test thermostatting by velocity rescaling"""
     for i in range(100):
         self.particles.append(self.create_point_particle(self.model,
                                                          -43.0, 65.0, 93.0))
         self.particles[-1].add_attribute(masskey, cmass, False)
     self.md.assign_velocities(100.0)
     scaler = IMP.atom.VelocityScalingOptimizerState(self.model,
                                                     self.particles, 298.0)
     scaler.set_period(10)
     self.md.add_optimizer_state(scaler)
     r = IMP.RestraintSet(self.model)
     self.md.set_scoring_function(r)
     self.md.optimize(10)
     # Temperature should have been rescaled to 298.0 at some point:
     self._check_temperature(298.0, 0.1)
     # Also check immediate rescaling:
     scaler.set_temperature(50.0)
     scaler.rescale_velocities()
     self._check_temperature(50.0, 0.1)
Beispiel #22
0
    def save_rmf_snapshot(self, filename):

        sorted_ids = None
        sorted_group_ids = sorted(self.cross_link_db.data_base.keys())
        list_of_pairs = []
        for group in sorted_group_ids:
            group_xls = []
            group_dists_particles = []
            for xl in self.cross_link_db.data_base[group]:
                xllabel = self.cross_link_db.get_short_cross_link_string(xl)
                (c1, c2, r1,
                 r2) = IMP.pmi.io.crosslink._ProteinsResiduesArray(xl)
                try:
                    (mdist, p1, p2) = self._get_distance_and_particle_pair(
                        r1, c1, r2, c2)
                except TypeError:
                    continue
                group_dists_particles.append((mdist, p1, p2, xllabel))
            if group_dists_particles:
                (minmdist, minp1, minp2,
                 minxllabel) = min(group_dists_particles, key=lambda t: t[0])
                list_of_pairs.append((minp1, minp2, xllabel))
            else:
                continue

        m = self.prots[0].get_model()
        linear = IMP.core.Linear(0, 0.0)
        linear.set_slope(1.0)
        dps2 = IMP.core.DistancePairScore(linear)
        rslin = IMP.RestraintSet(m, 'linear_dummy_restraints')

        for pair in list_of_pairs:
            pr = IMP.core.PairRestraint(m, dps2, (pair[0], pair[1]))
            pr.set_name(pair[2])
            rslin.add_restraint(pr)

        rh = RMF.create_rmf_file(filename)
        IMP.rmf.add_hierarchies(rh, self.prots)
        IMP.rmf.add_restraints(rh, [rslin])
        IMP.rmf.save_frame(rh)
        del rh
Beispiel #23
0
 def test_interaction_graph(self):
     """Testing the interaction graph with rigid bodies"""
     m = IMP.Model()
     rb0 = self._create_rigid_body(m)
     rb1 = self._create_rigid_body(m)
     rb2 = self._create_rigid_body(m)
     r = IMP.core.PairRestraint(m, IMP.core.HarmonicDistancePairScore(0, 1),
                                (rb0, rb1))
     rs = IMP.RestraintSet(m)
     rs.add_restraint(r)
     dg = IMP.get_dependency_graph(m)
     # IMP.show_graphviz(dg)
     ig = IMP.domino.get_interaction_graph([rs], [rb0, rb1, rb2])
     # IMP.show_graphviz(ig)
     for v in ig.get_vertices():
         if ig.get_vertex_name(v) == rb0 or ig.get_vertex_name(v) == rb1:
             self.assertEqual(len(ig.get_out_neighbors(v)), 1)
             self.assertEqual(len(ig.get_in_neighbors(v)), 1)
         else:
             self.assertEqual(len(ig.get_out_neighbors(v)), 0)
             self.assertEqual(len(ig.get_in_neighbors(v)), 0)
Beispiel #24
0
 def test_decomposition_5(self):
     """Test cache with simple restraint"""
     (m, ps, r, pst, ik, cache) = self._create_stuff()
     rs = IMP.RestraintSet(m, 1.0, "outer")
     r = IMP._ConstRestraint(1, [ps[0]])
     r.set_name("const 2")
     rs.add_restraint(r)
     r.set_maximum_score(.5)
     cache.add_restraints([rs])
     print("info:")
     cache.show_restraint_information()
     subset = IMP.domino.Subset([ps[0]])
     rsb = cache.get_restraints(subset, [])
     self.assertEqual(len(rsb), 1)
     slc = cache.get_slice(rsb[0], subset)
     self.assertEqual(len(slc), 1)
     aslc = slc.get_sliced(IMP.domino.Assignment(range(len(ps))))
     self.assertEqual(len(aslc), 1)
     score = cache.get_score(rsb[0], aslc)
     print(score)
     self.assert_(score > 1000)
Beispiel #25
0
    def setUp(self):
        """set up distance restraints and create optimizer """
        IMP.test.TestCase.setUp(self)

        self.imp_model = IMP.Model()
        self.particles = []
        self.restraint_sets = []
        self.rsrs = []

        # create particles 0 - 1
        self.particles.append(self.create_point_particle(self.imp_model,
                                                         -43.0, 65.0, 93.0))
        self.particles.append(self.create_point_particle(self.imp_model,
                                                         20.0, 74.0, -80.0))
        self.particles.append(self.create_point_particle(self.imp_model,
                                                         4.0, -39.0, 26.0))
        p1 = self.particles[0]
        p1.add_attribute(radkey, 1.0, False)
        p1 = self.particles[1]
        p1.add_attribute(radkey, 2.0, False)
        p1 = self.particles[2]
        p1.add_attribute(radkey, 3.0, False)

        # separate 3 particles by their radii
        for pairs in ((0, 1), (1, 2), (0, 2)):
            p1 = self.particles[pairs[0]]
            p2 = self.particles[pairs[1]]
            mean = p1.get_value(radkey) + p2.get_value(radkey)
            sf = IMP.core.Harmonic(mean, 0.1)
            rsr = IMP.core.DistanceRestraint(self.imp_model, sf, p1, p2)
            self.rsrs.append(rsr)

        # add restraints
        rs = IMP.RestraintSet(self.imp_model, 1.0, "distance_rsrs")
        self.restraint_sets.append(rs)
        for i in range(len(self.rsrs)):
            rs.add_restraint(self.rsrs[i])

        self.steepest_descent = IMP.core.SteepestDescent(self.imp_model)
        self.steepest_descent.set_scoring_function([rs])
Beispiel #26
0
    def test_global_min3(self):
        """Test sampling with edge scores"""
        m = IMP.Model()
        m.set_log_level(IMP.SILENT)
        ps = []
        for i in range(0, 3):
            p = IMP.Particle(m)
            d = IMP.core.XYZ.setup_particle(p)
            ps.append(p)
        pts = [
            IMP.algebra.Vector3D(0, 0, 0),
            IMP.algebra.Vector3D(1, 0, 0),
            IMP.algebra.Vector3D(2, 0, 0),
            IMP.algebra.Vector3D(3, 0, 0)
        ]
        particle_state = IMP.domino.XYZStates(pts)
        pst = IMP.domino.ParticleStatesTable()
        r = IMP.RestraintSet(m)
        for p in ps:
            pst.set_particle_states(p, particle_state)
            r.add_restraint(IMP._ConstRestraint(1, [p]))
        r.add_restraint(
            IMP.core.DistanceRestraint(m, IMP.core.Harmonic(1, 1), ps[0],
                                       ps[1]))
        r.add_restraint(
            IMP.core.DistanceRestraint(m, IMP.core.Harmonic(1, 1), ps[1],
                                       ps[2]))

        r.set_maximum_score(3.1)
        sampler = IMP.domino.DominoSampler(m, pst)
        sampler.set_restraints([r])
        sampler.set_log_level(IMP.VERBOSE)
        cs = sampler.create_sample()
        self.assertGreater(cs.get_number_of_configurations(), 0)
        for i in range(0, cs.get_number_of_configurations()):
            cs.load_configuration(i)
            self.assertLess((IMP.core.get_distance(IMP.core.XYZ(
                ps[0]), IMP.core.XYZ(ps[1])) - 1)**2, .1)
            self.assertLess((IMP.core.get_distance(IMP.core.XYZ(
                ps[1]), IMP.core.XYZ(ps[2])) - 1)**2, .1)
Beispiel #27
0
 def test_global_min1(self):
     """Testing splitting restraints with rigid bodies"""
     m = IMP.Model()
     rbs = [
         self._create_rb("1", m),
         self._create_rb("2", m),
         self._create_rb("3", m)
     ]
     trs = [
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(0, 0,
                                                                   0))),
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(2, 0,
                                                                   0))),
         ReferenceFrame3D(
             Transformation3D(get_identity_rotation_3d(), Vector3D(4, 0,
                                                                   0)))
     ]
     ps = IMP.core.HarmonicSphereDistancePairScore(0, 1)
     members = IMP.get_indexes([x.get_rigid_members()[0] for x in rbs])
     pl = IMP.container.ListPairContainer(m, [(members[0], members[1]),
                                              (members[1], members[2])])
     r = IMP.container.PairsRestraint(ps, pl)
     r.set_name("restraint")
     rs = IMP.RestraintSet(m)
     rs.add_restraint(r)
     r.set_maximum_score(.5)
     pst = IMP.domino.ParticleStatesTable()
     pstate = IMP.domino.RigidBodyStates(trs)
     pst.set_particle_states(rbs[0], pstate)
     pst.set_particle_states(rbs[1], pstate)
     pst.set_particle_states(rbs[2], pstate)
     rc = IMP.domino.RestraintCache(pst)
     rc.add_restraints([rs])
     allr = rc.get_restraints()
     for r in allr:
         print(r.get_name())
     self.assertEqual(len(allr), 3)
Beispiel #28
0
    def __init__(self,
                 representation,
                 radius,
                 hierarchies=None,
                 resolution=None):
        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, 'barrier')

        self.radius = radius
        self.label = "None"

        c3 = IMP.algebra.Vector3D(0, 0, 0)
        ub3 = IMP.core.HarmonicUpperBound(radius, 10.0)
        ss3 = IMP.core.DistanceToSingletonScore(ub3, c3)
        lsc = IMP.container.ListSingletonContainer(self.m)
        # IMP.atom.get_by_type
        particles = IMP.pmi.tools.select(representation,
                                         resolution=resolution,
                                         hierarchies=hierarchies)
        lsc.add_particles(particles)
        r3 = IMP.container.SingletonsRestraint(ss3, lsc)
        self.rs.add_restraint(r3)
Beispiel #29
0
    def __init__(self,
                 representation,
                 images,
                 pixel_size,
                 image_resolution,
                 projection_number,
                 resolution=None):

        self.weight = 1.0
        self.m = representation.prot.get_model()
        self.rs = IMP.RestraintSet(self.m, 'em2d')
        self.label = "None"

        # IMP.atom.get_by_type
        particles = IMP.pmi.tools.select(representation, resolution=resolution)

        #print particles

        em2d = IMP.em2d.PCAFitRestraint(particles, images, pixel_size,
                                        image_resolution, projection_number,
                                        True)
        self.rs.add_restraint(em2d)
Beispiel #30
0
    def __init__(self, objects, distance=3.78, strength=10.0, jitter=None):
        """Constructor
        @param objects  Objects to restrain
        @param distance Resting distance for restraint
        @param strength Bond constant
        @param jitter Defines the +- added to the optimal distance in
               the harmonic well restraint used to increase the tolerance
        """

        particles = IMP.pmi.tools.input_adaptor(objects, 1, flatten=True)
        self.m = particles[0].get_model()

        self.rs = IMP.RestraintSet(self.m, "Bonds")
        self.weight = 1
        self.label = "None"
        self.pairslist = []

        if not jitter:
            ts = IMP.core.Harmonic(distance, strength)
        else:
            ts = IMP.core.HarmonicWell((distance - jitter, distance + jitter),
                                       strength)

        for ps in IMP.pmi.tools.sublist_iterator(particles, 2, 2):
            pair = []
            if len(ps) != 2:
                raise ValueError("wrong length of pair")
            for p in ps:
                if not IMP.atom.Residue.get_is_setup(p):
                    raise TypeError("%s is not a residue" % p)
                else:
                    pair.append(p)
            print("ResidueBondRestraint: adding a restraint between %s %s" %
                  (pair[0].get_name(), pair[1].get_name()))
            self.rs.add_restraint(
                IMP.core.DistanceRestraint(self.m, ts, pair[0], pair[1]))
            self.pairslist.append(IMP.ParticlePair(pair[0], pair[1]))
            self.pairslist.append(IMP.ParticlePair(pair[1], pair[0]))