Beispiel #1
0
def get_ligand_buffer_models(model, qmr, verbose=False, write_steps=False):
    from cctbx.maptbx.box import shift_and_box_model
    if WRITE_STEPS_GLOBAL: write_steps = True
    ligand_model = select_and_reindex(model, qmr.selection)
    #
    # check for to sparse selections like a ligand in two monomers
    #
    if len(ligand_model.get_atoms()) == 0:
        raise Sorry('selection "%s" results in empty model' % qmr.selection)
    if write_steps: write_pdb_file(ligand_model, 'model_selection.pdb', None)
    assert qmr.selection.find('within') == -1
    buffer_selection_string = 'residues_within(%s, %s)' % (qmr.buffer,
                                                           qmr.selection)
    buffer_model = select_and_reindex(model, buffer_selection_string)
    buffer_model.remove_alternative_conformations(
        always_keep_one_conformer=True)
    for residue_group in buffer_model.get_hierarchy().residue_groups():
        if (residue_group.atom_groups_size() != 1):
            raise Sorry("Not implemented: cannot run QI on buffer " +
                        "molecules with alternate conformations")
    if write_steps: write_pdb_file(buffer_model, 'pre_super_cell.pdb', None)
    super_cell_and_prune(buffer_model,
                         ligand_model,
                         qmr.buffer,
                         write_steps=write_steps)
    buffer_model_p1 = shift_and_box_model(model=buffer_model)
    for atom1, atom2 in zip(buffer_model_p1.get_atoms(),
                            buffer_model.get_atoms()):
        atom1.tmp = atom2.tmp
    for atom1 in buffer_model.get_atoms():
        for atom2 in ligand_model.get_atoms():
            if atom1.id_str() == atom2.id_str():
                atom2.xyz = atom1.xyz
                break
    buffer_model = buffer_model_p1
    buffer_model.unset_restraints_manager()
    buffer_model.log = null_out()
    buffer_model.process(make_restraints=True)
    if write_steps: write_pdb_file(buffer_model, 'pre_add_terminii.pdb', None)
    add_hydrogen_atoms_to_model(buffer_model,
                                use_capping_hydrogens=qmr.capping_groups)
    buffer_model.unset_restraints_manager()
    buffer_model.process(make_restraints=True)
    if write_steps: write_pdb_file(buffer_model, 'post_add_terminii.pdb', None)
    ligand_atoms = ligand_model.get_atoms()
    buffer_atoms = buffer_model.get_atoms()
    for atom1 in ligand_atoms:
        for atom2 in buffer_atoms:
            if atom1.id_str() == atom2.id_str():
                break
        else:
            raise Sorry('''Bug alert
  Atom %s from ligand does not appear in buffer. Contact Phenix with input files.
  ''' % atom1.quote())
    use_neutron_distances_in_model_in_place(ligand_model)
    use_neutron_distances_in_model_in_place(buffer_model)
    if write_steps:
        write_pdb_file(buffer_model, 'post_neutron_cluster.pdb', None)
        write_pdb_file(ligand_model, 'post_neutron_ligand.pdb', None)
    return ligand_model, buffer_model
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 run(self):
        #
        self.model = self.data_manager.get_model()

        # shift_and_box_model creates a new model object, so the format needs to
        # be obtained here
        if self.params.output.format == 'Auto':
            if self.model.input_model_format_pdb():
                self.params.output.format = 'pdb'
            elif self.model.input_model_format_cif():
                self.params.output.format = 'cif'

        self.model = shift_and_box_model(model=self.model,
                                         box_cushion=self.params.buffer_layer)

        # Get output filename if not provided
        fn = self.data_manager.get_default_model_name()
        basename = os.path.splitext(os.path.basename(fn))[0]
        if self.params.output.prefix is None:
            self.params.output.prefix = basename
            self.data_manager.set_default_output_filename(
                self.get_default_output_filename())

        # save output
        output_fn = self.data_manager.write_model_file(
            self.model, format=self.params.output.format)
        print('Created file', output_fn, file=self.logger)
Beispiel #4
0
def get_map_model_managers():
  # Set up source data
  from iotbx.map_model_manager import map_model_manager
  mmm = map_model_manager()
  mmm.generate_map(wrapping=True)
  second_model=mmm.model().deep_copy()
  mmm.box_all_maps_around_model_and_shift_origin()
  mmm.map_manager().set_wrapping(False)
  mmm.set_log(sys.stdout)

  #now get a second one

  from scitbx import matrix
  r=matrix.sqr((-0.8090,0.5878,0.0000,
   -0.5878,-0.8090,-0.0000,
   0.0000,-0.0000,1.0000,))
  t = matrix.col((100,0,0))
  new_sites_cart = r.elems*mmm.model().get_sites_cart() + t.elems
  second_model.set_sites_cart(new_sites_cart)
  from cctbx.maptbx.box import shift_and_box_model
  second_model = shift_and_box_model(second_model)

  second_mmm = map_model_manager(model=second_model)
  second_mmm.generate_map(model=second_model,wrapping=True)
  second_mmm.box_all_maps_around_model_and_shift_origin(box_cushion=10)
  second_mmm.map_manager().set_wrapping(False)
  second_mmm.set_log(sys.stdout)

  print(mmm.model().get_sites_cart()[0])
  print(second_mmm.model().get_sites_cart()[0])
  return mmm, second_mmm
