def exercise(): pdb_file_names = raw_input( "pdb file name here,space interval,such as : 2ona.pdb 2whb.pdb") p_f = pdb_file_names.split(' ') for pdb_file_name in p_f: easy_run.call("phenix.fetch_pdb {0}".format(pdb_file_name[0:4])) easy_run.call("phenix.ready_set {0}".format(pdb_file_name)) print(pdb_file_name, "-" * 50) cif_file_name = pdb_file_name[0:4] + ".ligands.cif" if os.path.exists(cif_file_name): cif_file_names = cif_file_name else: cif_file_names = None model = get_model(pdb_file_name=pdb_file_name, cif_file_name=cif_file_names) resnames = raw_input( 'list of resnames ,comma interval,such as: resname PHE,resname HIS' ) resn = resnames.split(',') ss = " or ".join(resn) m_sel = model.selection(ss) new_model = model.select(m_sel) hierarchy = new_model.get_hierarchy() crystal_symmetry = new_model.crystal_symmetry() hierarchy.write_pdb_file(file_name=pdb_file_name[0:4] + "new.pdb", crystal_symmetry=crystal_symmetry)
def test_3(): """ test for command-line tool iotbx.unique_with_biomt""" inp = iotbx.pdb.input(source_info=None, lines=pdb_str_0) model = mmtbx.model.manager(model_input=inp) model.expand_with_BIOMT_records() model = shift_and_box_model(model) sel = model.selection("chain '0' or chain 'C' or chain 'F' or chain 'I' or chain 'L' or chain 'O' or chain 'R' or chain 'U' or chain 'X'") model = model.select(sel) pdb_str = model.model_as_pdb() fname = 'tst_reduce_model_with_biomt_test3.pdb' with open(fname, 'w') as f: f.write(pdb_str) assert os.path.isfile(fname) cmd = "iotbx.unique_with_biomt %s" % fname print(cmd) easy_run.call(cmd) res_fname = 'tst_reduce_model_with_biomt_test3_unique_biomt_000.cif' assert_lines_in_file(res_fname, """ ATOM 1 N . LYS 0 151 ? 72.74200 43.65400 193.22800 14.010 14.01000 N ? A ? 1 1""") assert_lines_in_file(res_fname, """ _pdbx_struct_assembly_gen.asym_id_list 1 (1-9) A""") cmd = "iotbx.unique_with_biomt %s chain_id_to_leave='C' output.serial=1" % fname print(cmd) easy_run.call(cmd) res_fname = 'tst_reduce_model_with_biomt_test3_unique_biomt_001.cif' assert_lines_in_file(res_fname, """ ATOM 1 N . LYS C 151 ? 186.74500 185.38200 236.77300 14.010 14.01000 N ? A ? 1 1""") assert_lines_in_file(res_fname, """ _pdbx_struct_assembly_gen.asym_id_list 1 (1-9) A""")
def remove_clashing(model, dist_min): h = model.get_hierarchy() # Remove overlapping water-water wsel = h.atom_selection_cache().selection(string="water") wh = h.select(wsel) sel = [] for i, ai in enumerate(wh.atoms()): for j, aj in enumerate(wh.atoms()): if (j >= i or ai.i_seq == aj.i_seq): continue d = ai.distance(aj) if (d < dist_min): sel_ = [ai.i_seq, aj.i_seq] sel_.sort() sel.append(sel_) sel_clash = flex.size_t([s[0] for s in sel]) # Remove overlapping water-nonwater nonwa = h.select(~wsel).atoms() sel = flex.size_t() for aw in wh.atoms(): for ap in nonwa: d = aw.distance(ap) if (d < dist_min): sel.append(aw.i_seq) break sel_clash.extend(sel) # return model.select(~flex.bool(h.atoms_size(), sel_clash))
def exclude_h_on_SS(model): rm = model.get_restraints_manager() bond_proxies_simple, asu = rm.geometry.get_all_bond_proxies( sites_cart=model.get_sites_cart()) els = model.get_hierarchy().atoms().extract_element() ss_i_seqs = [] all_proxies = [p for p in bond_proxies_simple] for proxy in asu: all_proxies.append(proxy) for proxy in all_proxies: if (isinstance(proxy, ext.bond_simple_proxy)): i, j = proxy.i_seqs elif (isinstance(proxy, ext.bond_asu_proxy)): i, j = proxy.i_seq, proxy.j_seq else: assert 0 # never goes here if ([els[i], els[j] ].count("S") == 2): # XXX may be coordinated if metal edits used ss_i_seqs.extend([i, j]) sel_remove = flex.size_t() for proxy in all_proxies: if (isinstance(proxy, ext.bond_simple_proxy)): i, j = proxy.i_seqs elif (isinstance(proxy, ext.bond_asu_proxy)): i, j = proxy.i_seq, proxy.j_seq else: assert 0 # never goes here if (els[i] in ["H", "D"] and j in ss_i_seqs): sel_remove.append(i) if (els[j] in ["H", "D"] and i in ss_i_seqs): sel_remove.append(j) return model.select(~flex.bool(model.size(), sel_remove))
def get_selected(sel): result = None if (type(sel) == str and sel == "all"): return find(model=model, a_DHA_cutoff=90).get_params_as_arrays() elif (sel is not None and sel.count(True) > 0): result = find(model=model.select(sel), a_DHA_cutoff=90).get_params_as_arrays() return result
def run(self): # I'm guessing self.data_manager, self.params and self.logger # are already defined here... # this must be mmtbx.model.manager? model = self.data_manager.get_model() atoms = model.get_atoms() all_bsel = flex.bool(atoms.size(), False) for selection_string in self.params.atom_selection_program.inselection: print("Selecting '%s'" % selection_string, file=self.logger) isel = model.iselection(string=selection_string) all_bsel.set_selected(isel, True) if self.params.atom_selection_program.write_pdb_file is None: print(" %d atom%s selected" % plural_s(isel.size()), file=self.logger) for atom in atoms.select(isel): print(" %s" % atom.format_atom_record(), file=self.logger) print("", file=self.logger) if self.params.atom_selection_program.write_pdb_file is not None: print("Writing file:", show_string( self.params.atom_selection_program.write_pdb_file), file=self.logger) ss_ann = model.get_ss_annotation() if not model.crystal_symmetry() or \ (not model.crystal_symmetry().unit_cell()): model = shift_and_box_model(model, shift_model=False) selected_model = model.select(all_bsel) if (ss_ann is not None): selected_model.set_ss_annotation(ss_ann.\ filter_annotation( hierarchy=selected_model.get_hierarchy(), asc=selected_model.get_atom_selection_cache(), remove_short_annotations=False, remove_3_10_helices=False, remove_empty_annotations=True, concatenate_consecutive_helices=False, split_helices_with_prolines=False, filter_sheets_with_long_hbonds=False)) if self.params.atom_selection_program.cryst1_replacement_buffer_layer is not None: box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=selected_model.get_atoms().extract_xyz(), buffer_layer=self.params.atom_selection_program. cryst1_replacement_buffer_layer) sp = crystal.special_position_settings(box.crystal_symmetry()) sites_frac = box.sites_frac() xrs_box = selected_model.get_xray_structure( ).replace_sites_frac(box.sites_frac()) xray_structure_box = xray.structure(sp, xrs_box.scatterers()) selected_model.set_xray_structure(xray_structure_box) pdb_str = selected_model.model_as_pdb() f = open(self.params.atom_selection_program.write_pdb_file, 'w') f.write(pdb_str) f.close() print("", file=self.logger)
def exercise_no_sidechains(prefix="tst_one_resid_rotation_no_sidechains"): pdb_inp = iotbx.pdb.input(lines=pdb_str.split('\n'), source_info=None) model = mmtbx.model.manager( model_input = pdb_inp) with open("%s_start.pdb" % prefix, 'w') as f: f.write(model.model_as_pdb()) s = model.selection("name N or name CA or name C or name O") model = model.select(s) ci = cablam_idealization(model = model, params=master_phil.extract().cablam_idealization, log=sys.stdout) pdb_txt = model.model_as_pdb()
def run(args, command_name=libtbx.env.dispatcher_name): parser = argparse.ArgumentParser( prog=command_name, usage='%s pdb_file "atom_selection" [...]' % command_name) parser.add_argument("file_name", nargs=1, help="File name of the model file") parser.add_argument( "inselections", help="Atom selection strings", nargs='+', ) parser.add_argument("--write-pdb-file", action="store", help="write selected atoms to new PDB file", default=None) parser.add_argument( "--cryst1-replacement-buffer-layer", action="store", type=float, help="replace CRYST1 with pseudo unit cell covering the selected" " atoms plus a surrounding buffer layer", default=None) co = parser.parse_args(args) pdb_inp = iotbx.pdb.input(file_name=co.file_name[0]) model = mmtbx.model.manager(model_input=pdb_inp, process_input=True) atoms = model.get_atoms() all_bsel = flex.bool(atoms.size(), False) for selection_string in co.inselections: print selection_string isel = model.iselection(selstr=selection_string) all_bsel.set_selected(isel, True) if (not co.write_pdb_file): print " %d atom%s selected" % plural_s(isel.size()) for atom in atoms.select(isel): print " %s" % atom.format_atom_record() print if (co.write_pdb_file): print "Writing file:", show_string(co.write_pdb_file) selected_model = model.select(all_bsel) if (co.cryst1_replacement_buffer_layer is not None): box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=selected_model.get_atoms().extract_xyz(), buffer_layer=co.cryst1_replacement_buffer_layer) sp = crystal.special_position_settings(box.crystal_symmetry()) sites_frac = box.sites_frac() xrs_box = selected_model.get_xray_structure().replace_sites_frac( box.sites_frac()) xray_structure_box = xray.structure(sp, xrs_box.scatterers()) selected_model.set_xray_structure(xray_structure_box) pdb_str = selected_model.model_as_pdb() f = open(co.write_pdb_file, 'w') f.write(pdb_str) f.close() print
def main(filename): t0 = time.time() pdb_inp = iotbx.pdb.input(file_name=filename) model = mmtbx.model.manager(model_input=pdb_inp, log=null_out()) sel = model.selection(string="protein") model = model.select(selection=sel) model.crystal_symmetry() a = aev.AEV(model=model) CC_value = aev.compare(a) print(CC_value) recs = aev.format_HELIX_records_from_AEV(CC_value) print("\n".join(recs)) print('time', time.time() - t0)
def run (args=(), params=None, out=None) : if (out is None) : out = sys.stdout if (params is None) : import iotbx.phil cmdline = iotbx.phil.process_command_line_with_files( args=args, master_phil_string=master_phil, pdb_file_def="adp_statistics.pdb_file", cif_file_def="adp_statistics.cif_file", usage_string="""\ phenix.b_factor_statistics model.pdb [restraints.cif] [selection=...] Show statistics for atomic displacement parameters (ADPs) or B-factors, including TLS contribution if present.""") params = cmdline.work.extract() validate_params(params) import mmtbx.model import mmtbx.restraints from mmtbx.monomer_library import pdb_interpretation processed_pdb_file = pdb_interpretation.run( args=[params.adp_statistics.pdb_file] + params.adp_statistics.cif_file, substitute_non_crystallographic_unit_cell_if_necessary=True, log=out) geometry = processed_pdb_file.geometry_restraints_manager(show_energies=True) restraints_manager = mmtbx.restraints.manager( geometry = geometry, normalization = True) model = mmtbx.model.manager( xray_structure = processed_pdb_file.xray_structure(), pdb_hierarchy = processed_pdb_file.all_chain_proxies.pdb_hierarchy, restraints_manager = restraints_manager, log = out) make_sub_header("Analyzing model B-factors", out=out) if (params.adp_statistics.selection is not None) : sel_cache = model.pdb_hierarchy().atom_selection_cache() selection = sel_cache.selection(params.adp_statistics.selection) n_sel = selection.count(True) if (n_sel == 0) : raise Sorry("No atoms in selection!") else : model = model.select(selection) print >> out, "Extracted %d atoms in selection:" % n_sel print >> out, " %s" % params.adp_statistics.selection print >> out, "" stats = model.adp_statistics() stats.file_name = params.adp_statistics.pdb_file stats.selection = params.adp_statistics.selection stats.show_1(out=out) return stats
def test_1(): inp = iotbx.pdb.input(source_info=None, lines=pdb_str_0) model = mmtbx.model.manager(model_input=inp) model.expand_with_BIOMT_records() model = shift_and_box_model(model) sel = model.selection("chain '0' or chain 'C' or chain 'F' or chain 'I' or chain 'L' or chain 'O' or chain 'R' or chain 'U' or chain 'X'") model = model.select(sel) model.search_for_ncs() model.setup_ncs_constraints_groups(filter_groups=True) n1 = model.get_number_of_atoms() assert n1 == 648, n1 assert model.ncs_constraints_present() nrgl = model.get_ncs_groups() assert len(nrgl[0].master_iselection) == 72 assert len(nrgl[0].copies) == 8 # nrgl._show() # print (model.can_be_unique_with_biomt()) cif_txt = model.model_as_mmcif(try_unique_with_biomt=True) # print (cif_txt) assert_lines_in_text(cif_txt, """ loop_ _pdbx_struct_assembly_gen.assembly_id _pdbx_struct_assembly_gen.oper_expression _pdbx_struct_assembly_gen.asym_id_list 1 (1-9) A""") assert_lines_in_text(cif_txt, """ loop_ _pdbx_struct_assembly.id _pdbx_struct_assembly.details _pdbx_struct_assembly.method_details _pdbx_struct_assembly.oligomeric_details _pdbx_struct_assembly.oligomeric_count 1 'Symmetry assembly' ? ? ? """) assert_lines_in_text(cif_txt, """ _pdbx_struct_oper_list.vector[1] _pdbx_struct_oper_list.vector[2] _pdbx_struct_oper_list.vector[3] 1 'point symmetry operation' ? ? 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0""") inp = iotbx.pdb.input(source_info=None, lines=cif_txt) m2 = mmtbx.model.manager(model_input=inp) n2_1 = m2.get_number_of_atoms() assert n2_1 == 72 m2.expand_with_BIOMT_records() n2_2 = m2.get_number_of_atoms() # print (n1, n2) assert n1 == n2_2, "%d, %d" % (n1, n2)
def run(args=(), params=None, out=None): if (out is None): out = sys.stdout if (params is None): import iotbx.phil cmdline = iotbx.phil.process_command_line_with_files( args=args, master_phil_string=master_phil, pdb_file_def="adp_statistics.pdb_file", cif_file_def="adp_statistics.cif_file", usage_string="""\ phenix.b_factor_statistics model.pdb [restraints.cif] [selection=...] Show statistics for atomic displacement parameters (ADPs) or B-factors, including TLS contribution if present.""") params = cmdline.work.extract() validate_params(params) import mmtbx.model import mmtbx.restraints from mmtbx.monomer_library import pdb_interpretation processed_pdb_file = pdb_interpretation.run( args=[params.adp_statistics.pdb_file] + params.adp_statistics.cif_file, substitute_non_crystallographic_unit_cell_if_necessary=True, log=out) geometry = processed_pdb_file.geometry_restraints_manager( show_energies=True) restraints_manager = mmtbx.restraints.manager(geometry=geometry, normalization=True) model = mmtbx.model.manager( xray_structure=processed_pdb_file.xray_structure(), pdb_hierarchy=processed_pdb_file.all_chain_proxies.pdb_hierarchy, restraints_manager=restraints_manager, log=out) make_sub_header("Analyzing model B-factors", out=out) if (params.adp_statistics.selection is not None): sel_cache = model.pdb_hierarchy().atom_selection_cache() selection = sel_cache.selection(params.adp_statistics.selection) n_sel = selection.count(True) if (n_sel == 0): raise Sorry("No atoms in selection!") else: model = model.select(selection) print >> out, "Extracted %d atoms in selection:" % n_sel print >> out, " %s" % params.adp_statistics.selection print >> out, "" stats = model.adp_statistics() stats.file_name = params.adp_statistics.pdb_file stats.selection = params.adp_statistics.selection stats.show_1(out=out) return stats
def get_clashes_result(raw_records, sel=None): ''' Helper function to get clashes results from raw records ''' params = mmtbx.model.manager.get_default_pdb_interpretation_params() params.pdb_interpretation.allow_polymer_cross_special_position = True params.pdb_interpretation.clash_guard.nonbonded_distance_threshold = None pdb_inp = iotbx.pdb.input(lines=raw_records.split("\n"), source_info=None) model = mmtbx.model.manager(model_input=pdb_inp, log=null_out()) model.process(pdb_interpretation_params=params, make_restraints=True) if sel is not None: model = model.select(sel) pnps = pnp.manager(model=model) clashes = pnps.get_clashes() return clashes
def exclude_h_on_coordinated_S(model): # XXX if edits used it should be like in exclude_h_on_SS rm = model.get_restraints_manager().geometry els = model.get_hierarchy().atoms().extract_element() # Find possibly coordinated S exclusion_list = ["H","D","T","S","O","P","N","C","SE"] sel_s = [] for proxy in rm.pair_proxies().nonbonded_proxies.simple: i,j = proxy.i_seqs if(els[i] == "S" and not els[j] in exclusion_list): sel_s.append(i) if(els[j] == "S" and not els[i] in exclusion_list): sel_s.append(j) # Find H attached to possibly coordinated S bond_proxies_simple, asu = rm.get_all_bond_proxies( sites_cart = model.get_sites_cart()) sel_remove = flex.size_t() for proxy in bond_proxies_simple: i,j = proxy.i_seqs if(els[i] in ["H","D"] and j in sel_s): sel_remove.append(i) if(els[j] in ["H","D"] and i in sel_s): sel_remove.append(j) return model.select(~flex.bool(model.size(), sel_remove))
def run(args=(), params=None, out=None): if (out is None): out = sys.stdout if (params is None): import iotbx.phil cmdline = iotbx.phil.process_command_line_with_files( args=args, master_phil_string=master_phil, pdb_file_def="adp_statistics.pdb_file", cif_file_def="adp_statistics.cif_file", usage_string="""\ phenix.b_factor_statistics model.pdb [restraints.cif] [selection=...] Show statistics for atomic displacement parameters (ADPs) or B-factors, including TLS contribution if present.""") params = cmdline.work.extract() validate_params(params) import mmtbx.model m_input = iotbx.pdb.input(file_name=params.adp_statistics.pdb_file) restraint_objects = [] for fn in params.adp_statistics.cif_file: cif_object = iotbx.cif.reader(file_path=fn).model() restraint_objects.append((fn, cif_object)) model = mmtbx.model.manager(model_input=m_input, restraint_objects=restraint_objects, build_grm=True, log=out) make_sub_header("Analyzing model B-factors", out=out) if (params.adp_statistics.selection is not None): selection = model.selection(params.adp_statistics.selection) n_sel = selection.count(True) if (n_sel == 0): raise Sorry("No atoms in selection!") else: model = model.select(selection) print >> out, "Extracted %d atoms in selection:" % n_sel print >> out, " %s" % params.adp_statistics.selection print >> out, "" stats = model.adp_statistics() stats.file_name = params.adp_statistics.pdb_file stats.selection = params.adp_statistics.selection stats.show_1(out=out) return stats
def run(self): # I'm guessing self.data_manager, self.params and self.logger # are already defined here... # this must be mmtbx.model.manager? model = self.data_manager.get_model() atoms = model.get_atoms() all_bsel = flex.bool(atoms.size(), False) for selection_string in self.params.atom_selection_program.inselection: print("Selecting '%s'" % selection_string, file=self.logger) isel = model.iselection(selstr=selection_string) all_bsel.set_selected(isel, True) if self.params.atom_selection_program.write_pdb_file is None: print(" %d atom%s selected" % plural_s(isel.size()), file=self.logger) for atom in atoms.select(isel): print(" %s" % atom.format_atom_record(), file=self.logger) print("", file=self.logger) if self.params.atom_selection_program.write_pdb_file is not None: print("Writing file:", show_string( self.params.atom_selection_program.write_pdb_file), file=self.logger) selected_model = model.select(all_bsel) if self.params.atom_selection_program.cryst1_replacement_buffer_layer is not None: box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=selected_model.get_atoms().extract_xyz(), buffer_layer=self.params.atom_selection_program. cryst1_replacement_buffer_layer) sp = crystal.special_position_settings(box.crystal_symmetry()) sites_frac = box.sites_frac() xrs_box = selected_model.get_xray_structure( ).replace_sites_frac(box.sites_frac()) xray_structure_box = xray.structure(sp, xrs_box.scatterers()) selected_model.set_xray_structure(xray_structure_box) pdb_str = selected_model.model_as_pdb() f = open(self.params.atom_selection_program.write_pdb_file, 'w') f.write(pdb_str) f.close() print("", file=self.logger)
def add(model, use_neutron_distances=False, adp_scale=1, exclude_water=True, protein_only=False, stop_for_unknowns=True, remove_first=True): if (remove_first): model = model.select(~model.get_hd_selection()) pdb_hierarchy = model.get_hierarchy() mon_lib_srv = model.get_mon_lib_srv() get_class = iotbx.pdb.common_residue_names_get_class """ for pmodel in pdb_hierarchy.models(): for chain in pmodel.chains(): for residue_group in chain.residue_groups(): for conformer in residue_group.conformers(): for residue in conformer.residues(): print list(residue.atoms().extract_name()) """ #XXX This breaks for 1jxt, residue 2, TYR for chain in pdb_hierarchy.only_model().chains(): for rg in chain.residue_groups(): for ag in rg.atom_groups(): #print list(ag.atoms().extract_name()) if (get_class(name=ag.resname) == "common_water"): continue if (protein_only and not ag.resname.strip().upper() in aa_codes): continue actual = [a.name.strip().upper() for a in ag.atoms()] mlq = mon_lib_query(residue=ag.resname, mon_lib_srv=mon_lib_srv) expected_all = mlq.atom_dict().keys() expected_h = [] for k, v in mlq.atom_dict().iteritems(): if (v.type_symbol == "H"): expected_h.append(k) missing_h = list(set(expected_h).difference(set(actual))) if 0: print ag.resname, missing_h new_xyz = ag.atoms().extract_xyz().mean() hetero = ag.atoms()[0].hetero for mh in missing_h: # TODO: this should be probably in a central place if len(mh) < 4: mh = (' ' + mh).ljust(4) a = (iotbx.pdb.hierarchy.atom().set_name( new_name=mh).set_element(new_element="H").set_xyz( new_xyz=new_xyz).set_hetero(new_hetero=hetero)) ag.append_atom(a) pdb_hierarchy.atoms().reset_serial() #pdb_hierarchy.sort_atoms_in_place() p = mmtbx.model.manager.get_default_pdb_interpretation_params() p.pdb_interpretation.clash_guard.nonbonded_distance_threshold = None p.pdb_interpretation.use_neutron_distances = use_neutron_distances p.pdb_interpretation.proceed_with_excessive_length_bonds = True #p.pdb_interpretation.restraints_library.cdl=False # XXX this triggers a bug !=360 ro = model.get_restraint_objects() model = mmtbx.model.manager(model_input=None, pdb_hierarchy=pdb_hierarchy, build_grm=True, stop_for_unknowns=stop_for_unknowns, crystal_symmetry=model.crystal_symmetry(), restraint_objects=ro, pdb_interpretation_params=p, log=null_out()) # # Remove lone H # sel_h = model.get_hd_selection() # sel_isolated = model.isolated_atoms_selection() # sel_lone = sel_h & sel_isolated # model = model.select(~sel_lone) # Only keep H which have been parameterized in riding H procedure sel_h = model.get_hd_selection() model.setup_riding_h_manager() sel_h_in_para = flex.bool( [bool(x) for x in model.riding_h_manager.h_parameterization]) sel_h_not_in_para = sel_h_in_para.exclusive_or(sel_h) model = model.select(~sel_h_not_in_para) model = exclude_h_on_SS(model=model) model = exclude_h_on_coordinated_S(model=model) # Reset occupancies, ADPs and idealize model.reset_adp_for_hydrogens(scale=adp_scale) model.reset_occupancy_for_hydrogens_simple() model.idealize_h_riding() return model
def add(model, use_neutron_distances = False, adp_scale = 1, exclude_water = True, protein_only = False, stop_for_unknowns = False, keep_existing_H = False): """ Add H atoms to a model Parameters ---------- use_neutron_distances : bool use neutron distances instead of X-ray adp_scale : float scale factor for isotropic B of H atoms. B(H-atom) = adp_scale * B(parent non-H atom) keep_existing_H : bool keep existing H atoms in model, only place missing H Returns ------- model mmtbx model object with H atoms """ model_has_bogus_cs = False # TODO temporary fix until the code is moved to model class # check if box cussion of 5 A is enough to prevent symm contacts cs = model.crystal_symmetry() if cs is None: model = shift_and_box_model(model = model) model_has_bogus_cs = True # Remove existing H if requested if( not keep_existing_H): model = model.select(~model.get_hd_selection()) pdb_hierarchy = model.get_hierarchy() mon_lib_srv = model.get_mon_lib_srv() """ for pmodel in pdb_hierarchy.models(): for chain in pmodel.chains(): for residue_group in chain.residue_groups(): for conformer in residue_group.conformers(): for residue in conformer.residues(): print list(residue.atoms().extract_name()) """ add_missing_H_atoms_at_bogus_position(pdb_hierarchy = pdb_hierarchy, mon_lib_srv = mon_lib_srv, protein_only = protein_only) pdb_hierarchy.atoms().reset_serial() #pdb_hierarchy.sort_atoms_in_place() p = mmtbx.model.manager.get_default_pdb_interpretation_params() p.pdb_interpretation.clash_guard.nonbonded_distance_threshold=None p.pdb_interpretation.use_neutron_distances = use_neutron_distances p.pdb_interpretation.proceed_with_excessive_length_bonds=True #p.pdb_interpretation.restraints_library.cdl=False # XXX this triggers a bug !=360 ro = model.get_restraint_objects() model = mmtbx.model.manager( model_input = None, pdb_hierarchy = pdb_hierarchy, build_grm = True, stop_for_unknowns = stop_for_unknowns, crystal_symmetry = model.crystal_symmetry(), restraint_objects = ro, pdb_interpretation_params = p, log = null_out()) # f = open("intermediate1.pdb","w") # f.write(model.model_as_pdb()) # # Remove lone H # sel_h = model.get_hd_selection() # sel_isolated = model.isolated_atoms_selection() # sel_lone = sel_h & sel_isolated # model = model.select(~sel_lone) # # Only keep H that have been parameterized in riding H procedure sel_h = model.get_hd_selection() model.setup_riding_h_manager(use_ideal_dihedral = True) sel_h_in_para = flex.bool( [bool(x) for x in model.riding_h_manager.h_parameterization]) sel_h_not_in_para = sel_h_in_para.exclusive_or(sel_h) model = model.select(~sel_h_not_in_para) model = exclude_h_on_SS(model = model) model = exclude_h_on_coordinated_S(model = model) # f = open("intermediate2.pdb","w") # f.write(model.model_as_pdb()) # Reset occupancies, ADPs and idealize model.reset_adp_for_hydrogens(scale = adp_scale) model.reset_occupancy_for_hydrogens_simple() model.idealize_h_riding() # return model
def stats(model, prefix, no_ticks=True): # Get rid of H, multi-model, no-protein and single-atom residue models if (model.percent_of_single_atom_residues() > 20): return None sel = model.selection(string="protein") if (sel.count(True) == 0): return None ssr = "protein and not (element H or element D or resname UNX or resname UNK or resname UNL)" sel = model.selection(string=ssr) model = model.select(sel) if (len(model.get_hierarchy().models()) > 1): return None # Add H; this looses CRYST1 ! rr = run_reduce_with_timeout( stdin_lines=model.get_hierarchy().as_pdb_string().splitlines(), file_name=None, parameters="-oh -his -flip -keep -allalt -pen9999 -", override_auto_timeout_with=None) # Create model; this is a single-model pure protein with new H added pdb_inp = iotbx.pdb.input(source_info=None, lines=rr.stdout_lines) model = mmtbx.model.manager(model_input=None, build_grm=True, pdb_hierarchy=pdb_inp.construct_hierarchy(), process_input=True, log=null_out()) box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=model.get_sites_cart(), buffer_layer=5) model.set_sites_cart(box.sites_cart) model._crystal_symmetry = box.crystal_symmetry() # N = 10 SS = get_ss_selections(hierarchy=model.get_hierarchy()) HB_all = find( model=model.select(flex.bool(model.size(), True)), a_DHA_cutoff=90).get_params_as_arrays(replace_with_empty_threshold=N) HB_alpha = find( model=model.select(SS.both.h_sel), a_DHA_cutoff=90).get_params_as_arrays(replace_with_empty_threshold=N) HB_beta = find( model=model.select(SS.both.s_sel), a_DHA_cutoff=90).get_params_as_arrays(replace_with_empty_threshold=N) print(HB_all.d_HA.size()) result_dict = {} result_dict["all"] = HB_all result_dict["alpha"] = HB_alpha result_dict["beta"] = HB_beta # result_dict["loop"] = get_selected(sel=loop_sel) # Load histograms for reference high-resolution d_HA and a_DHA pkl_fn = libtbx.env.find_in_repositories( relative_path="mmtbx") + "/nci/d_HA_and_a_DHA_high_res.pkl" assert os.path.isfile(pkl_fn) ref = easy_pickle.load(pkl_fn) # import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 10)) kwargs = dict(histtype='bar', bins=20, range=[1.6, 3.0], alpha=.8) for j, it in enumerate([["alpha", 1], ["beta", 3], ["all", 5]]): key, i = it ax = plt.subplot(int("32%d" % i)) if (no_ticks): #ax.set_xticks([]) ax.set_yticks([]) if (j in [0, 1]): ax.tick_params(bottom=False) ax.set_xticklabels([]) ax.tick_params(axis="x", labelsize=12) ax.tick_params(axis="y", labelsize=12, left=False, pad=-2) ax.text(0.98, 0.92, key, size=12, horizontalalignment='right', transform=ax.transAxes) HB = result_dict[key] if HB is None: continue w1 = np.ones_like(HB.d_HA) / HB.d_HA.size() ax.hist(HB.d_HA, color="orangered", weights=w1, rwidth=0.3, **kwargs) # start, end1, end2 = 0, max(ref.distances[key].vals), \ round(max(ref.distances[key].vals),2) if (not no_ticks): plt.yticks([0.01, end1], ["0", end2], visible=True, rotation="horizontal") if (key == "alpha"): plt.ylim(0, end2 + 0.02) elif (key == "beta"): plt.ylim(0, end2 + 0.02) elif (key == "all"): plt.ylim(0, end2 + 0.02) else: assert 0 # if (j == 0): ax.set_title("Distance", size=15) bins = list(flex.double(ref.distances[key].bins)) ax.bar(bins, ref.distances[key].vals, alpha=.3, width=0.07) # kwargs = dict(histtype='bar', bins=20, range=[90, 180], alpha=.8) for j, it in enumerate([["alpha", 2], ["beta", 4], ["all", 6]]): key, i = it ax = plt.subplot(int("32%d" % i)) if (j in [0, 1]): ax.tick_params(bottom=False) ax.set_xticklabels([]) if (no_ticks): #ax.set_xticks([]) ax.set_yticks([]) ax.tick_params(axis="x", labelsize=12) ax.tick_params(axis="y", labelsize=12, left=False, pad=-2) ax.text(0.98, 0.92, key, size=12, horizontalalignment='right', transform=ax.transAxes) ax.text(0.98, 0.92, key, size=12, horizontalalignment='right', transform=ax.transAxes) #if(j in [0,1]): ax.plot_params(bottom=False) HB = result_dict[key] if HB is None: continue w1 = np.ones_like(HB.a_DHA) / HB.a_DHA.size() ax.hist(HB.a_DHA, color="orangered", weights=w1, rwidth=0.3, **kwargs) # start, end1, end2 = 0, max(ref.angles[key].vals), \ round(max(ref.angles[key].vals),2) if (not no_ticks): plt.yticks([0.01, end1], ["0", end2], visible=True, rotation="horizontal") if (key == "alpha"): plt.ylim(0, end2 + 0.02) elif (key == "beta"): plt.ylim(0, end2 + 0.02) elif (key == "all"): plt.ylim(0, end2 + 0.02) else: assert 0 # if (j == 0): ax.set_title("Angle", size=15) ax.bar(ref.angles[key].bins, ref.angles[key].vals, width=4.5, alpha=.3) plt.subplots_adjust(wspace=0.12, hspace=0.025) if (no_ticks): plt.subplots_adjust(wspace=0.025, hspace=0.025) #fig.savefig("%s.png"%prefix, dpi=1000) fig.savefig("%s.pdf" % prefix)