From 4adce5321abf5744a2c764320d964c251e76538d Mon Sep 17 00:00:00 2001 From: Seth Axen Date: Mon, 25 Jun 2018 14:18:00 -0700 Subject: [PATCH] Conform model attribute to developer guide Relates #163 --- pyext/src/dof/__init__.py | 31 +++--- pyext/src/io/__init__.py | 26 +++-- pyext/src/io/crosslink.py | 4 +- pyext/src/io/xltable.py | 11 +- pyext/src/macros.py | 30 ++++-- pyext/src/mmcif.py | 2 +- pyext/src/plotting/topology.py | 13 ++- pyext/src/representation.py | 119 +++++++++++---------- pyext/src/restraints/stereochemistry.py | 4 +- pyext/src/samplers.py | 78 +++++++++----- pyext/src/topology/__init__.py | 57 ++++++---- pyext/src/topology/system_tools.py | 42 ++++---- test/expensive_test_input.py | 8 +- test/medium_test_topology.py | 86 +++++++-------- test/test_GaussianEMRestraint_rigidbody.py | 6 +- 15 files changed, 302 insertions(+), 215 deletions(-) diff --git a/pyext/src/dof/__init__.py b/pyext/src/dof/__init__.py index 6d342d41..aec79200 100644 --- a/pyext/src/dof/__init__.py +++ b/pyext/src/dof/__init__.py @@ -37,8 +37,8 @@ class DegreesOfFreedom(object): Call the various create() functions to get started. Can get all enabled movers with get_movers(). Pass this to ReplicaExchange0. """ - def __init__(self,mdl): - self.mdl = mdl + def __init__(self,model): + self.model = model self.movers = [] self.fb_movers = [] #stores movers corresponding to floppy parts self.rigid_bodies = [] #stores rigid body objects @@ -55,6 +55,11 @@ def __init__(self,mdl): # internal mover = [mover obj, list of particles, enabled?] ? # mover map = {particles/rbs : movers} + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model + def create_rigid_body(self, rigid_parts, nonrigid_parts=None, @@ -335,15 +340,15 @@ def setup_md(self, vykey = IMP.FloatKey('vy') vzkey = IMP.FloatKey('vz') hiers = IMP.pmi.tools.input_adaptor(hspec,flatten=True) - mdl = hiers[0].get_model() + model = hiers[0].get_model() all_ps = [] for hl in hiers: for h in IMP.core.get_leaves(hl): p = h.get_particle() - IMP.core.XYZ(mdl,p.get_index()).set_coordinates_are_optimized(True) - mdl.add_attribute(vxkey,p.get_index(),0.0) - mdl.add_attribute(vykey,p.get_index(),0.0) - mdl.add_attribute(vzkey,p.get_index(),0.0) + IMP.core.XYZ(model,p.get_index()).set_coordinates_are_optimized(True) + model.add_attribute(vxkey,p.get_index(),0.0) + model.add_attribute(vykey,p.get_index(),0.0) + model.add_attribute(vzkey,p.get_index(),0.0) all_ps.append(p) return all_ps @@ -399,11 +404,11 @@ def constrain_symmetry(self, if type=="RIGID_BODY": - p=IMP.Particle(self.mdl) + p=IMP.Particle(self.model) p.set_name("RigidBody_Symmetry") rb=IMP.core.RigidBody.setup_particle(p,IMP.algebra.ReferenceFrame3D(transform)) for cp in [(10,0,0),(0,10,0),(0,0,10)]: - p=IMP.Particle(self.mdl) + p=IMP.Particle(self.model) IMP.core.XYZ.setup_particle(p,cp) rb.add_member(p) sm = IMP.core.TransformationSymmetry(rb.get_particle_index()) @@ -428,9 +433,9 @@ def constrain_symmetry(self, #self._rb2mov[rb] = [rb_mover_tr] #dictionary relating rb to movers lsc = IMP.container.ListSingletonContainer( - self.mdl,[p.get_particle().get_index() for p in clones_rbs+clones_beads]) + self.model,[p.get_particle().get_index() for p in clones_rbs+clones_beads]) c = IMP.container.SingletonsConstraint(sm, None, lsc) - self.mdl.add_score_state(c) + self.model.add_score_state(c) print('Created symmetry restraint for',len(ref_rbs),'rigid bodies and', len(ref_beads),'flexible beads') @@ -439,7 +444,7 @@ def constrain_symmetry(self, #sym_movers = [m for cl in clones_rbs for m in self._rb2mov[cl]] #self.movers = [m for m in self.movers if m not in sym_movers] - self.mdl.update() + self.model.update() def __repr__(self): @@ -459,7 +464,7 @@ def optimize_flexible_beads(self, nsteps, temperature=1.0): for n, fb in enumerate(self.get_flexible_beads()): pts.add_particle(fb, "Floppy_Bodies", 1.0, "Flexible_Bead_" + str(n)) if len(pts.get_particles_to_sample()) > 0: - mc = IMP.pmi.samplers.MonteCarlo(self.mdl, [pts], temperature) + mc = IMP.pmi.samplers.MonteCarlo(self.model, [pts], temperature) print("optimize_flexible_beads: optimizing %i flexible beads" % len(self.get_flexible_beads())) mc.optimize(nsteps) else: diff --git a/pyext/src/io/__init__.py b/pyext/src/io/__init__.py index 8bb23d3d..f2cd8fe8 100644 --- a/pyext/src/io/__init__.py +++ b/pyext/src/io/__init__.py @@ -129,7 +129,7 @@ def convert_chain(ch): sses['beta'].append(beta_dict[beta_sheet]) return sses -def save_best_models(mdl, +def save_best_models(model, out_dir, stat_files, number_of_best_scoring_models=10, @@ -141,7 +141,7 @@ def save_best_models(mdl, override_rmf_dir=None): """Given a list of stat files, read them all and find the best models. Save to a single RMF along with a stat file. - @param mdl The IMP Model + @param model The IMP Model @param out_dir The output directory. Will save 3 files (RMF, stat, summary) @param stat_files List of all stat files to collect @param number_of_best_scoring_models Num best models to gather @@ -227,7 +227,7 @@ def save_best_models(mdl, stat = open(out_stat_fn,'w') rh0 = RMF.open_rmf_file_read_only( os.path.join(root_directory_of_stat_file,all_fields[rmf_file_key][0])) - prots = IMP.rmf.create_hierarchies(rh0,mdl) + prots = IMP.rmf.create_hierarchies(rh0,model) del rh0 outf = RMF.create_rmf_file(out_rmf_fn) IMP.rmf.add_hierarchies(outf,prots) @@ -574,13 +574,19 @@ def get_bead_sizes(model,rmf_tuple,rmsd_calculation_components=None,state_number class RMSDOutput(object): """A helper output based on dist to initial coordinates""" def __init__(self,ps,label,init_coords=None): - self.mdl = ps[0].get_model() + self.model = ps[0].get_model() self.ps = ps if init_coords is None: self.init_coords = [IMP.core.XYZ(p).get_coordinates() for p in self.ps] else: self.init_coords = init_coords self.label = label + + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model + def get_output(self): output = {} coords = [IMP.core.XYZ(p).get_coordinates() for p in self.ps] @@ -590,9 +596,15 @@ def get_output(self): class TotalScoreOutput(object): """A helper output for model evaluation""" - def __init__(self,mdl): - self.mdl = mdl - self.rs = IMP.pmi.tools.get_restraint_set(self.mdl) + def __init__(self,model): + self.model = model + self.rs = IMP.pmi.tools.get_restraint_set(self.model) + + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model + def get_output(self): score = self.rs.evaluate(False) output = {} diff --git a/pyext/src/io/crosslink.py b/pyext/src/io/crosslink.py index 0575ea83..17343438 100644 --- a/pyext/src/io/crosslink.py +++ b/pyext/src/io/crosslink.py @@ -1519,11 +1519,11 @@ def __init__(self,representation=None, #PMI 1.0 mode self.mode="pmi1" self.representation=representation - self.model=self.representation.m + self.model=self.representation.model elif system is not None: #PMI 2.0 mode self.system=system - self.model=self.system.mdl + self.model=self.system.model self.mode="pmi2" else: print("Argument error: please provide either a representation object or a IMP.Hierarchy") diff --git a/pyext/src/io/xltable.py b/pyext/src/io/xltable.py index 31e04fae..9a07bc80 100644 --- a/pyext/src/io/xltable.py +++ b/pyext/src/io/xltable.py @@ -50,7 +50,12 @@ def __init__(self,contact_threshold): self._first = True self.index_dict={} self.stored_dists={} - self.mdl = IMP.Model() + self.model = IMP.Model() + + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model def _colormap_distance(self, dist, threshold=35, tolerance=0): if dist < threshold - tolerance: @@ -160,7 +165,7 @@ def load_pdb_coordinates(self,pdbfile,chain_to_name_map): Key: PDB chain ID. Value: Protein name (set in sequence reading) \note This function returns an error if the sequence for each chain has NOT been read """ - mh = IMP.atom.read_pdb(pdbfile,self.mdl,IMP.atom.CAlphaPDBSelector()) + mh = IMP.atom.read_pdb(pdbfile,self.model,IMP.atom.CAlphaPDBSelector()) total_len = sum(len(self.sequence_dict[s]) for s in self.sequence_dict) coords = np.ones((total_len,3)) * 1e5 #default to coords "very far away" prev_stop = 0 @@ -248,7 +253,7 @@ def load_rmf_coordinates(self,rmf_name,rmf_frame_index, chain_names, nomap=False def _get_rmf_structure(self,rmf_name,rmf_frame_index): rh= RMF.open_rmf_file_read_only(rmf_name) - prots=IMP.rmf.create_hierarchies(rh, self.mdl) + prots=IMP.rmf.create_hierarchies(rh, self.model) IMP.rmf.load_frame(rh, rmf_frame_index) print("getting coordinates for frame %i rmf file %s" % (rmf_frame_index, rmf_name)) del rh diff --git a/pyext/src/macros.py b/pyext/src/macros.py index ab5b3c31..f1cd82d9 100644 --- a/pyext/src/macros.py +++ b/pyext/src/macros.py @@ -576,10 +576,10 @@ class BuildSystem(object): as a dictionary with key = (molecule name), value = IMP.pmi.topology.Molecule Quick multi-state system: @code{.python} - mdl = IMP.Model() + model = IMP.Model() reader1 = IMP.pmi.topology.TopologyReader(tfile1) reader2 = IMP.pmi.topology.TopologyReader(tfile2) - bs = IMP.pmi.macros.BuildSystem(mdl) + bs = IMP.pmi.macros.BuildSystem(model) bs.add_state(reader1) bs.add_state(reader2) bs.execute_macro() # build everything including degrees of freedom @@ -591,12 +591,12 @@ class BuildSystem(object): as requested. """ def __init__(self, - mdl, + model, sequence_connectivity_scale=4.0, force_create_gmm_files=False, resolutions=[1,10]): """Constructor - @param mdl An IMP Model + @param model An IMP Model @param sequence_connectivity_scale For scaling the connectivity restraint @param force_create_gmm_files If True, will sample and create GMMs no matter what. If False, will only sample if the @@ -604,14 +604,19 @@ def __init__(self, do anything. @param resolutions The resolutions to build for structured regions """ - self.mdl = mdl - self.system = IMP.pmi.topology.System(self.mdl) + self.model = model + self.system = IMP.pmi.topology.System(self.model) self._readers = [] # the TopologyReaders (one per state) self._domain_res = [] # TempResidues for each domain key=unique name, value=(atomic_res,non_atomic_res). self._domains = [] # key = domain unique name, value = Component self.force_create_gmm_files = force_create_gmm_files self.resolutions = resolutions + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model + def add_state(self, reader, keep_chain_id=False, fasta_name_map=None): @@ -741,7 +746,7 @@ def execute_macro(self, max_rb_trans=4.0, max_rb_rot=0.04, max_bead_trans=4.0, m self.root_hier = self.system.build() print("BuildSystem.execute_macro: setting up degrees of freedom") - self.dof = IMP.pmi.dof.DegreesOfFreedom(self.mdl) + self.dof = IMP.pmi.dof.DegreesOfFreedom(self.model) for nstate,reader in enumerate(self._readers): rbs = reader.get_rigid_bodies() srbs = reader.get_super_rigid_bodies() @@ -839,8 +844,8 @@ def __init__(self, files don't exist. If number of Gaussians is zero, won't do anything. """ - self.m = model - self.simo = IMP.pmi.representation.Representation(self.m, + self.model = model + self.simo = IMP.pmi.representation.Representation(self.model, upperharmonic=True, disorderedlength=False) @@ -939,6 +944,11 @@ def __init__(self, self.simo.set_floppy_bodies() self.simo.setup_bonds() + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model + def get_representation(self): '''Return the Representation object''' return self.simo @@ -1415,7 +1425,7 @@ def set_coordinates(self,hier_name,xyz_tuple): def save_rmf(self,rmfname): o=IMP.pmi.output.Output() - self.simo.m.update() + self.simo.model.update() o.init_rmf(rmfname,[self.simo.prot]) o.write_rmf(rmfname) o.close_rmf(rmfname) diff --git a/pyext/src/mmcif.py b/pyext/src/mmcif.py index 2ae61301..3c5305fb 100644 --- a/pyext/src/mmcif.py +++ b/pyext/src/mmcif.py @@ -161,7 +161,7 @@ def __init__(self, state, component, start, end, pdb_offset, self.state, self.chain, self.hier = state, chain, hier sel = IMP.atom.NonWaterNonHydrogenPDBSelector() \ & IMP.atom.ChainPDBSelector(chain) - self.starting_hier = IMP.atom.read_pdb(pdbname, state.m, sel) + self.starting_hier = IMP.atom.read_pdb(pdbname, state.model, sel) rigid = property(lambda self: _get_fragment_is_rigid(self), lambda self, val: None) diff --git a/pyext/src/plotting/topology.py b/pyext/src/plotting/topology.py index a9ba5650..1b12ca60 100644 --- a/pyext/src/plotting/topology.py +++ b/pyext/src/plotting/topology.py @@ -29,7 +29,7 @@ def __init__(self,model,selections,cutoff,frequency_cutoff, """ import itertools\ - self.mdl = model + self.model = model self.selections = selections self.contact_counts={} self.edges=defaultdict(int) @@ -47,17 +47,22 @@ def __init__(self,model,selections,cutoff,frequency_cutoff, self.quantitative_proteomic_data=quantitative_proteomic_data self.num_rmf=0 + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model + def add_rmf(self,rmf_fn,nframe): """Add selections from an RMF file""" print('reading from RMF file',rmf_fn) rh = RMF.open_rmf_file_read_only(rmf_fn) - prots = IMP.rmf.create_hierarchies(rh, self.mdl) + prots = IMP.rmf.create_hierarchies(rh, self.model) hier = prots[0] IMP.rmf.load_frame(rh, RMF.FrameID(0)) ps_per_component=defaultdict(list) if self.num_rmf==0: self.size_per_component=defaultdict(int) - self.mdl.update() + self.model.update() #gathers particles for all components part_dict = IMP.pmi.analysis.get_particles_at_resolution_one(hier) @@ -81,7 +86,7 @@ def add_rmf(self,rmf_fn,nframe): for n1,name1 in enumerate(self.names): for name2 in self.names[n1+1:]: - ncontacts = len(self.gcpf.get_close_pairs(self.mdl, + ncontacts = len(self.gcpf.get_close_pairs(self.model, ps_per_component[name1], ps_per_component[name2])) if ncontacts>0: diff --git a/pyext/src/representation.py b/pyext/src/representation.py index 66d37348..fc30ea73 100644 --- a/pyext/src/representation.py +++ b/pyext/src/representation.py @@ -82,9 +82,9 @@ class Representation(object): ''' - def __init__(self, m, upperharmonic=True, disorderedlength=True): + def __init__(self, model, upperharmonic=True, disorderedlength=True): """Constructor. - @param m the model + @param model the model @param upperharmonic This flag uses either harmonic (False) or upperharmonic (True) in the intra-pair connectivity restraint. @@ -134,12 +134,12 @@ def __init__(self, m, upperharmonic=True, disorderedlength=True): self.resolution = 10.0 self.bblenght = 100.0 self.kappa = 100.0 - self.m = m + self.model = model self.representation_is_modified = False self.unmodeledregions_cr_dict = {} self.sortedsegments_cr_dict = {} - self.prot = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.m)) + self.prot = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.model)) self.connected_intra_pairs = [] self.hier_dict = {} self.color_dict = {} @@ -156,7 +156,7 @@ def __init__(self, m, upperharmonic=True, disorderedlength=True): # structures that are used to calculate the rmsd self.reference_structures = {} self.elements = {} - self.linker_restraints = IMP.RestraintSet(self.m, "linker_restraints") + self.linker_restraints = IMP.RestraintSet(self.model, "linker_restraints") self.linker_restraints.set_was_used(True) self.linker_restraints_dict = {} self.threetoone = {'ALA': 'A', 'ARG': 'R', 'ASN': 'N', 'ASP': 'D', @@ -169,6 +169,11 @@ def __init__(self, m, upperharmonic=True, disorderedlength=True): self.residuenamekey = IMP.StringKey("ResidueName") + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model + def add_metadata(self, m): """Associate some metadata with this modeling. @param m an instance of IMP.pmi.metadata.Metadata or a subclass. @@ -202,7 +207,7 @@ def add_protocol_output(self, p): self._protocol_output.append((p, state)) p._each_metadata.append(self._metadata) p._file_datasets.append(self._file_dataset) - state.m = self.m + state.model = self.model state.prot = self.prot protocol_output = property(lambda self: [x[0] for x in self._protocol_output]) @@ -215,7 +220,7 @@ def create_component(self, name, color=0.0): # This is because old PMI1 code expects the top-level particle to be # a Molecule, but we also need it to be a Chain to set the sequence. # This looks a little odd but is a valid IMP atom::Hierarchy. - protein_h = IMP.atom.Chain.setup_particle(IMP.Particle(self.m), 'X') + protein_h = IMP.atom.Chain.setup_particle(IMP.Particle(self.model), 'X') IMP.atom.Molecule.setup_particle(protein_h) protein_h.set_name(name) self.hier_dict[name] = protein_h @@ -308,7 +313,7 @@ def autobuild_model(self, name, pdbname, chain, print("autobuild_model: constructing %s from pdb %s and chain %s" % (name, pdbname, str(chain))) # get the initial and end residues of the pdb - t = IMP.atom.read_pdb(pdbname, self.m, + t = IMP.atom.read_pdb(pdbname, self.model, IMP.atom.AndPDBSelector(IMP.atom.ChainPDBSelector(chain), IMP.atom.CAlphaPDBSelector())) # find start and end indexes @@ -438,7 +443,7 @@ def add_component_pdb(self, name, pdbname, chain, resolutions, color=None, sel = IMP.atom.AndPDBSelector( IMP.atom.ChainPDBSelector(chain), sel) - t = IMP.atom.read_pdb(pdbname, self.m, sel) + t = IMP.atom.read_pdb(pdbname, self.model, sel) # get the first and last residue start = IMP.atom.Residue( @@ -447,7 +452,7 @@ def add_component_pdb(self, name, pdbname, chain, resolutions, color=None, t.get_children()[0].get_children()[-1]).get_index() c = IMP.atom.Chain(IMP.atom.get_by_type(t, IMP.atom.CHAIN_TYPE)[0]) else: - t = IMP.atom.read_pdb(pdbname, self.m, sel) + t = IMP.atom.read_pdb(pdbname, self.model, sel) c = IMP.atom.Chain( IMP.atom.get_by_type(t, IMP.atom.CHAIN_TYPE)[chain]) @@ -485,7 +490,7 @@ def add_component_pdb(self, name, pdbname, chain, resolutions, color=None, if len(ps) == 0: raise ValueError("%s no residue found in pdb %s chain %s that overlaps with the queried stretch %s-%s" \ % (name, pdbname, str(chain), str(resrange[0]), str(resrange[1]))) - c0 = IMP.atom.Chain.setup_particle(IMP.Particle(self.m), "X") + c0 = IMP.atom.Chain.setup_particle(IMP.Particle(self.model), "X") for p in ps: par = IMP.atom.Atom(p).get_parent() @@ -522,7 +527,7 @@ def add_component_pdb(self, name, pdbname, chain, resolutions, color=None, residues[par] = None for r in residues.keys(): IMP.atom.destroy(r) - self.m.remove_particle(c0) + self.model.remove_particle(c0) IMP.atom.destroy(t) @@ -556,7 +561,7 @@ def add_component_ideal_helix( start = resrange[0] end = resrange[1] self.elements[name].append((start, end, " ", "helix")) - c0 = IMP.atom.Chain.setup_particle(IMP.Particle(self.m), "X") + c0 = IMP.atom.Chain.setup_particle(IMP.Particle(self.model), "X") for n, res in enumerate(range(start, end + 1)): if name in self.sequence_dict: try: @@ -578,8 +583,8 @@ def add_component_ideal_helix( # mass=IMP.atom.get_mass_from_residue_type(IMP.atom.ResidueType("ALA")) radius = IMP.algebra.get_ball_radius_from_volume_3d(vol) - r = IMP.atom.Residue.setup_particle(IMP.Particle(self.m), rt, res) - p = IMP.Particle(self.m) + r = IMP.atom.Residue.setup_particle(IMP.Particle(self.model), rt, res) + p = IMP.Particle(self.model) d = IMP.core.XYZR.setup_particle(p) x = 2.3 * cos(n * 2 * pi / 3.6) y = 2.3 * sin(n * 2 * pi / 3.6) @@ -622,7 +627,7 @@ def add_component_beads(self, name, ds, colors=None, incoord=None): for n, dss in enumerate(ds): ds_frag = (dss[0], dss[1]) self.elements[name].append((dss[0], dss[1], " ", "bead")) - prt = IMP.Particle(self.m) + prt = IMP.Particle(self.model) if ds_frag[0] == ds_frag[1]: # if the bead represent a single residue if name in self.sequence_dict: @@ -645,7 +650,7 @@ def add_component_beads(self, name, ds, colors=None, incoord=None): h.set_residue_indexes(list(range(ds_frag[0], ds_frag[1] + 1))) resolution = len(h.get_residue_indexes()) if "Beads" not in self.hier_representation[name]: - root = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.m)) + root = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.model)) root.set_name("Beads") self.hier_representation[name]["Beads"] = root protein_h.add_child(root) @@ -764,7 +769,7 @@ def add_component_density( out_hier = [] protein_h = self.hier_dict[name] if "Densities" not in self.hier_representation[name]: - root = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.m)) + root = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.model)) root.set_name("Densities") self.hier_representation[name]["Densities"] = root protein_h.add_child(root) @@ -789,10 +794,10 @@ def add_component_density( if inputfile: IMP.isd.gmm_tools.decorate_gmm_from_text( inputfile, density_particles, - self.m, transform) + self.model, transform) elif density_ps_to_copy: for ip in density_ps_to_copy: - p = IMP.Particle(self.m) + p = IMP.Particle(self.model) shape = IMP.core.Gaussian(ip).get_gaussian() mass = IMP.atom.Mass(ip).get_mass() IMP.core.Gaussian.setup_particle(p, shape) @@ -803,11 +808,11 @@ def add_component_density( print("add_component_density: no particle was selected") return out_hier for p in fragment_particles: - if not (IMP.atom.Fragment.get_is_setup(self.m,p.get_particle_index()) and - IMP.core.XYZ.get_is_setup(self.m,p.get_particle_index())): + if not (IMP.atom.Fragment.get_is_setup(self.model,p.get_particle_index()) and + IMP.core.XYZ.get_is_setup(self.model,p.get_particle_index())): raise Exception("The particles you selected must be Fragments and XYZs") - nres=len(IMP.atom.Fragment(self.m,p.get_particle_index()).get_residue_indexes()) - pos=IMP.core.XYZ(self.m,p.get_particle_index()).get_coordinates() + nres=len(IMP.atom.Fragment(self.model,p.get_particle_index()).get_residue_indexes()) + pos=IMP.core.XYZ(self.model,p.get_particle_index()).get_coordinates() density_particles=[] try: IMP.isd.get_data_path("beads/bead_%i.txt"%nres) @@ -816,7 +821,7 @@ def add_component_density( transform = IMP.algebra.Transformation3D(pos) IMP.isd.gmm_tools.decorate_gmm_from_text( IMP.isd.get_data_path("beads/bead_%i.txt"%nres), density_particles, - self.m, transform) + self.model, transform) else: #compute the gaussians here if len(fragment_particles) == 0: @@ -824,7 +829,7 @@ def add_component_density( return out_hier density_particles = IMP.isd.gmm_tools.sample_and_fit_to_particles( - self.m, + self.model, fragment_particles, num_components, sampled_points, @@ -837,7 +842,7 @@ def add_component_density( outputfile) # prepare output hierarchy - s0 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.m)) + s0 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.model)) s0.set_name(out_hier_name) self.hier_representation[name]["Densities"].add_child(s0) out_hier.append(s0) @@ -983,10 +988,10 @@ def dump_particle_descriptors(self): "COORDINATES_NONRIGID_MEMBER":{}, "COORDINATES_RIGID_MEMBER":{}} for mi in rb.get_member_indexes(): - rm=self.m.get_particle(mi) + rm=self.model.get_particle(mi) if IMP.core.NonRigidMember.get_is_setup(rm): name_part=rm.get_name() - xyz=[self.m.get_attribute(fk, rm) for fk in [IMP.FloatKey(4), IMP.FloatKey(5), IMP.FloatKey(6)]] + xyz=[self.model.get_attribute(fk, rm) for fk in [IMP.FloatKey(4), IMP.FloatKey(5), IMP.FloatKey(6)]] rigid_body_attributes[name]["COORDINATES_NONRIGID_MEMBER"][name_part]=numpy.array(xyz) else: name_part=rm.get_name() @@ -1045,12 +1050,12 @@ def load_particle_descriptors(self): coor_rm_model=[] coor_rm_ref=[] for mi in rb.get_member_indexes(): - rm=self.m.get_particle(mi) + rm=self.model.get_particle(mi) if IMP.core.NonRigidMember.get_is_setup(rm): name_part=rm.get_name() xyz=coor_nrm_ref[name_part] for n,fk in enumerate([IMP.FloatKey(4), IMP.FloatKey(5), IMP.FloatKey(6)]): - self.m.set_attribute(fk, rm,xyz[n]) + self.model.set_attribute(fk, rm,xyz[n]) else: name_part=rm.get_name() coor_rm_ref.append(IMP.algebra.Vector3D(coor_rm_ref_dict[name_part])) @@ -1059,7 +1064,7 @@ def load_particle_descriptors(self): t=IMP.algebra.get_transformation_aligning_first_to_second(coor_rm_model,coor_rm_ref) IMP.core.transform(rb,t) - IMP.isd.gmm_tools.decorate_gmm_from_text("model_gmm.txt",gaussians,self.m) + IMP.isd.gmm_tools.decorate_gmm_from_text("model_gmm.txt",gaussians,self.model) def _compare_rmf_repr_names(self, rmfname, reprname, component_name): """Print a warning if particle names in RMF and model don't match""" @@ -1225,7 +1230,7 @@ def check_root(self, name, protein_h, resolution): If the root hierarchy does not exist, construct it. ''' if "Res:" + str(int(resolution)) not in self.hier_representation[name]: - root = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.m)) + root = IMP.atom.Hierarchy.setup_particle(IMP.Particle(self.model)) root.set_name(name + "_Res:" + str(int(resolution))) self.hier_representation[name][ "Res:" + str(int(resolution))] = root @@ -1249,14 +1254,14 @@ def coarse_hierarchy(self, name, start, end, resolutions, isnucleicacid, if 1 in resolutions: self.check_root(name, protein_h, 1) - s1 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.m)) + s1 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.model)) s1.set_name('%s_%i-%i_%s' % (name, start, end, type)) # s1.set_residue_indexes(range(start,end+1)) self.hier_representation[name]["Res:1"].add_child(s1) outhiers += [s1] if 0 in resolutions: self.check_root(name, protein_h, 0) - s0 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.m)) + s0 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.model)) s0.set_name('%s_%i-%i_%s' % (name, start, end, type)) # s0.set_residue_indexes(range(start,end+1)) self.hier_representation[name]["Res:0"].add_child(s0) @@ -1333,7 +1338,7 @@ def coarse_hierarchy(self, name, start, end, resolutions, isnucleicacid, r) chil = s.get_children() - s0 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.m)) + s0 = IMP.atom.Fragment.setup_particle(IMP.Particle(self.model)) s0.set_name('%s_%i-%i_%s' % (name, start, end, type)) # Move all children from s to s0 for ch in chil: @@ -1488,10 +1493,10 @@ def shuffle_configuration( IMP.core.transform(rb, transformation) if avoidcollision: - self.m.update() + self.model.update() npairs = len( gcpf.get_close_pairs( - self.m, + self.model, otherparticleindexes, rbindexes)) if npairs == 0: @@ -1554,10 +1559,10 @@ def shuffle_configuration( IMP.core.transform(d, transformation) if (avoidcollision): - self.m.update() + self.model.update() npairs = len( gcpf.get_close_pairs( - self.m, + self.model, otherparticleindexes, fbindexes)) if npairs == 0: @@ -1629,8 +1634,8 @@ def setup_component_sequence_connectivity( ''' - unmodeledregions_cr = IMP.RestraintSet(self.m, "unmodeledregions") - sortedsegments_cr = IMP.RestraintSet(self.m, "sortedsegments") + unmodeledregions_cr = IMP.RestraintSet(self.model, "unmodeledregions") + sortedsegments_cr = IMP.RestraintSet(self.model, "sortedsegments") protein_h = self.hier_dict[name] SortedSegments = [] @@ -1686,7 +1691,7 @@ def setup_component_sequence_connectivity( pt0 = last.get_particle() pt1 = first.get_particle() - r = IMP.core.PairRestraint(self.m, dps, (pt0.get_index(), pt1.get_index())) + r = IMP.core.PairRestraint(self.model, dps, (pt0.get_index(), pt1.get_index())) print("Adding sequence connectivity restraint between", pt0.get_name(), " and ", pt1.get_name(), 'of distance', optdist) sortedsegments_cr.add_restraint(r) @@ -1697,7 +1702,7 @@ def setup_component_sequence_connectivity( self.linker_restraints.add_restraint(sortedsegments_cr) self.linker_restraints.add_restraint(unmodeledregions_cr) - IMP.pmi.tools.add_restraint_to_model(self.m, self.linker_restraints) + IMP.pmi.tools.add_restraint_to_model(self.model, self.linker_restraints) self.sortedsegments_cr_dict[name] = sortedsegments_cr self.unmodeledregions_cr_dict[name] = unmodeledregions_cr @@ -1707,7 +1712,7 @@ def optimize_floppy_bodies(self, nsteps, temperature=1.0): for n, fb in enumerate(self.floppy_bodies): pts.add_particle(fb, "Floppy_Bodies", 1.0, "Floppy_Body_" + str(n)) if len(pts.get_particles_to_sample()) > 0: - mc = IMP.pmi.samplers.MonteCarlo(self.m, [pts], temperature) + mc = IMP.pmi.samplers.MonteCarlo(self.model, [pts], temperature) print("optimize_floppy_bodies: optimizing %i floppy bodies" % len(self.floppy_bodies)) mc.optimize(nsteps) else: @@ -1739,7 +1744,7 @@ def create_rotational_symmetry(self, maincopy, copies, rotational_axis=IMP.algeb sm = IMP.core.TransformationSymmetry(rotation3D) clone_hiers = IMP.atom.get_leaves(self.hier_dict[copies[k]]) - lc = IMP.container.ListSingletonContainer(self.m) + lc = IMP.container.ListSingletonContainer(self.model) for n, p in enumerate(main_hiers): if (skip_gaussian_in_clones): if (IMP.core.Gaussian.get_is_setup(p)) and not (IMP.atom.Fragment.get_is_setup(p) or IMP.atom.Residue.get_is_setup(p)): @@ -1750,12 +1755,12 @@ def create_rotational_symmetry(self, maincopy, copies, rotational_axis=IMP.algeb lc.add(pc.get_particle().get_index()) c = IMP.container.SingletonsConstraint(sm, None, lc) - self.m.add_score_state(c) + self.model.add_score_state(c) print("Completed setting " + str(maincopy) + " as a reference for " + str(copies[k]) + " by rotating it by " + str(rotation_angle / 2.0 / pi * 360) + " degrees around the " + str(rotational_axis) + " axis.") - self.m.update() + self.model.update() def create_rigid_body_symmetry(self, particles_reference, particles_copy,label="None", initial_transformation=IMP.algebra.get_identity_transformation_3d()): @@ -1765,7 +1770,7 @@ def create_rigid_body_symmetry(self, particles_reference, particles_copy,label=" mainparticles = particles_reference t=initial_transformation - p=IMP.Particle(self.m) + p=IMP.Particle(self.model) p.set_name("RigidBody_Symmetry") rb=IMP.core.RigidBody.setup_particle(p,IMP.algebra.ReferenceFrame3D(t)) @@ -1792,7 +1797,7 @@ def create_rigid_body_symmetry(self, particles_reference, particles_copy,label=" else: IMP.pmi.Symmetric(pc).set_symmetric(1) - lc = IMP.container.ListSingletonContainer(self.m) + lc = IMP.container.ListSingletonContainer(self.model) for n, p in enumerate(mainpurged): pc = copypurged[n] @@ -1802,9 +1807,9 @@ def create_rigid_body_symmetry(self, particles_reference, particles_copy,label=" lc.add(pc.get_index()) c = IMP.container.SingletonsConstraint(sm, None, lc) - self.m.add_score_state(c) + self.model.add_score_state(c) - self.m.update() + self.model.update() self.rigid_bodies.append(rb) self.rigid_body_symmetries.append(rb) rb.set_name(label+".rigid_body_symmetry."+str(len(self.rigid_body_symmetries))) @@ -1838,7 +1843,7 @@ def create_amyloid_fibril_symmetry(self, maincopy, axial_copies, translation = IMP.algebra.Vector3D(translation_vector) sm = IMP.core.TransformationSymmetry( IMP.algebra.Transformation3D(rotation3D, translation)) - lc = IMP.container.ListSingletonContainer(self.m) + lc = IMP.container.ListSingletonContainer(self.model) for n, p in enumerate(mainparts): pc = copyparts[n] if not IMP.pmi.Symmetric.get_is_setup(p): @@ -1848,8 +1853,8 @@ def create_amyloid_fibril_symmetry(self, maincopy, axial_copies, IMP.core.Reference.setup_particle(pc, p) lc.add(pc.get_index()) c = IMP.container.SingletonsConstraint(sm, None, lc) - self.m.add_score_state(c) - self.m.update() + self.model.add_score_state(c) + self.model.update() return outhiers def link_components_to_rmf(self, rmfname, frameindex): @@ -1874,7 +1879,7 @@ def create_components_from_rmf(self, rmfname, frameindex): load the coordinates from the rmf file at frameindex. ''' rh = RMF.open_rmf_file_read_only(rmfname) - self.prot = IMP.rmf.create_hierarchies(rh, self.m)[0] + self.prot = IMP.rmf.create_hierarchies(rh, self.model)[0] IMP.atom.show_molecular_hierarchy(self.prot) IMP.rmf.link_hierarchies(rh, [self.prot]) IMP.rmf.load_frame(rh, RMF.FrameID(frameindex)) @@ -2469,7 +2474,7 @@ def set_output_level(self, level): def _evaluate(self, deriv): """Evaluate the total score of all added restraints""" - r = IMP.pmi.tools.get_restraint_set(self.m) + r = IMP.pmi.tools.get_restraint_set(self.model) return r.evaluate(deriv) def get_output(self): diff --git a/pyext/src/restraints/stereochemistry.py b/pyext/src/restraints/stereochemistry.py index cfee760a..402ffb70 100644 --- a/pyext/src/restraints/stereochemistry.py +++ b/pyext/src/restraints/stereochemistry.py @@ -218,7 +218,7 @@ def __init__(self, if bipartite: other_ps = [h.get_particle() for h in other_hierarchies] elif isinstance(representation, IMP.pmi.representation.Representation): - self.mdl = representation.m + self.mdl = representation.model included_ps = IMP.pmi.tools.select( representation, resolution=resolution, @@ -876,7 +876,7 @@ def __init__(self,representation=None, atom_type=IMP.atom.AtomType("CA")) particles+=sel.get_selected_particles() elif representation is not None and type(representation)==IMP.pmi.representation.Representation: - self.m = representation.mdl + self.m = representation.model for st in selection_tuples: print('selecting with',st) for p in IMP.pmi.tools.select_by_tuple(representation,st,resolution=resolution): diff --git a/pyext/src/samplers.py b/pyext/src/samplers.py index dc619892..f37ecbdd 100644 --- a/pyext/src/samplers.py +++ b/pyext/src/samplers.py @@ -43,9 +43,9 @@ class MonteCarlo(object): except ImportError: isd_available = False - def __init__(self, m, objects=None, temp=1.0, filterbyname=None): + def __init__(self, model, objects=None, temp=1.0, filterbyname=None): """Setup Monte Carlo sampling - @param m The IMP Model + @param model The IMP Model @param objects What to sample. Use flat list of particles or (deprecated) 'MC Sample Objects' from PMI1 @param temp The MC temperature @@ -66,7 +66,7 @@ def __init__(self, m, objects=None, temp=1.0, filterbyname=None): self.mvs = [] self.mvslabels = [] self.label = "None" - self.m = m + self.model = model self.movers_data={} # check if using PMI1 or just passed a list of movers @@ -142,12 +142,17 @@ def __init__(self, m, objects=None, temp=1.0, filterbyname=None): # SerialMover self.smv = IMP.core.SerialMover(self.mvs) - self.mc = IMP.core.MonteCarlo(self.m) - self.mc.set_scoring_function(get_restraint_set(self.m)) + self.mc = IMP.core.MonteCarlo(self.model) + self.mc.set_scoring_function(get_restraint_set(self.model)) self.mc.set_return_best(False) self.mc.set_kt(self.temp) self.mc.add_mover(self.smv) + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model + def set_kt(self, temp): self.temp = temp self.mc.set_kt(temp) @@ -156,7 +161,7 @@ def get_mc(self): return self.mc def set_scoring_function(self, objectlist): - rs = IMP.RestraintSet(self.m, 1.0, 'sfo') + rs = IMP.RestraintSet(self.model, 1.0, 'sfo') for ob in objectlist: rs.add_restraint(ob.get_restraint()) sf = IMP.core.RestraintsScoringFunction([rs]) @@ -276,14 +281,14 @@ def get_super_rigid_body_movers(self, rbs, maxtrans, maxrot): for rb in rbs: if len(rb) == 2: # normal Super Rigid Body - srbm = IMP.pmi.TransformMover(self.m, maxtrans, maxrot) + srbm = IMP.pmi.TransformMover(self.model, maxtrans, maxrot) elif len(rb) == 3: if type(rb[2]) == tuple and type(rb[2][0]) == float \ and type(rb[2][1]) == float and type(rb[2][2]) == float \ and len(rb[2])== 3: # super rigid body with 2D rotation, rb[2] is the axis srbm = IMP.pmi.TransformMover( - self.m, + self.model, IMP.algebra.Vector3D(rb[2]), maxtrans, maxrot) @@ -292,7 +297,7 @@ def get_super_rigid_body_movers(self, rbs, maxtrans, maxrot): # # super rigid body with bond rotation # srbm = IMP.pmi.TransformMover( - # self.m, + # self.model, # rb[2][0],rb[2][1], # 0, #no translation # maxrot) @@ -392,15 +397,15 @@ def get_output(self): class MolecularDynamics(object): """Sample using molecular dynamics""" - def __init__(self,m,objects,kt,gamma=0.01,maximum_time_step=1.0,sf=None): + def __init__(self,model,objects,kt,gamma=0.01,maximum_time_step=1.0,sf=None): """Setup MD - @param m The IMP Model + @param model The IMP Model @param objects What to sample. Use flat list of particles or (deprecated) 'MD Sample Objects' from PMI1 @param kt Temperature @param gamma Viscosity parameter @param maximum_time_step MD max time step """ - self.m=m + self.model=model # check if using PMI1 objects dictionary, or just list of particles try: @@ -409,18 +414,24 @@ def __init__(self,m,objects,kt,gamma=0.01,maximum_time_step=1.0,sf=None): except: to_sample = objects - self.ltstate=IMP.atom.LangevinThermostatOptimizerState(self.m,to_sample, + self.ltstate=IMP.atom.LangevinThermostatOptimizerState(self.model,to_sample, kt/0.0019872041, gamma) - self.md = IMP.atom.MolecularDynamics(self.m) + self.md = IMP.atom.MolecularDynamics(self.model) self.md.set_maximum_time_step(maximum_time_step) if sf: self.md.set_scoring_function(sf) else: - self.md.set_scoring_function(get_restraint_set(self.m)) + self.md.set_scoring_function(get_restraint_set(self.model)) self.md.add_optimizer_state(self.ltstate) self.simulated_annealing = False self.nframe = -1 + + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model + def set_kt(self,kt): temp=kt/0.0019872041 self.ltstate.set_temperature(temp) @@ -461,11 +472,16 @@ def get_output(self): class ConjugateGradients(object): """Sample using conjugate gradients""" - def __init__(self, m, objects): - self.m = m + def __init__(self, model, objects): + self.model = model self.nframe = -1 - self.cg = IMP.core.ConjugateGradients(self.m) - self.cg.set_scoring_function(get_restraint_set(self.m)) + self.cg = IMP.core.ConjugateGradients(self.model) + self.cg.set_scoring_function(get_restraint_set(self.model)) + + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model def set_label(self, label): self.label = label @@ -482,7 +498,7 @@ def optimize(self, nstep): self.cg.optimize(nstep) def set_scoring_function(self, objectlist): - rs = IMP.RestraintSet(self.m, 1.0, 'sfo') + rs = IMP.RestraintSet(self.model, 1.0, 'sfo') for ob in objectlist: rs.add_restraint(ob.get_restraint()) sf = IMP.core.RestraintsScoringFunction([rs]) @@ -515,7 +531,7 @@ def __init__( ''' - self.m = model + self.model = model self.samplerobjects = samplerobjects # min and max temperature self.TEMPMIN_ = tempmin @@ -559,6 +575,11 @@ def __init__( self.nmaxtemp = 0 self.nsuccess = 0 + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model + def get_temperatures(self): return self.temperatures @@ -570,7 +591,7 @@ def get_my_index(self): def swap_temp(self, nframe, score=None): if score is None: - score = self.m.evaluate(False) + score = self.model.evaluate(False) # get my replica index and temperature myindex = self.rem.get_my_index() mytemp = self.rem.get_my_parameter("temp")[0] @@ -702,11 +723,16 @@ def __init__(self, model): from math import exp import random - self.m = model + self.model = model self.restraints = None self.first_call = True self.nframe = -1 + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model + def add_mover(self, mv): self.mv = mv @@ -723,13 +749,13 @@ def get_energy(self): if self.restraints: pot = sum([r.evaluate(False) for r in self.restraints]) else: - pot = self.m.evaluate(False) + pot = self.model.evaluate(False) return pot def metropolis(self, old, new): deltaE = new - old print(": old %f new %f deltaE %f new_epot: %f" % (old, new, deltaE, - self.m.evaluate( + self.model.evaluate( False)), end=' ') kT = self.kT if deltaE < 0: @@ -771,7 +797,7 @@ def set_restraints(self, restraints): def set_scoring_function(self, objects): # objects should be pmi.restraints - rs = IMP.RestraintSet(self.m, 1.0, 'sfo') + rs = IMP.RestraintSet(self.model, 1.0, 'sfo') for ob in objects: rs.add_restraint(ob.get_restraint()) self.set_restraints([rs]) diff --git a/pyext/src/topology/__init__.py b/pyext/src/topology/__init__.py index b6fbdd9f..3adb29d7 100644 --- a/pyext/src/topology/__init__.py +++ b/pyext/src/topology/__init__.py @@ -1,6 +1,6 @@ """@namespace IMP.pmi.topology Set of python classes to create a multi-state, multi-resolution IMP hierarchy. -* Start by creating a System with `mdl = IMP.Model(); s = IMP.pmi.topology.System(mdl)`. The System will store all the states. +* Start by creating a System with `model = IMP.Model(); s = IMP.pmi.topology.System(model)`. The System will store all the states. * Then call System.create_state(). You can easily create a multistate system by calling this function multiples times. * For each State, call State.create_molecule() to add a Molecule (a uniquely named polymer). This function returns the Molecule object which can be passed to various PMI functions. * Some useful functions to help you set up your Molecules: @@ -31,7 +31,7 @@ from math import pi,cos,sin from operator import itemgetter -def _build_ideal_helix(mdl, residues, coord_finder): +def _build_ideal_helix(model, residues, coord_finder): """Creates an ideal helix from the specified residue range Residues MUST be contiguous. This function actually adds them to the TempResidue hierarchy @@ -47,14 +47,14 @@ def _build_ideal_helix(mdl, residues, coord_finder): raise Exception("Passed non-contiguous segment to build_ideal_helix for",tempres.get_molecule()) # New residue particle will replace the TempResidue's existing (empty) hierarchy - rp = IMP.Particle(mdl) + rp = IMP.Particle(model) rp.set_name("Residue_%i" % tempres.get_index()) # Copy the original residue type and index this_res = IMP.atom.Residue.setup_particle(rp,tempres.get_hierarchy()) # Create the CAlpha - ap = IMP.Particle(mdl) + ap = IMP.Particle(model) d = IMP.core.XYZR.setup_particle(ap) x = 2.3 * cos(n * 2 * pi / 3.6) y = 2.3 * sin(n * 2 * pi / 3.6) @@ -76,15 +76,20 @@ class _SystemBase(object): classes. It contains shared functions in common to these classes """ - def __init__(self,mdl=None): - if mdl is None: - self.mdl=IMP.Model() + def __init__(self,model=None): + if model is None: + self.model=IMP.Model() else: - self.mdl=mdl + self.model=model + + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model def _create_hierarchy(self): """create a new hierarchy""" - tmp_part=IMP.Particle(self.mdl) + tmp_part=IMP.Particle(self.model) return IMP.atom.Hierarchy.setup_particle(tmp_part) def _create_child(self,parent_hierarchy): @@ -103,8 +108,8 @@ def build(self): class System(_SystemBase): """This class initializes the root node of the global IMP.atom.Hierarchy.""" - def __init__(self,mdl=None,name="System"): - _SystemBase.__init__(self,mdl) + def __init__(self,model=None,name="System"): + _SystemBase.__init__(self,model) self._number_of_states = 0 self._protocol_output = [] self.states = [] @@ -166,7 +171,7 @@ def __init__(self,system,state_index): \note It's expected that you will not use this constructor directly, but rather create it with pmi::System::create_state() """ - self.mdl = system.get_hierarchy().get_model() + self.model = system.get_hierarchy().get_model() self.system = system self.hier = self._create_child(system.get_hierarchy()) self.short_name = self.long_name = "State_"+str(state_index) @@ -178,13 +183,18 @@ def __init__(self,system,state_index): for p in system._protocol_output: self._add_protocol_output(p, system) + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model + def __repr__(self): return self.system.__repr__()+'.'+self.hier.get_name() def _add_protocol_output(self, p, system): state = p._add_state(self) self._protocol_output.append((p, state)) - state.m = system.mdl + state.model = system.model state.prot = self.hier def get_molecules(self): @@ -265,7 +275,7 @@ def __init__(self,state,name,sequence,chain_id,copy_num,mol_to_clone=None,is_nuc but rather create a Molecule with pmi::State::create_molecule() """ # internal data storage - self.mdl = state.get_hierarchy().get_model() + self.model = state.get_hierarchy().get_model() self.state = state self.sequence = sequence self.built = False @@ -289,6 +299,11 @@ def __init__(self,state,name,sequence,chain_id,copy_num,mol_to_clone=None,is_nuc r = TempResidue(self,s,ns+1,ns,is_nucleic) self.residues.append(r) + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def mdl(self): + return self.model + def __repr__(self): return self.state.__repr__()+'.'+self.get_name()+'.'+ \ str(IMP.atom.Copy(self.hier).get_copy_index()) @@ -399,7 +414,7 @@ def add_structure(self,pdb_fn,chain_id,res_range=[], self.pdb_fn = pdb_fn # get IMP.atom.Residues from the pdb file - rhs = system_tools.get_structure(self.mdl,pdb_fn,chain_id,res_range,offset,ca_only=ca_only) + rhs = system_tools.get_structure(self.model,pdb_fn,chain_id,res_range,offset,ca_only=ca_only) self.coord_finder.add_residues(rhs) if len(self.residues)==0: @@ -628,7 +643,7 @@ def build(self): # first build any ideal helices (fills in structure for the TempResidues) for rep in self.representations: if rep.ideal_helix: - _build_ideal_helix(self.mdl,rep.residues,self.coord_finder) + _build_ideal_helix(self.model,rep.residues,self.coord_finder) # build all the representations built_reps = [] @@ -805,7 +820,7 @@ def __init__(self,model,pdb_fn,name_map=None): @param pdb_fn file @param name_map dictionary mapping the pdb chain id to final stored name """ - self.m=model + self.model=model # self.sequences data-structure: (two-key dictionary) # it contains all contiguous fragments: # chain_id, tuples indicating first and last residue, sequence @@ -818,9 +833,13 @@ def __init__(self,model,pdb_fn,name_map=None): self.sequences = IMP.pmi.tools.OrderedDict() self.read_sequences(pdb_fn,name_map) + @property + @IMP.deprecated_method("3.0", "Model should be accessed with `.model`.") + def m(self): + return self.model def read_sequences(self,pdb_fn,name_map): - t = IMP.atom.read_pdb(pdb_fn, self.m, IMP.atom.ATOMPDBSelector()) + t = IMP.atom.read_pdb(pdb_fn, self.model, IMP.atom.ATOMPDBSelector()) cs=IMP.atom.get_by_type(t,IMP.atom.CHAIN_TYPE) for c in cs: id=IMP.atom.Chain(c).get_id() @@ -961,7 +980,7 @@ def __init__(self,molecule,code,index,internal_index,is_nucleic=None): self.state_index = IMP.atom.State(self.molecule.state.hier).get_state_index() #these are expected to change self._structured = False - self.hier = IMP.atom.Residue.setup_particle(IMP.Particle(molecule.mdl), + self.hier = IMP.atom.Residue.setup_particle(IMP.Particle(molecule.model), self.rtype, index) def __str__(self): diff --git a/pyext/src/topology/system_tools.py b/pyext/src/topology/system_tools.py index b3076d3e..661be198 100644 --- a/pyext/src/topology/system_tools.py +++ b/pyext/src/topology/system_tools.py @@ -29,9 +29,9 @@ def resnums2str(res): ret+=', ' return ret -def get_structure(mdl,pdb_fn,chain_id,res_range=None,offset=0,model_num=None,ca_only=False): +def get_structure(model,pdb_fn,chain_id,res_range=None,offset=0,model_num=None,ca_only=False): """read a structure from a PDB file and return a list of residues - @param mdl The IMP model + @param model The IMP model @param pdb_fn The file to read @param chain_id Chain ID to read @param res_range Add only a specific set of residues. @@ -46,11 +46,11 @@ def get_structure(mdl,pdb_fn,chain_id,res_range=None,offset=0,model_num=None,ca_ if ca_only: sel = IMP.atom.CAlphaPDBSelector() if model_num is None: - mh = IMP.atom.read_pdb(pdb_fn,mdl, + mh = IMP.atom.read_pdb(pdb_fn,model, IMP.atom.AndPDBSelector(IMP.atom.ChainPDBSelector(chain_id), sel)) else: - mhs = IMP.atom.read_multimodel_pdb(pdb_fn,mdl,sel) + mhs = IMP.atom.read_multimodel_pdb(pdb_fn,model,sel) if model_num>=len(mhs): raise Exception("you requested model num "+str(model_num)+\ " but the PDB file only contains "+str(len(mhs))+" models") @@ -83,11 +83,11 @@ def get_structure(mdl,pdb_fn,chain_id,res_range=None,offset=0,model_num=None,ca_ % (pdb_fn, res_range)) return ret -def build_bead(mdl,residues,input_coord=None): +def build_bead(model,residues,input_coord=None): """Generates a single bead""" ds_frag = (residues[0].get_index(), residues[-1].get_index()) - prt = IMP.Particle(mdl) + prt = IMP.Particle(model) IMP.core.XYZR.setup_particle(prt) ptem = IMP.core.XYZR(prt) mass = IMP.atom.get_mass_from_number_of_residues(len(residues)) @@ -121,19 +121,19 @@ def build_bead(mdl,residues,input_coord=None): pass return h -def build_necklace(mdl,residues, resolution, input_coord=None): +def build_necklace(model,residues, resolution, input_coord=None): """Generates a string of beads with given length""" out_hiers = [] for chunk in list(IMP.pmi.tools.list_chunks_iterator(residues, resolution)): - out_hiers.append(build_bead(mdl,chunk, input_coord=input_coord)) + out_hiers.append(build_bead(model,chunk, input_coord=input_coord)) return out_hiers -def build_ca_centers(mdl,residues): +def build_ca_centers(model,residues): """Create a bead on the CA position with coarsened size and mass""" out_hiers = [] for tempres in residues: residue = tempres.get_hierarchy() - rp1 = IMP.Particle(mdl) + rp1 = IMP.Particle(model) rp1.set_name("Residue_%i"%residue.get_index()) rt = residue.get_residue_type() this_res = IMP.atom.Residue.setup_particle(rp1,residue) @@ -200,7 +200,7 @@ def build_representation(parent,rep,coord_finder): built_reps = [] atomic_res = 0 ca_res = 1 - mdl = parent.get_model() + model = parent.get_model() if rep.color is not None: if type(rep.color) is float: color = IMP.display.get_rgb_color(rep.color) @@ -226,20 +226,20 @@ def build_representation(parent,rep,coord_finder): single_node = True num_components = len(rep.residues)//rep.density_residues_per_component+1 rep_dict = defaultdict(list) - segp = IMP.Particle(mdl) + segp = IMP.Particle(model) root_representation = IMP.atom.Representation.setup_particle(segp, primary_resolution) built_reps.append(root_representation) res_nums = [r.get_index() for r in rep.residues] IMP.atom.Fragment.setup_particle(segp,res_nums) - density_frag = IMP.atom.Fragment.setup_particle(IMP.Particle(mdl),res_nums) + density_frag = IMP.atom.Fragment.setup_particle(IMP.Particle(model),res_nums) density_frag.get_particle().set_name("Densities %i"%rep.density_residues_per_component) density_ps = [] if os.path.exists(rep.density_prefix+'.txt') and not rep.density_force_compute: IMP.isd.gmm_tools.decorate_gmm_from_text(rep.density_prefix+'.txt', density_ps, - mdl) + model) if len(density_ps)!=num_components or not os.path.exists(rep.density_prefix+'.txt') or rep.density_force_compute: fit_coords = [] total_mass = 0.0 @@ -252,7 +252,7 @@ def build_representation(parent,rep,coord_finder): density_ps = [] IMP.isd.gmm_tools.fit_gmm_to_points(fit_coords, num_components, - mdl, + model, density_ps, min_covar=4.0, mass_multiplier=total_mass) @@ -301,13 +301,13 @@ def build_representation(parent,rep,coord_finder): elif name_count==3: name_all +='...' name_count+=1 - segp = IMP.Particle(mdl,name) + segp = IMP.Particle(model,name) this_segment = IMP.atom.Fragment.setup_particle(segp,res_nums) if not single_node: this_representation = IMP.atom.Representation.setup_particle(segp,primary_resolution) built_reps.append(this_representation) for resolution in rep.bead_resolutions: - fp = IMP.Particle(mdl) + fp = IMP.Particle(model) this_resolution = IMP.atom.Fragment.setup_particle(fp,res_nums) this_resolution.set_name("%s: Res %i"%(name,resolution)) if frag_res[0].get_has_structure(): @@ -316,11 +316,11 @@ def build_representation(parent,rep,coord_finder): for residue in frag_res: this_resolution.add_child(residue.get_hierarchy()) elif resolution==ca_res and rep.bead_ca_centers: - beads = build_ca_centers(mdl,frag_res) + beads = build_ca_centers(model,frag_res) for bead in beads: this_resolution.add_child(bead) else: - tempc = IMP.atom.Chain.setup_particle(IMP.Particle(mdl),"X") + tempc = IMP.atom.Chain.setup_particle(IMP.Particle(model),"X") for residue in frag_res: tempc.add_child(IMP.atom.create_clone(residue.hier)) beads = IMP.atom.create_simplified_along_backbone(tempc,resolution) @@ -333,7 +333,7 @@ def build_representation(parent,rep,coord_finder): input_coord = coord_finder.find_nearest_coord(min(r.get_index() for r in frag_res)) if input_coord is None: input_coord = rep.bead_default_coord - beads = build_necklace(mdl, + beads = build_necklace(model, frag_res, resolution, input_coord) @@ -371,7 +371,7 @@ def build_representation(parent,rep,coord_finder): d[0].set_name('%s: '%name_all + d[0].get_name()) for resolution in rep.bead_resolutions: this_resolution = IMP.atom.Fragment.setup_particle( - IMP.Particle(mdl), + IMP.Particle(model), [r.get_index() for r in rep.residues]) this_resolution.set_name("%s: Res %i"%(name_all,resolution)) for hier in rep_dict[resolution]: diff --git a/test/expensive_test_input.py b/test/expensive_test_input.py index ddd4d6f5..a5a8fc3f 100644 --- a/test/expensive_test_input.py +++ b/test/expensive_test_input.py @@ -10,7 +10,7 @@ class Tests(IMP.test.TestCase): def setUp(self): IMP.test.TestCase.setUp(self) - self.mdl=IMP.Model() + self.model=IMP.Model() input_dir=os.path.dirname(self.get_input_file_name('chainA.pdb')) self.stat_files = [os.path.join(input_dir,'output','stat.2.out'), os.path.join(input_dir,'output','stat.3.out')] @@ -21,7 +21,7 @@ def setUp(self): def test_save_best_models(self): """Test function to collect top models into a single RMF file""" - IMP.pmi.io.save_best_models(self.mdl,'./',self.stat_files, + IMP.pmi.io.save_best_models(self.model,'./',self.stat_files, number_of_best_scoring_models=3, score_key=self.score_key, feature_keys=self.feature_keys) @@ -30,7 +30,7 @@ def test_save_best_models(self): self.assertEqual(len(fields[self.score_key]),3) self.assertEqual(float(fields[self.score_key][0]),301.048975729) rh = RMF.open_rmf_file_read_only('top_3.rmf3') - prots = IMP.rmf.create_hierarchies(rh,self.mdl) + prots = IMP.rmf.create_hierarchies(rh,self.model) # testing first coordinate of med2 for each frame check_coords=[(26.2109, 61.2197, -16.9102), @@ -74,7 +74,7 @@ def test_read_coordinates_of_rmfs(self): range(len(score_list)), range(len(score_list))) rmsdc={'med2':'med2'} - got_coords = IMP.pmi.io.read_coordinates_of_rmfs(self.mdl, + got_coords = IMP.pmi.io.read_coordinates_of_rmfs(self.model, rmf_tuples, alignment_components=None, rmsd_calculation_components=rmsdc) diff --git a/test/medium_test_topology.py b/test/medium_test_topology.py index 54fbe924..49fbca61 100644 --- a/test/medium_test_topology.py +++ b/test/medium_test_topology.py @@ -25,8 +25,8 @@ def get_atomic_residue_list(residues): class MultiscaleTopologyTest(IMP.test.TestCase): - def initialize_system(self, mdl): - s = IMP.pmi.topology.System(mdl) + def initialize_system(self, model): + s = IMP.pmi.topology.System(model) st1 = s.create_state() # Read sequences and create Molecules @@ -66,8 +66,8 @@ def test_molecule_set_behaviour2(self): the model build. The current behaviour does not make the test pass. ''' - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) st1 = s.create_state() # Read sequences and create Molecules @@ -133,8 +133,8 @@ def test_molecule_set_behaviour(self): the model build. The current behaviour does not make the test pass. ''' - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) st1 = s.create_state() # Read sequences and create Molecules @@ -207,8 +207,8 @@ def test_molecule_set_behaviour(self): def test_num_residues(self): """ Test different ways of accessing residues""" - mdl = IMP.Model() - (a1, hier, mol) = self.initialize_system(mdl) + model = IMP.Model() + (a1, hier, mol) = self.initialize_system(model) #print(a1, mol.get_atomic_residues()) self.assertEqual(37, len(a1)) # now these are duplicated @@ -225,8 +225,8 @@ def test_num_unstruct_res(self): except ImportError: self.skipTest("no sklearn package") - mdl = IMP.Model() - (a1, hier, mol) = self.initialize_system(mdl) + model = IMP.Model() + (a1, hier, mol) = self.initialize_system(model) struct_res = 0 unstruct_res = 0 @@ -250,8 +250,8 @@ def test_residue_print(self): except ImportError: self.skipTest("no sklearn package") - mdl = IMP.Model() - (a1, hier, mol) = self.initialize_system(mdl) + model = IMP.Model() + (a1, hier, mol) = self.initialize_system(model) res = mol.residues[0] try: print(res) @@ -269,9 +269,9 @@ def test_molecule_rigid_members(self): except ImportError: self.skipTest("no sklearn package") - mdl = IMP.Model() - (a1, hier, mol) = self.initialize_system(mdl) - dof = IMP.pmi.dof.DegreesOfFreedom(mdl) + model = IMP.Model() + (a1, hier, mol) = self.initialize_system(model) + dof = IMP.pmi.dof.DegreesOfFreedom(model) dof.create_rigid_body(mol, nonrigid_parts=mol.get_non_atomic_residues()) rb = IMP.core.RigidBodyMember( @@ -295,9 +295,9 @@ def test_molecule_rigid_members1(self): except ImportError: self.skipTest("no sklearn package") - mdl = IMP.Model() - (a1, hier, mol) = self.initialize_system(mdl) - dof = IMP.pmi.dof.DegreesOfFreedom(mdl) + model = IMP.Model() + (a1, hier, mol) = self.initialize_system(model) + dof = IMP.pmi.dof.DegreesOfFreedom(model) # Create rigid body dof.create_rigid_body(mol, @@ -328,9 +328,9 @@ def test_molecule_rigid_members2(self): except ImportError: self.skipTest("no sklearn package") - mdl = IMP.Model() - (a1, hier, mol) = self.initialize_system(mdl) - dof = IMP.pmi.dof.DegreesOfFreedom(mdl) + model = IMP.Model() + (a1, hier, mol) = self.initialize_system(model) + dof = IMP.pmi.dof.DegreesOfFreedom(model) # Create rigid body dof.create_rigid_body(mol) @@ -384,7 +384,7 @@ def test_create_states(self): st = s.create_state() self.assertEqual(st.get_hierarchy().get_parent(), s.get_hierarchy()) - self.assertEqual(st.mdl, s.mdl) + self.assertEqual(st.model, s.model) self.assertEqual(s.get_number_of_states(), 10) def test_create_molecules(self): @@ -402,8 +402,8 @@ def test_create_molecules(self): m2 = st.create_molecule("Prot2", sequence=seqs["Prot2"]) self.assertEqual(m1.get_hierarchy().get_parent(), st.get_hierarchy()) self.assertEqual(m2.get_hierarchy().get_parent(), st.get_hierarchy()) - self.assertEqual(m1.mdl, st.mdl) - self.assertEqual(m2.mdl, st.mdl) + self.assertEqual(m1.model, st.model) + self.assertEqual(m2.model, st.model) self.assertEqual(m1.get_name(), "Prot1") self.assertEqual(m2.get_name(), "Prot2") self.assertEqual(len(st.get_hierarchy().get_children()), 2) @@ -412,7 +412,7 @@ def test_create_molecules(self): st2 = s.create_state() m3 = st2.create_molecule("Prot3", sequence=seqs["Prot3"]) self.assertEqual(m3.get_hierarchy().get_parent(), st2.get_hierarchy()) - self.assertEqual(m3.mdl, st2.mdl) + self.assertEqual(m3.model, st2.model) self.assertEqual(m3.get_name(), "Prot3") self.assertEqual(len(st2.get_hierarchy().get_children()), 1) @@ -715,8 +715,8 @@ def get_color(p): return [int(c.get_red() * 255), int(c.get_green() * 255), int(c.get_blue() * 255)] base_res = 0 bead_res = 1 - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) st1 = s.create_state() seqs = IMP.pmi.topology.Sequences( self.get_input_file_name('seqs.fasta')) @@ -738,7 +738,7 @@ def get_color(p): del rh rh2 = RMF.open_rmf_file_read_only(fname) - h2 = IMP.rmf.create_hierarchies(rh2, mdl)[0] + h2 = IMP.rmf.create_hierarchies(rh2, model)[0] IMP.rmf.load_frame(rh2, 0) self.assertEqual(len(IMP.atom.get_leaves(orig_hier)), @@ -777,8 +777,8 @@ def test_setup_densities(self): except ImportError: self.skipTest("no sklearn package") - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) st1 = s.create_state() seqs = IMP.pmi.topology.Sequences( self.get_input_file_name('seqs.fasta')) @@ -804,8 +804,8 @@ def test_setup_beads_as_densities(self): """Test setup of individual density particles. This is mainly for flexible beads or all-atom simulations """ - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) st1 = s.create_state() seqs = IMP.pmi.topology.Sequences( self.get_input_file_name('seqs.fasta')) @@ -824,8 +824,8 @@ def test_setup_beads_as_densities(self): def test_no_sequence(self): """Test automatic poly-A sequence when you add structure""" - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) st1 = s.create_state() m1 = st1.create_molecule("Prot1") atomic_res = m1.add_structure(self.get_input_file_name('prot.pdb'), @@ -847,8 +847,8 @@ def test_ideal_helix(self): except ImportError: self.skipTest("no sklearn package") - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) st1 = s.create_state() m1 = st1.create_molecule("Prot1", sequence='A' *25) m1.add_representation(m1[0:20], @@ -872,8 +872,8 @@ def test_ideal_helix(self): def test_write_multistate(self): """Test you write multistate system with correct hierarchy""" - mdl = IMP.Model() - s = IMP.pmi.topology.System(mdl) + model = IMP.Model() + s = IMP.pmi.topology.System(model) seqs = IMP.pmi.topology.Sequences(self.get_input_file_name('seqs.fasta')) st1 = s.create_state() @@ -888,7 +888,7 @@ def test_write_multistate(self): m2.add_representation(atomic_res,resolutions=0) root_hier = s.build() - rex = IMP.pmi.macros.ReplicaExchange0(mdl, + rex = IMP.pmi.macros.ReplicaExchange0(model, root_hier=root_hier, number_of_frames=0, number_of_best_scoring_models=0, @@ -896,17 +896,17 @@ def test_write_multistate(self): rex.execute_macro() rh2 = RMF.open_rmf_file_read_only('multistate_test/initial.0.rmf3') - hs = IMP.rmf.create_hierarchies(rh2,mdl) + hs = IMP.rmf.create_hierarchies(rh2,model) self.assertEqual(len(hs),1) states = IMP.atom.get_by_type(hs[0],IMP.atom.STATE_TYPE) self.assertEqual(len(states),2) def test_pmi_molecule_hierarchy(self): - mdl=IMP.Model() + model=IMP.Model() seqs = IMP.pmi.topology.Sequences(self.get_input_file_name('seqs.fasta')) - state=IMP.atom.State.setup_particle(IMP.Particle(mdl),0) + state=IMP.atom.State.setup_particle(IMP.Particle(model),0) for seq in seqs: - mol=IMP.atom.Molecule.setup_particle(IMP.Particle(mdl)) + mol=IMP.atom.Molecule.setup_particle(IMP.Particle(model)) ch=IMP.atom.Chain.setup_particle(mol,"A") ch.set_sequence(seqs[seq]) state.add_child(mol) diff --git a/test/test_GaussianEMRestraint_rigidbody.py b/test/test_GaussianEMRestraint_rigidbody.py index 5e564eb8..71c32e34 100644 --- a/test/test_GaussianEMRestraint_rigidbody.py +++ b/test/test_GaussianEMRestraint_rigidbody.py @@ -11,9 +11,9 @@ class Tests(IMP.test.TestCase): def setUp(self): IMP.test.TestCase.setUp(self) - self.m = IMP.Model() + self.model = IMP.Model() self.simo1 = IMP.pmi.representation.Representation( - self.m, upperharmonic=True, disorderedlength=False) + self.model, upperharmonic=True, disorderedlength=False) def test_GaussianEMRestraint_rigid_body(self): """Test rigid body movement of target EM map""" @@ -22,7 +22,7 @@ def test_GaussianEMRestraint_rigid_body(self): IMP.isd.gmm_tools.decorate_gmm_from_text( fname, target_ps, - self.m, + self.model, radius_scale=3.0, mass_scale=1.0) gemh = IMP.pmi.restraints.em.GaussianEMRestraint(target_ps, fname,