def get_ligand_buffer_models(model, qmr, verbose=False, write_steps=False):
  from cctbx.maptbx.box import shift_and_box_model
  ligand_model = select_and_reindex(model, qmr.selection)
  if len(ligand_model.get_atoms())==0:
    raise Sorry('selection "%s" results in empty model' % qmr.selection)
  buffer_selection_string = 'residues_within(%s, %s)' % (qmr.buffer,
                                                         qmr.selection)
  buffer_model = select_and_reindex(model, buffer_selection_string)
  buffer_model.remove_alternative_conformations(always_keep_one_conformer=True)
  for residue_group in buffer_model.get_hierarchy().residue_groups():
    if (residue_group.atom_groups_size() != 1):
      raise Sorry("Not implemented: cannot run QI on buffer "+
                  "molecules with alternate conformations")
  if write_steps: write_pdb_file(buffer_model, 'pre_super_cell.pdb', None)
  super_cell_and_prune(buffer_model, ligand_model, qmr.buffer, write_steps=write_steps)
  buffer_model_p1 = shift_and_box_model(model=buffer_model)
  for atom1, atom2 in zip(buffer_model_p1.get_atoms(), buffer_model.get_atoms()):
    atom1.tmp=atom2.tmp
  buffer_model = buffer_model_p1
  buffer_model.unset_restraints_manager()
  buffer_model.log=null_out()
  buffer_model.process(make_restraints=True)
  if write_steps: write_pdb_file(buffer_model, 'pre_add_terminii.pdb', None)
  add_hydrogen_atoms_to_model(buffer_model, use_capping_hydrogens=qmr.capping_groups)
  buffer_model.unset_restraints_manager()
  buffer_model.process(make_restraints=True)
  return ligand_model, buffer_model
Beispiel #6
0
    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 test_2():
  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)
  model.search_for_ncs()
  model.setup_ncs_constraints_groups(filter_groups=True)
  assert model.ncs_constraints_present()
  assert not model.can_be_unique_with_biomt()
  assert "" == model.model_as_mmcif(try_unique_with_biomt=True)
Beispiel #8
0
    def run(self):
        models = []
        for model_name in self.data_manager.get_model_names():
            models.append(self.data_manager.get_model(model_name))

        # model = self.data_manager.get_model()
        self.inp_fn = os.path.basename(
            self.data_manager.get_default_model_name())[:-4]
        self.rama_z = rama_z.rama_z(models=models, log=self.logger)
        if len(models) == 1:
            model = models[0]
            cs = model.crystal_symmetry()
            if cs is None:
                model = shift_and_box_model(model)
            self._write_plots_if_needed(model,
                                        label='whole',
                                        type_of_plot='whole')
            helix_sel, sheet_sel, loop_sel = self.rama_z.get_ss_selections()
            if model.get_hierarchy().models_size() != 1:
                print(
                    "Warning! Outputting partial models and plots are not supported \
  for multi-model files",
                    file=self.logger)
            else:
                for sel, label in [(helix_sel, "helix"), (sheet_sel, "sheet"),
                                   (loop_sel, "loop")]:
                    selected_model = model.select(sel)
                    if self.params.write_HSL_models:
                        pdb_str = selected_model.model_as_pdb()
                        fn = "%s" % self.get_default_output_filename(
                            prefix='%s_' % self.inp_fn,
                            suffix=label,
                            serial=Auto)
                        print("Writing out partial model: %s" % fn,
                              file=self.logger)
                        self.data_manager.write_model_file(selected_model,
                                                           filename=fn)
                    self._write_plots_if_needed(selected_model,
                                                label,
                                                type_of_plot='HSL')
        result = self.get_results()
        res_info = self.rama_z.get_detailed_values()
        print("Individual residues info:", file=self.logger)
        print("Residue name, type, SS, (phi, psi), Z", file=self.logger)
        for i in res_info:
            print('%4s %10s %1s (%7.2f, %7.2f) %7.4f' %
                  (i[2], res_type_labels[i[1]], i[3], i[4], i[5], i[6]),
                  file=self.logger)

        print(result.as_string(prefix=""), file=self.logger)
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)
Beispiel #10
0
    def __init__(
            self,
            model,
            mmm=None,
            take_ncs_from_map=True,
            solvent_sel_str=solvent_sel_str,
            solvent_chain_mode="nearest",
            write_debug=False,
            write_debug_dir=os.getcwd(),
            out=None,
    ):
        if model.crystal_symmetry() is None:
            model = shift_and_box_model(model, shift_model=False)
        self.model = model
        self.mmm = mmm
        self.solvent_sel_str = solvent_sel_str
        assert solvent_chain_mode in ["nearest", "unique"]
        self.solvent_chain_mode = solvent_chain_mode
        self.write_debug = write_debug
        self.write_debug_dir = write_debug_dir
        self.out = out
        self.devnull = open(os.devnull, "w")

        # set up ncs relationships
        self.ncs_input_obj, self.ncs_group = self.generate_ncs_group()

        if self.assert_ncs_covers_all(self.model, self.ncs_group) is False:
            print(
                "NCS selection does not cover all atoms, will try to add solvent "
                "to the nearest non-solvent chain")
            self.model = self.solvent_to_nearest_chain(self.model)
            self.ncs_group = self.generate_ncs_group()
            assert self.assert_ncs_covers_all(self.model, self.ncs_group)

        # modify ncs_group transformations based on map
        if take_ncs_from_map and mmm is None:
            print(
                "\nNo map model manager. Cannot take symmetry from map...",
                file=self.out,
            )
        elif take_ncs_from_map:
            print("\nSearching for symmetry in map...", file=self.out)
            self.ncs_group = self.take_ncs_from_map(self.mmm, self.ncs_group)
