6from collections
import defaultdict
17 """Take iterable of TempResidues and return compatified string"""
20 idxs = [r.get_index()
for r
in res]
23 cur_range = [idxs[0], idxs[0]]
25 if idx != cur_range[1]+1:
26 all_ranges.append(cur_range)
27 cur_range = [idx, idx]
29 all_ranges.append(cur_range)
31 for nr, r
in enumerate(all_ranges):
32 ret +=
'%i-%i' % (r[0], r[1])
33 if nr < len(all_ranges)-1:
38def _select_ca_or_p(hiers, **kwargs):
39 """Select all CA (amino acids) or P (nucleic acids) as appropriate"""
41 ps = sel_p.get_selected_particles()
49 atom_type=_AT_HET_CA, **kwargs)
50 return sel.get_selected_particles()
53def get_structure(model, pdb_fn, chain_id, res_range=None, offset=0,
54 model_num=None, ca_only=False):
55 """read a structure from a PDB file and return a list of residues
56 @param model The IMP model
57 @param pdb_fn The file to read (in mmCIF, BinaryCIF, or legacy PDB format)
58 @param chain_id Chain ID to read
59 @param res_range Add only a specific set of residues.
60 res_range[0] is the starting and res_range[1] is the ending
62 The ending residue can be "END", that will take everything
63 to the end of the sequence.
65 @param offset Apply an offset to the residue indexes of the PDB file
66 @param model_num Read multi-model PDB and return that model (0-based index)
67 @param ca_only Read only CA atoms (by default, all non-waters are read)
70 if pdb_fn.endswith(
'.cif'):
71 read_file = IMP.atom.read_mmcif
72 read_multi_file = IMP.atom.read_multimodel_mmcif
73 elif pdb_fn.endswith(
'.bcif'):
74 read_file = IMP.atom.read_bcif
75 read_multi_file = IMP.atom.read_multimodel_bcif
77 read_file = IMP.atom.read_pdb
78 read_multi_file = IMP.atom.read_multimodel_pdb
85 if res_range[1] ==
"END":
90 reader = read_file
if model_num
is None else read_multi_file
92 if model_num
is not None:
95 ps = _select_ca_or_p(mh, chain=chain_id)
100 res.set_index(res.get_index() + offset)
104 "no residues selected from %s in range %s" % (pdb_fn, res_range),
109def build_bead(model, residues, input_coord=None):
110 """Generates a single bead"""
112 ds_frag = (residues[0].get_index(), residues[-1].get_index())
118 if ds_frag[0] == ds_frag[-1]:
119 rt = residues[0].get_residue_type()
121 h.set_name(
'%i_bead' % (ds_frag[0]))
122 prt.set_name(
'%i_bead' % (ds_frag[0]))
129 ptem.set_radius(radius)
132 h.set_name(
'%i-%i_bead' % (ds_frag[0], ds_frag[-1]))
133 prt.set_name(
'%i-%i_bead' % (ds_frag[0], ds_frag[-1]))
134 h.set_residue_indexes(range(ds_frag[0], ds_frag[-1] + 1))
136 radius = 0.8 * (3.0 / 4.0 / math.pi * volume) ** (1.0 / 3.0)
137 ptem.set_radius(radius)
141 if tuple(input_coord)
is not None:
142 ptem.set_coordinates(input_coord)
148def build_necklace(model, residues, resolution, input_coord=None):
149 """Generates a string of beads with given length"""
153 out_hiers.append(build_bead(model, chunk, input_coord=input_coord))
157def build_ca_centers(model, residues):
158 """Create a bead on the CA position with coarsened size and mass"""
160 for tempres
in residues:
161 residue = tempres.get_hierarchy()
163 rp1.set_name(
"Residue_%i" % residue.get_index())
164 rt = residue.get_residue_type()
177 atom_types=[IMP.atom.AT_CA, _AT_HET_CA]).get_selected_particles()
179 residue, atom_type=IMP.atom.AT_P).get_selected_particles()
182 central_atom = calpha[0]
187 "build_ca_centers: weird selection (no CA, no "
188 "nucleotide P or ambiguous selection found)")
194 out_hiers.append(this_res)
198def setup_bead_as_gaussian(mh):
199 """Setup bead as spherical gaussian, using radius as variance"""
200 p = mh.get_particle()
210def show_representation(node):
214 resolutions = repr.get_resolutions()
215 for r
in resolutions:
216 print(
'---- resolution %i ----' % r)
223def _get_color_for_representation(rep):
224 """Return an IMP.display.Color object (or None) for the given
226 if rep.color
is not None:
227 if isinstance(rep.color, float):
229 elif isinstance(rep.color, str):
231 elif hasattr(rep.color,
'__iter__')
and len(rep.color) == 3:
236 raise TypeError(
"Color must be Chimera color name, a hex "
237 "string, a float or (r,g,b) tuple")
240def _add_fragment_provenance(fragment, first_residue, rephandler):
241 """Track the original source of a fragment's structure.
242 If the residues in the given fragment were extracted from a PDB
243 file, add suitable provenance information to the Model (the name
244 of that file, chain ID, and residue index offset)."""
245 pdb_element = rephandler.pdb_for_residue.get(first_residue.get_index())
247 m = fragment.get_model()
250 p, pdb_element.filename, pdb_element.chain_id, pdb_element.offset)
255def build_representation(parent, rep, coord_finder, rephandler):
256 """Create requested representation.
257 For beads, identifies continuous segments and sets up as Representation.
258 If any volume-based representations (e.g.,densities) are requested,
259 will instead create a single Representation node.
260 All reps are added as children of the passed parent.
261 @param parent The Molecule to which we'll add representations
262 @param rep What to build. An instance of pmi::topology::_Representation
263 @param coord_finder A _FindCloseStructure object to help localize beads
268 model = parent.hier.get_model()
269 _start_model = parent._start_model
270 color = _get_color_for_representation(rep)
274 primary_resolution = min(rep.bead_resolutions)
281 if rep.density_residues_per_component:
283 num_components = math.ceil(
284 len(rep.residues) / rep.density_residues_per_component)
285 rep_dict = defaultdict(list)
288 segp, primary_resolution)
289 built_reps.append(root_representation)
290 res_nums = [r.get_index()
for r
in rep.residues]
294 density_frag.get_particle().set_name(
295 "Densities %i" % rep.density_residues_per_component)
298 if os.path.exists(rep.density_prefix +
'.txt') \
299 and not rep.density_force_compute:
301 rep.density_prefix +
'.txt', density_ps, model)
302 if (len(density_ps) != num_components
303 or not os.path.exists(rep.density_prefix +
'.txt')
304 or rep.density_force_compute):
307 for r
in rep.residues:
319 mass_multiplier=total_mass)
322 rep.density_prefix +
'.txt')
323 if rep.density_voxel_size > 0.0:
325 density_ps, rep.density_prefix +
'.mrc',
326 rep.density_voxel_size, fast=
True)
328 for n, d
in enumerate(density_ps):
329 d.set_name(
'Density #%d' % n)
330 density_frag.add_child(d)
331 root_representation.add_representation(
332 density_frag, IMP.atom.DENSITIES,
333 rep.density_residues_per_component)
337 rsort = sorted(list(rep.residues), key=
lambda r: r.get_index())
338 prev_idx = rsort[0].get_index()-1
339 prev_structure = rsort[0].get_has_structure()
342 for nr, r
in enumerate(rsort):
343 if (r.get_index() != prev_idx+1
344 or r.get_has_structure() != prev_structure
or force_break):
345 segments.append(cur_seg)
349 prev_idx = r.get_index()
350 prev_structure = r.get_has_structure()
351 if r.get_index()-1
in rep.bead_extra_breaks:
354 segments.append(cur_seg)
359 for frag_res
in segments:
360 res_nums = [r.get_index()
for r
in frag_res]
361 rrange =
"%i-%i" % (res_nums[0], res_nums[-1])
362 name =
"Frag_" + rrange
364 name_all += rrange +
','
365 elif name_count == 3:
372 segp, primary_resolution)
373 built_reps.append(this_representation)
374 for resolution
in rep.bead_resolutions:
377 this_resolution.set_name(
"%s: Res %i" % (name, resolution))
378 if frag_res[0].get_has_structure():
379 pdb_element = _add_fragment_provenance(
380 this_resolution, frag_res[0], rephandler)
381 if pdb_element
is not None:
382 prov_dict[resolution] = pdb_element
384 if resolution == atomic_res:
385 for residue
in frag_res:
386 this_resolution.add_child(residue.get_hierarchy(model))
387 elif resolution == ca_res
and rep.bead_ca_centers:
388 beads = build_ca_centers(model, frag_res)
390 this_resolution.add_child(bead)
394 for residue
in frag_res:
395 tempc.add_child(residue.hier)
397 tempc, resolution,
False, model)
398 for bead
in beads.get_children():
399 this_resolution.add_child(bead)
400 _start_model.remove_particle(tempc.get_particle_index())
401 model.remove_particle(beads.get_particle_index())
404 input_coord = coord_finder.find_nearest_coord(
405 min(r.get_index()
for r
in frag_res))
406 if input_coord
is None:
407 input_coord = rep.bead_default_coord
408 beads = build_necklace(model,
413 this_resolution.add_child(bead)
424 rep_dict[resolution] += this_resolution.get_children()
426 if resolution == primary_resolution:
427 this_representation.add_child(this_resolution)
429 this_representation.add_representation(this_resolution,
433 if rep.setup_particles_as_densities:
435 setup_bead_as_gaussian(p)
436 this_resolution.set_name(
437 this_resolution.get_name() +
' Densities %i' % resolution)
438 this_representation.add_representation(this_resolution,
443 root_representation.set_name(name_all.strip(
',') +
": Base")
444 d = root_representation.get_representations(IMP.atom.DENSITIES)
445 d[0].set_name(
'%s: ' % name_all + d[0].get_name())
446 for resolution
in rep.bead_resolutions:
449 [r.get_index()
for r
in rep.residues])
450 this_resolution.set_name(
"%s: Res %i" % (name_all, resolution))
454 if prov_dict.get(resolution):
455 pdb_element = prov_dict[resolution]
458 pdb_element.filename,
459 pdb_element.chain_id, pdb_element.offset)
461 for hier
in rep_dict[resolution]:
462 this_resolution.add_child(hier)
463 if resolution == primary_resolution:
464 root_representation.add_child(this_resolution)
466 root_representation.add_representation(this_resolution,
Class to handle individual particles of a Model object.
An exception for an invalid value being passed to IMP.
A Gaussian distribution in 3D.
A decorator for a particle representing an atom.
Select all CA ATOM records.
Select all ATOM and HETATM records with the given chain ids.
static Chain setup_particle(Model *m, ParticleIndex pi, std::string id)
static Fragment setup_particle(Model *m, ParticleIndex pi)
static Mass setup_particle(Model *m, ParticleIndex pi, Float mass)
A decorator for a representation.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
static Representation setup_particle(Model *m, ParticleIndex pi)
Select all residue numbers in the given range (inclusive).
A decorator for a residue.
static Residue setup_particle(Model *m, ParticleIndex pi, ResidueType t, int index, int insertion_code)
Select hierarchy particles identified by the biological name.
static Gaussian setup_particle(Model *m, ParticleIndex pi)
static StructureProvenance setup_particle(Model *m, ParticleIndex pi, std::string filename, std::string chain_id, int residue_offset)
A decorator for a particle with x,y,z coordinates and a radius.
static XYZR setup_particle(Model *m, ParticleIndex pi)
A decorator for a particle with x,y,z coordinates.
static Colored setup_particle(Model *m, ParticleIndex pi, Color color)
Warning related to handling of structures.
double get_ball_radius_from_volume_3d(double volume)
Return the radius of a sphere with a given volume.
Rotation3D get_identity_rotation_3d()
Return a rotation that does not do anything.
Functionality for loading, creating, manipulating and scoring atomic structures.
PDBSelector * get_default_pdb_selector()
double get_volume_from_residue_type(ResidueType rt)
Return an estimate for the volume of a given residue.
double get_volume_from_mass(double m, ProteinDensityReference ref=ALBER)
Estimate the volume of a protein from its mass.
double get_mass(ResidueType c)
Get the mass from the residue type.
double get_mass_from_number_of_residues(unsigned int num_aa)
Estimate the mass of a protein from the number of amino acids.
void show_molecular_hierarchy(Hierarchy h)
Print out the molecular hierarchy.
Hierarchy create_simplified_along_backbone(Hierarchy input, int num_res, bool keep_detailed=false, Model *m=nullptr)
void add_provenance(Model *m, ParticleIndex pi, Provenance p)
Add provenance to part of the model.
GenericHierarchies get_leaves(Hierarchy mhd)
Get all the leaves of the bit of hierarchy.
Color get_rgb_color(double f)
Return the color for f from the RGB color map.
Python classes to represent, score, sample and analyze models.