Beispiel #11
0
    def generate_mock_rms_fc_list(self,
                                  n_bins=None,
                                  d_min=None,
                                  map_model_manager=None,
                                  model=None,
                                  out=null_out()):
        mmm = map_model_manager
        if not model:
            from cctbx.development.create_models_or_maps import generate_model
            model = generate_model(n_residues=100, b_iso=0, log=null_out())
        # shift the model and return it with new crystal_symmetry
        from cctbx.maptbx.box import shift_and_box_model
        model = shift_and_box_model(model=model,
                                    crystal_symmetry=mmm.crystal_symmetry())
        model.set_shift_cart((0, 0, 0))
        model = mmm.remove_model_outside_map(model=model,
                                             boundary=0,
                                             return_as_new_model=True)
        map_id_model_map = 'map_for_mock_data'
        out_sav = mmm.log
        mmm.set_log(null_out())
        mmm.generate_map(model=model,
                         gridding=mmm.get_any_map_manager().map_data().all(),
                         d_min=d_min,
                         map_id=map_id_model_map)

        map_coeffs = mmm.get_map_manager_by_id(
            map_id_model_map).map_as_fourier_coefficients(d_min=d_min)
        mmm.remove_map_manager_by_id(map_id=map_id_model_map)
        mmm.set_log(out_sav)
        f_array = get_map_coeffs_as_fp_phi(map_coeffs,
                                           n_bins=n_bins,
                                           d_min=d_min).f_array
        rms_fc_list = flex.double()
        for i_bin in f_array.binner().range_used():
            sel = f_array.binner().selection(i_bin)
            fc = map_coeffs.select(sel)
            f_array_fc = map_coeffs_to_fp(fc)
            rms_fc = f_array_fc.data().norm()
            rms_fc_list.append(rms_fc)
        self.rms_fc_list = rms_fc_list
Beispiel #12
0
    def generate_mock_rms_fc_list(self,
                                  n_bins=None,
                                  d_min=None,
                                  map_model_manager=None,
                                  model=None,
                                  k_sol=None,
                                  b_sol=None,
                                  n_bins_use=None,
                                  out=null_out()):
        mmm = map_model_manager
        if not model:
            from cctbx.development.create_models_or_maps import generate_model
            model = generate_model(n_residues=100, b_iso=0, log=null_out())
        # shift the model and return it with new crystal_symmetry
        from cctbx.maptbx.box import shift_and_box_model
        model = shift_and_box_model(model=model,
                                    crystal_symmetry=mmm.crystal_symmetry())
        model.set_shift_cart((0, 0, 0))
        model = mmm.remove_model_outside_map(model=model,
                                             boundary=0,
                                             return_as_new_model=True)
        map_id_model_map = 'map_for_mock_data'
        out_sav = mmm.log
        mmm.set_log(null_out())
        mmm.generate_map(model=model,
                         gridding=mmm.get_any_map_manager().map_data().all(),
                         d_min=d_min,
                         k_sol=k_sol,
                         b_sol=b_sol,
                         map_id=map_id_model_map)

        self.rms_fc_list = mmm.get_rms_f_list(map_id=map_id_model_map,
                                              d_min=d_min,
                                              n_bins=n_bins).rms_f_list
        self.n_bins_use = n_bins_use  # just save it
        mmm.remove_map_manager_by_id(map_id=map_id_model_map)
        mmm.set_log(out_sav)
def RunProbeTests(inFileName):

    #========================================================================
    # Call the test functions for the libraries we test.

    ret = probeext.DotSpheres_test()
    assert len(ret) == 0, "DotSpheres_test() failed: " + ret

    ret = probeext.SpatialQuery_test()
    assert len(ret) == 0, "SpatialQuery_test() failed: " + ret

    ret = probeext.Scoring_test()
    assert len(ret) == 0, "Scoring_test() failed: " + ret

    AtomTypes.Test()
    Helpers.Test()

    #========================================================================
    # Now ensure that we can use the C++-wrapped classes as intended to make sure
    # that the wrapping code or parameters have not changed.

    #========================================================================
    # Make sure we can get at the DotSphere objects and their methods
    cache = probeext.DotSphereCache(10)
    sphere1 = cache.get_sphere(1)
    dots = sphere1.dots()

    #========================================================================
    # Make sure we can fill in an ExtraAtomInfoList and pass it to scoring
    # Generate an example data model with a small molecule in it unless we've
    # been given a file name to open.
    if inFileName is not None and len(inFileName) > 0:
        # Read a model from a file using the DataManager
        dm = DataManager()
        dm.process_model_file(inFileName)
        model = dm.get_model(inFileName)
    else:
        # Generate a small-molecule model using the map model manager
        mmm = map_model_manager(
        )  #   get an initialized instance of the map_model_manager
        mmm.generate_map(
        )  #   get a model from a generated small library model and calculate a map for it
        model = mmm.model()  #   get the model

    # Fix up bogus unit cell when it occurs by checking crystal symmetry.
    cs = model.crystal_symmetry()
    if (cs is None) or (cs.unit_cell() is None):
        model = shift_and_box_model(model=model)

    # Get the list of all atoms in the model
    atoms = model.get_atoms()

    # Get the bonding information we'll need to exclude our bonded neighbors.
    try:
        p = mmtbx.model.manager.get_default_pdb_interpretation_params()
        model.process(make_restraints=True,
                      pdb_interpretation_params=p)  # make restraints
        geometry = model.get_restraints_manager().geometry
        sites_cart = model.get_sites_cart()  # cartesian coordinates
        bond_proxies_simple, asu = \
            geometry.get_all_bond_proxies(sites_cart = sites_cart)
    except Exception as e:
        raise Exception("Could not get bonding information for input file: " +
                        str(e))
    bondedNeighbors = Helpers.getBondedNeighborLists(atoms,
                                                     bond_proxies_simple)

    # Traverse the hierarchy and look up the extra data to be filled in.
    class philLike:
        def __init__(self, useImplicitHydrogenDistances=False):
            self.implicit_hydrogens = useImplicitHydrogenDistances
            self.set_polar_hydrogen_radius = True

    ret = Helpers.getExtraAtomInfo(model,
                                   bondedNeighbors,
                                   useNeutronDistances=False,
                                   probePhil=philLike(False))
    extra = ret.extraAtomInfo

    # Construct a SpatialQuery and fill in the atoms.  Ensure that we can make a
    # query within 1000 Angstroms of the origin.
    sq = probeext.SpatialQuery(atoms)
    nb = sq.neighbors((0, 0, 0), 0, 1000)

    # Construct a DotScorer object.
    # Find the radius of each atom in the structure and construct dot spheres for
    # them. Find the atoms that are bonded to them and add them to an excluded list.
    # Then compute the score for each of them and report the summed score over the
    # whole molecule the way that Reduce will.
    ds = probeext.DotScorer(extra)
    total = 0
    badBumpTotal = 0
    for a in atoms:
        rad = extra.getMappingFor(a).vdwRadius
        assert rad > 0, "Invalid radius for atom look-up: " + a.name + " rad = " + str(
            rad)
        sphere = cache.get_sphere(rad)

        # Excluded atoms that are bonded to me or to one of my neightbors.
        # It has the side effect of excluding myself if I have any neighbors.
        # Construct as a set to avoid duplicates.
        exclude = set()
        for n in bondedNeighbors[a]:
            exclude.add(n)
            for n2 in bondedNeighbors[n]:
                exclude.add(n2)
        exclude = list(exclude)

        dots = sphere.dots()
        res = ds.score_dots(a, 1.0, sq, rad * 3, 0.25, exclude, sphere.dots(),
                            sphere.density(), False)
        total += res.totalScore()
        if res.hasBadBump:
            badBumpTotal += 1

    # Test calling the single-dot checking code as will be used by Probe to make sure
    # all of the Python linkage is working
    dotOffset = [1, 0, 0]
    check = ds.check_dot(atoms[0], dotOffset, 1, atoms, [atoms[0]])
    overlapType = check.overlapType

    # Test calling the interaction_type method to be sure Python linkage is working
    interactionType = ds.interaction_type(check.overlapType, check.gap)

    #========================================================================
    # Regression test a Probe2 run against a snippet of a file, comparing the output
    # to the output generated by a previous version of the program.  If there are
    # differences, report that this is the case and recommend verifying that the
    # differences are intentional and replacing the stored output.
    data_dir = libtbx.env.under_dist(module_name="mmtbx",
                                     path=os.path.join("regression", "pdbs"),
                                     test=os.path.isdir)
    model_file = os.path.join(data_dir, 'Fe_1brf_snip_reduced.pdb')
    kin_dir = libtbx.env.under_dist(module_name="mmtbx",
                                    path=os.path.join("regression", "kins"),
                                    test=os.path.isdir)
    kin_file = os.path.join(kin_dir, 'Fe_1brf_snip_reduced.kin')
    temp_file = os.path.join(tempfile._get_default_tempdir(),
                             next(tempfile._get_candidate_names()) + ".kin")
    try:
        my_env = os.environ
        exe_name = 'mmtbx.probe2'
        if platform.system() == 'Windows':
            exe_name += '.bat'
        if subprocess.check_call([
                exe_name, 'source_selection="all"', 'approach=self',
                'output.separate_worse_clashes=True', 'output.file_name=' +
                temp_file, 'include_mainchain_mainchain=True',
                'output.add_kinemage_keyword=True', model_file
        ],
                                 env=my_env,
                                 stdout=subprocess.DEVNULL,
                                 stderr=subprocess.DEVNULL):
            raise Exception(
                "Call to subprocess to regression test had nonzero return")
    except Exception as e:
        raise Exception("Could not call subprocess to do regression test: " +
                        str(e))
    with open(temp_file) as ft:
        ft_text = ft.readlines()
    with open(kin_file) as fk:
        fk_text = fk.readlines()
    instructions = (
        "  Use KiNG or another program to see what changed and then determine if the "
        + "differences are expected.  If so, replace " + kin_file +
        " with the new file.")
    if len(ft_text) != len(fk_text):
        raise Exception("Different number of lines in " + temp_file + " and " +
                        kin_file + instructions)
    for i in range(3, len(ft_text)):
        if ft_text[i] != fk_text[i]:
            print('Line', i, 'from each file:')
            print(ft_text[i])
            print(fk_text[i])
            raise Exception("Line " + str(i) + " in " + temp_file + " and " +
                            kin_file + "differ." + instructions)
Beispiel #14
0
  def run(self):

    # String describing the run that will be output to the specified file.
    outString = 'reduce2 v.{}, run {}\n'.format(version, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    for a in sys.argv:
      outString += ' {}'.format(a)
    outString += '\n'

    make_sub_header('Loading Model', out=self.logger)

    # Get our model.
    self.model = self.data_manager.get_model()

    # Fix up bogus unit cell when it occurs by checking crystal symmetry.
    cs = self.model.crystal_symmetry()
    if (cs is None) or (cs.unit_cell() is None):
      self.model = shift_and_box_model(model = self.model)

    if self.params.approach == 'add':
      # Add Hydrogens to the model
      make_sub_header('Adding Hydrogens', out=self.logger)
      startAdd = work_clock()
      reduce_add_h_obj = reduce_hydrogen.place_hydrogens(
        model = self.model,
        n_terminal_charge=self.params.n_terminal_charge,
        stop_for_unknowns=True
      )
      reduce_add_h_obj.run()
      self.model = reduce_add_h_obj.get_model()
      doneAdd = work_clock()

      # Interpret the model after shifting and adding Hydrogens to it so that
      # all of the needed fields are filled in when we use them below.
      # @todo Remove this once place_hydrogens() does all the interpretation we need.
      make_sub_header('Interpreting Hydrogenated Model', out=self.logger)
      startInt = work_clock()
      self.model.get_hierarchy().sort_atoms_in_place()
      self.model.get_hierarchy().atoms().reset_serial()
      p = mmtbx.model.manager.get_default_pdb_interpretation_params()
      p.pdb_interpretation.allow_polymer_cross_special_position=True
      p.pdb_interpretation.clash_guard.nonbonded_distance_threshold=None
      p.pdb_interpretation.use_neutron_distances = self.params.use_neutron_distances
      p.pdb_interpretation.proceed_with_excessive_length_bonds=True
      #p.pdb_interpretation.sort_atoms=True
      self.model.process(make_restraints=True, pdb_interpretation_params=p) # make restraints
      doneInt = work_clock()

      make_sub_header('Optimizing', out=self.logger)
      startOpt = work_clock()
      Optimizers.probePhil = self.params.probe
      opt = Optimizers.FastOptimizer(self.params.add_flip_movers, self.model, probeRadius=0.25,
        altID=self.params.alt_id, preferenceMagnitude=self.params.preference_magnitude)
      doneOpt = work_clock()
      outString += opt.getInfo()
      outString += 'Time to Add Hydrogen = '+str(doneAdd-startAdd)+'\n'
      outString += 'Time to Interpret = '+str(doneInt-startInt)+'\n'
      outString += 'Time to Optimize = '+str(doneOpt-startOpt)+'\n'

    else: # Removing Hydrogens from the model rather than adding them.
      make_sub_header('Removing Hydrogens', out=self.logger)
      sel = self.model.selection("element H")
      for a in self.model.get_atoms():
        if sel[a.i_seq]:
          a.parent().remove_atom(a)

    # Re-process the model because we have removed some atoms that were previously
    # bonded.  Don't make restraints during the reprocessing.
    # We had to do this to keep from crashing on a call to pair_proxies when generating
    # mmCIF files, so we always do it for safety.
    self.model.process(make_restraints=False, pdb_interpretation_params=p)

    make_sub_header('Writing output', out=self.logger)

    # Write the description output to the specified file.
    of = open(self.params.output.description_file_name,"w")
    of.write(outString)
    of.close()

    # Determine whether to write a PDB or CIF file and write the appropriate text output.
    # Then determine the output file name and write it there.
    if str(self.params.output.suffix).lower() == "pdb":
      txt = self.model.model_as_pdb()
      suffix = ".pdb"
    else:
      txt = self.model.model_as_mmcif()
      suffix = ".cif"
    if self.params.output.model_file_base_name is not None:
      base = self.params.output.model_file_base_name
    else:
      file_name = self.data_manager.get_model_names()[0]
      base = os.path.splitext(os.path.basename(file_name))[0] + "_reduced"
    fullname = base+suffix
    with open(fullname, 'w') as f:
      f.write(txt)

    print('Wrote',fullname,'and',self.params.output.description_file_name, file = self.logger)

    # Report profiling info if we've been asked to in the Phil parameters
    if self.params.profile:
      print('Profile results:')
      import pstats
      profile_params = {'sort_by': 'time', 'num_entries': 20}
      self._pr.disable()
      ps = pstats.Stats(self._pr).sort_stats(profile_params['sort_by'])
      ps.print_stats(profile_params['num_entries'])
Beispiel #15
0
    def run(self):
        '''
    Function that places 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 = self.model.crystal_symmetry()
        if (cs is None) or (cs.unit_cell() is None):
            self.model = shift_and_box_model(model=self.model)
            model_has_bogus_cs = True

        # Remove existing H if requested
        self.n_H_initial = self.model.get_hd_selection().count(True)
        if not self.keep_existing_H:
            self.model = self.model.select(~self.model.get_hd_selection())

        t0 = time.time()
        # Add H atoms and place them at center of coordinates
        pdb_hierarchy = self.add_missing_H_atoms_at_bogus_position()
        if print_time:
            print("add_missing_H_atoms_at_bogus_position:",
                  round(time.time() - t0, 2))

        #print(pdb_hierarchy.composition().n_hd)

#    f = open("intermediate1.pdb","w")
#    f.write(self.model.model_as_pdb())

# place N-terminal propeller hydrogens
#    if self.n_terminal_charge != 'no_charge':
#      for m in pdb_hierarchy.models():
#        for chain in m.chains():
#          rgs = chain.residue_groups()[0]
#          # by default, place NH3 only at residue with resseq 1
#          if (self.n_terminal_charge == 'residue_one' and rgs.resseq_as_int() != 1):
#            continue
#          elif (self.n_terminal_charge == 'first_in_chain'):
#            pass
#          for ag in rgs.atom_groups():
#            if (get_class(name=ag.resname) in
#                ['common_amino_acid', 'modified_amino_acid', 'd_amino_acid']):
#              if ag.get_atom('H'):
#                ag.remove_atom(ag.get_atom('H'))
#            rc = add_n_terminal_hydrogens_to_residue_group(rgs)
#            # rc is always empty list?

        pdb_hierarchy.sort_atoms_in_place()
        pdb_hierarchy.atoms().reset_serial()
        #    f = open("intermediate2.pdb","w")
        #    f.write(self.model.model_as_pdb())

        p = mmtbx.model.manager.get_default_pdb_interpretation_params()
        p.pdb_interpretation.clash_guard.nonbonded_distance_threshold = None
        p.pdb_interpretation.use_neutron_distances = self.use_neutron_distances
        p.pdb_interpretation.proceed_with_excessive_length_bonds = True
        #p.pdb_interpretation.automatic_linking.link_metals = True

        t0 = time.time()
        #p.pdb_interpretation.restraints_library.cdl=False # XXX this triggers a bug !=360
        ro = self.model.get_restraint_objects()
        self.model = mmtbx.model.manager(
            model_input=None,
            pdb_hierarchy=pdb_hierarchy,
            stop_for_unknowns=self.stop_for_unknowns,
            crystal_symmetry=self.model.crystal_symmetry(),
            restraint_objects=ro,
            log=null_out())
        self.model.process(pdb_interpretation_params=p, make_restraints=True)
        if print_time:
            print("get new model obj and grm:", round(time.time() - t0, 2))

        #f = open("intermediate3.pdb","w")
        #f.write(self.model.model_as_pdb())

        # Only keep H that have been parameterized in riding H procedure
        sel_h = self.model.get_hd_selection()
        if sel_h.count(True) == 0:
            return

        # get rid of isolated H atoms.
        #For example when heavy atom is missing, H needs not to be placed
        sel_isolated = self.model.isolated_atoms_selection()
        self.sel_lone_H = sel_h & sel_isolated
        self.model = self.model.select(~self.sel_lone_H)

        t0 = time.time()
        # get riding H manager --> parameterize all H atoms
        sel_h = self.model.get_hd_selection()
        self.model.setup_riding_h_manager(use_ideal_dihedral=True)
        riding_h_manager = self.model.riding_h_manager
        if riding_h_manager is None:
            return
        sel_h_in_para = flex.bool(
            [bool(x) for x in riding_h_manager.h_parameterization])
        sel_h_not_in_para = sel_h_in_para.exclusive_or(sel_h)
        self.site_labels_no_para = [
            atom.id_str().replace('pdb=', '').replace('"', '') for atom in
            self.model.get_hierarchy().atoms().select(sel_h_not_in_para)
        ]
        #
        self.model = self.model.select(~sel_h_not_in_para)
        if print_time:
            print("set up riding H manager and some cleanup:",
                  round(time.time() - t0, 2))

    #  f = open("intermediate4.pdb","w")
    #  f.write(model.model_as_pdb())

        if self.validate_e:
            t0 = time.time()
            self.validate_electrons()
            if print_time:
                print("validate electrons:", round(time.time() - t0, 2))

        t0 = time.time()
        # Reset occupancies, ADPs and idealize H atom positions
        self.model.reset_adp_for_hydrogens(scale=self.adp_scale)
        self.model.reset_occupancy_for_hydrogens_simple()
        self.model.idealize_h_riding()
        if print_time:
            print("reset adp, occ; idealize:", round(time.time() - t0, 2))

        t0 = time.time()
        self.exclude_H_on_links()
        if print_time:
            print("all links:", round(time.time() - t0, 2))

        # place N-terminal propeller hydrogens
        if self.n_terminal_charge != 'no_charge':
            hierarchy = self.model.get_hierarchy()
            for m in hierarchy.models():
                for chain in m.chains():
                    rgs = chain.residue_groups()[0]
                    # by default, place NH3 only at residue with resseq 1
                    if (self.n_terminal_charge == 'residue_one'
                            and rgs.resseq_as_int() != 1):
                        continue
                    elif (self.n_terminal_charge == 'first_in_chain'):
                        pass
                    add_charge = True
                    for ag in rgs.atom_groups():
                        if (get_class(name=ag.resname) in [
                                'common_amino_acid', 'modified_amino_acid',
                                'd_amino_acid'
                        ]):
                            if ag.get_atom('N'):
                                N = ag.get_atom('N')
                                if N.i_seq in self.exclusion_iseqs:
                                    add_charge = False
                            if ag.get_atom('H'):
                                H = ag.get_atom('H')
                                ag.remove_atom(H)
                                H_label = H.id_str().replace('pdb=',
                                                             '').replace(
                                                                 '"', '')
                                if H_label in self.site_labels_no_para:
                                    self.site_labels_no_para.remove(H_label)
                        if add_charge:
                            rc = add_n_terminal_hydrogens_to_residue_group(rgs)
            hierarchy.sort_atoms_in_place()
            hierarchy.atoms().reset_serial()
            self.model = mmtbx.model.manager(
                model_input=None,
                pdb_hierarchy=hierarchy,
                stop_for_unknowns=self.stop_for_unknowns,
                crystal_symmetry=self.model.crystal_symmetry(),
                restraint_objects=ro,
                log=null_out())

        self.n_H_final = self.model.get_hd_selection().count(True)
Beispiel #16
0
def RunProbeTests(inFileName):

    #========================================================================
    # Call the test functions for the libraries we test.

    ret = probeext.DotSpheres_test()
    assert len(ret) == 0, "DotSpheres_test() failed: " + ret

    ret = probeext.SpatialQuery_test()
    assert len(ret) == 0, "SpatialQuery_test() failed: " + ret

    ret = probeext.Scoring_test()
    assert len(ret) == 0, "Scoring_test() failed: " + ret

    AtomTypes.Test()
    Helpers.Test()

    #========================================================================
    # Now ensure that we can use the C++-wrapped classes as intended to make sure
    # that the wrapping code or parameters have not changed.

    #========================================================================
    # Make sure we can get at the DotSphere objects and their methods
    cache = probeext.DotSphereCache(10)
    sphere1 = cache.get_sphere(1)
    dots = sphere1.dots()

    #========================================================================
    # Make sure we can fill in an ExtraAtomInfoList and pass it to scoring
    # Generate an example data model with a small molecule in it
    if inFileName is not None and len(inFileName) > 0:
        # Read a model from a file using the DataManager
        dm = DataManager()
        dm.process_model_file(inFileName)
        model = dm.get_model(inFileName)
    else:
        # Generate a small-molecule model using the map model manager
        mmm = map_model_manager(
        )  #   get an initialized instance of the map_model_manager
        mmm.generate_map(
        )  #   get a model from a generated small library model and calculate a map for it
        model = mmm.model()  #   get the model

    # Fix up bogus unit cell when it occurs by checking crystal symmetry.
    cs = model.crystal_symmetry()
    if (cs is None) or (cs.unit_cell() is None):
        model = shift_and_box_model(model=model)

    # Get the list of all atoms in the model
    atoms = model.get_atoms()

    # Get the bonding information we'll need to exclude our bonded neighbors.
    try:
        p = mmtbx.model.manager.get_default_pdb_interpretation_params()
        model.process(make_restraints=True,
                      pdb_interpretation_params=p)  # make restraints
        geometry = model.get_restraints_manager().geometry
        sites_cart = model.get_sites_cart()  # cartesian coordinates
        bond_proxies_simple, asu = \
            geometry.get_all_bond_proxies(sites_cart = sites_cart)
    except Exception as e:
        raise Exception("Could not get bonding information for input file: " +
                        str(e))
    bondedNeighbors = Helpers.getBondedNeighborLists(atoms,
                                                     bond_proxies_simple)

    # Traverse the hierarchy and look up the extra data to be filled in.
    ret = Helpers.getExtraAtomInfo(model)
    extra = ret.extraAtomInfo

    # Construct a SpatialQuery and fill in the atoms.  Ensure that we can make a
    # query within 1000 Angstroms of the origin.
    sq = probeext.SpatialQuery(atoms)
    nb = sq.neighbors((0, 0, 0), 0, 1000)

    # Construct a DotScorer object.
    # Find the radius of each atom in the structure and construct dot spheres for
    # them. Find the atoms that are bonded to them and add them to an excluded list.
    # Then compute the score for each of them and report the summed score over the
    # whole molecule the way that Reduce will.
    ds = probeext.DotScorer(extra)
    total = 0
    badBumpTotal = 0
    for a in atoms:
        rad = extra.getMappingFor(a).vdwRadius
        assert rad > 0, "Invalid radius for atom look-up: " + a.name + " rad = " + str(
            rad)
        sphere = cache.get_sphere(rad)

        # Excluded atoms that are bonded to me or to one of my neightbors.
        # It has the side effect of excluding myself if I have any neighbors.
        # Construct as a set to avoid duplicates.
        exclude = set()
        for n in bondedNeighbors[a]:
            exclude.add(n)
            for n2 in bondedNeighbors[n]:
                exclude.add(n2)
        exclude = list(exclude)

        dots = sphere.dots()
        res = ds.score_dots(a, 1.0, sq, rad * 3, 0.25, exclude, sphere.dots(),
                            sphere.density(), False)
        total += res.totalScore()
        if res.hasBadBump:
            badBumpTotal += 1

    # Test calling the single-dot checking code as will be used by Probe to make sure
    # all of the Python linkage is working
    dotOffset = [1, 0, 0]
    check = ds.check_dot(atoms[0], dotOffset, 1, atoms, [atoms[0]])
    overlapType = check.overlapType

    # Test calling the interaction_type method to be sure Python linkage is working
    interactionType = ds.interaction_type(check.overlapType, check.gap)
    def run(self):
        '''
    Function that places 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 = self.model.crystal_symmetry()
        if cs is None:
            self.model = shift_and_box_model(model=self.model)
            model_has_bogus_cs = True

        # Remove existing H if requested
        self.n_H_initial = self.model.get_hd_selection().count(True)
        if not self.keep_existing_H:
            self.model = self.model.select(~self.model.get_hd_selection())
        # Add H atoms and place them at center of coordinates
        pdb_hierarchy = self.add_missing_H_atoms_at_bogus_position()

        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 = self.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 = self.model.get_restraint_objects()
        self.model = mmtbx.model.manager(
            model_input=None,
            pdb_hierarchy=pdb_hierarchy,
            build_grm=True,
            stop_for_unknowns=self.stop_for_unknowns,
            crystal_symmetry=self.model.crystal_symmetry(),
            restraint_objects=ro,
            pdb_interpretation_params=p,
            log=null_out())

        #f = open("intermediate1.pdb","w")
        #f.write(self.model.model_as_pdb())

        # Only keep H that have been parameterized in riding H procedure
        sel_h = self.model.get_hd_selection()
        if sel_h.count(True) == 0:
            return

        # get rid of isolated H atoms.
        #For example when heavy atom is missing, H needs not to be placed
        sel_isolated = self.model.isolated_atoms_selection()
        self.sel_lone_H = sel_h & sel_isolated
        self.model = self.model.select(~self.sel_lone_H)

        # get riding H manager --> parameterize all H atoms
        sel_h = self.model.get_hd_selection()
        self.model.setup_riding_h_manager(use_ideal_dihedral=True)
        sel_h_in_para = flex.bool(
            [bool(x) for x in self.model.riding_h_manager.h_parameterization])
        sel_h_not_in_para = sel_h_in_para.exclusive_or(sel_h)
        self.site_labels_no_para = [
            atom.id_str().replace('pdb=', '').replace('"', '') for atom in
            self.model.get_hierarchy().atoms().select(sel_h_not_in_para)
        ]
        #
        self.model = self.model.select(~sel_h_not_in_para)

        self.exclude_H_on_disulfides()
        #self.exclude_h_on_coordinated_S()

        #  f = open("intermediate2.pdb","w")
        #  f.write(model.model_as_pdb())

        # Reset occupancies, ADPs and idealize H atom positions
        self.model.reset_adp_for_hydrogens(scale=self.adp_scale)
        self.model.reset_occupancy_for_hydrogens_simple()
        self.model.idealize_h_riding()

        self.exclude_h_on_coordinated_S()
        #
        self.n_H_final = self.model.get_hd_selection().count(True)
Beispiel #18
0
def generate_model(file_name=None,
                   n_residues=None,
                   start_res=None,
                   b_iso=30,
                   box_cushion=5,
                   space_group_number=1,
                   output_model_file_name=None,
                   shake=None,
                   random_seed=None,
                   log=sys.stdout):
    '''
    generate_model: Simple utility for generating a model for testing purposes.

    This function typically accessed and tested through map_model_manager

     Summary
    -------

    Generate a model from a user-specified file or from some examples available
    in the cctbx.  Cut out specified number of residues, shift to place on
    positive side of origin, optionally set b values to b_iso,
    place in box with buffering of box_cushion on all
    edges, optionally randomly shift (shake) atomic positions by rms of shake A,
    and write out to output_model_file_name and return model object.

    Parameters:

      file_name (string, None):  File containing model (PDB, CIF format)
      n_residues (int, 10):      Number of residues to include
      start_res (int, None):     Starting residue number
      b_iso (float, 30):         B-value (ADP) to use for all atoms
      box_cushion (float, 5):     Buffer (A) around model
      space_group_number (int, 1):  Space group to use
      output_model_file_name (string, None):  File for output model
      shake (float, None):       RMS variation to add (A) in shake
      random_seed (int, None):    Random seed for shake

    Returns:
      model.manager object (model) in a box defined by a crystal_symmetry object

  '''

    # Get the parameters

    space_group_number = int(space_group_number)
    if n_residues is not None:
        n_residues = int(n_residues)
    box_cushion = float(box_cushion)
    if start_res:
        start_res = int(start_res)
    if shake:
        shake = float(shake)
    if random_seed:
        random_seed = int(random_seed)
        import random
        random.seed(random_seed)
        random_seed = random.randint(1, 714717)
        flex.set_random_seed(random_seed)

    # Choose file with coordinates

    if not file_name:
        if not n_residues:
            n_residues = 10  # default
        import libtbx.load_env
        iotbx_regression = os.path.join(
            libtbx.env.find_in_repositories("iotbx"), 'regression')
        if n_residues < 25:
            file_name = os.path.join(iotbx_regression, 'secondary_structure',
                                     '5a63_chainBp.pdb')  # starts at 219
            if not start_res: start_res = 219
        elif n_residues < 167:
            file_name = os.path.join(iotbx_regression, 'secondary_structure',
                                     '3jd6_noh.pdb')  # starts at 58
            if not start_res: start_res = 58
        else:
            file_name = os.path.join(iotbx_regression, 'secondary_structure',
                                     '4a7h_chainC.pdb')  # starts at 9
            if not start_res: start_res = 9
    else:  # have file_name
        if start_res is None:
            start_res = 1
        if not n_residues:
            n_residues = 100000  #  a big number

    # Read in coordinates and cut out the part of the model we want

    from iotbx.data_manager import DataManager

    dm = DataManager(['model'])
    dm.process_model_file(file_name)
    model = dm.get_model(file_name)

    if not model.crystal_symmetry() or not model.crystal_symmetry().unit_cell(
    ):
        from cctbx.maptbx.box import shift_and_box_model
        model = shift_and_box_model(model=model, box_cushion=box_cushion)

    selection = model.selection('resseq %s:%s' %
                                (start_res, start_res + n_residues - 1))
    model = model.select(selection)

    # shift the model and return it with new crystal_symmetry
    from cctbx.maptbx.box import shift_and_box_model
    model = shift_and_box_model(model=model, box_cushion=box_cushion)

    if b_iso is not None:
        b_values = flex.double(model.get_sites_cart().size(), b_iso)
        ph = model.get_hierarchy()
        ph.atoms().set_b(b_values)

    # Optionally shake model
    if shake:
        model = shake_model(model, shake=shake)

    if output_model_file_name:
        f = open(output_model_file_name, 'w')
        print("%s" % (model.model_as_pdb()), file=f)
        f.close()
        print("Writing model with %s residues and b_iso=%s from %s to %s" %
              (n_residues, b_iso, file_name, output_model_file_name),
              file=log)
    else:
        print("Generated model with %s residues and b_iso=%s from %s " %
              (n_residues, b_iso, file_name),
              file=log)
    return model
Beispiel #19
0
  def __init__(self, model, params, log = None):
    self.log = log
    self.params = params
    self.model = model
    self._neutralize_scatterers()
    if not model.crystal_symmetry() or not model.crystal_symmetry().unit_cell():
      # Make it up
      from cctbx.maptbx.box import shift_and_box_model
      model = shift_and_box_model(model, shift_model=False)

    self.pdb_hierarchy = model.get_hierarchy()
    self.crystal_symmetry = model.crystal_symmetry()
    if(self.log is None): self.log = sys.stdout
    self.xray_structure = model.get_xray_structure()
    asc = self.pdb_hierarchy.atom_selection_cache(
        special_position_settings=crystal.special_position_settings(
            crystal_symmetry = self.crystal_symmetry))
    if(self.params.random_seed is not None):
      random.seed(self.params.random_seed)
      flex.set_random_seed(self.params.random_seed)
    self.top_selection = flex.smart_selection(
        flags=flex.bool(self.xray_structure.scatterers().size(), True))
    if(self.params.selection is not None):
      self.top_selection = flex.smart_selection(
        flags=asc.selection(self.params.selection))
    self._rotate_about_axis()
    self._process_adp()
    self._process_sites()
    self._process_occupancies()
    self._put_in_box()
    self._change_of_basis()
    # Up to this point we are done with self.xray_structure
    self.model.set_xray_structure(self.xray_structure)
    self.pdb_hierarchy = self.model.get_hierarchy()
    # Now only manipulations that use self.pdb_hierarchy are done
### segID manipulations
    if (params.set_seg_id_to_chain_id):
      if (params.clear_seg_id):
        raise Sorry("Parameter conflict - set_seg_id_to_chain_id=True and "+
          "clear_seg_id=True.  Please choose only one of these options.")
      for atom in self.pdb_hierarchy.atoms():
        labels = atom.fetch_labels()
        atom.segid = "%-4s" % labels.chain_id
    elif (params.clear_seg_id):
      for atom in self.pdb_hierarchy.atoms():
        atom.segid = "    "
    if(self.params.set_chemical_element_simple_if_necessary or
       self.params.rename_chain_id.old_id or
       self.params.renumber_residues or self.params.increment_resseq or
       self.params.convert_semet_to_met or
       self.params.convert_met_to_semet or
       self.params.set_charge.charge or
       self.params.truncate_to_polyala or
       self.params.truncate_to_polygly or
       self.params.remove_alt_confs or
       self.params.move_waters_last or
       self.params.remove_fraction or
       self.params.keep or
       self.params.remove):
      # del self.xray_structure # it is invalide below this point
      self._set_chemical_element_simple_if_necessary()
      self._rename_chain_id()
      self._renumber_residues()
      self._convert_semet_to_met()
      self._convert_met_to_semet()
      self._set_atomic_charge()
      self._truncate_to_poly_ala()
      self._truncate_to_poly_gly()
      self._remove_alt_confs()
      self._move_waters()
      self._remove_atoms()
      self._apply_keep_remove()
      # Here goes really nasty hack. Never repeat it.
      # It is here because I don't have clear idea about how to handle
      # such dramatic changes in number of atoms etc that just was performed
      # for hierarchy.
      self.pdb_hierarchy.reset_atom_i_seqs()
      self.pdb_hierarchy.atoms_reset_serial()
      self.model._pdb_hierarchy = self.pdb_hierarchy
      self.model._xray_structure = self.pdb_hierarchy.extract_xray_structure(
          crystal_symmetry=self.model.crystal_symmetry())
      self.model._update_atom_selection_cache()
      self.model._update_has_hd()
      self.model.get_hierarchy().atoms().reset_i_seq()
Beispiel #20
0
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