Beispiel #1
0
def generate_perfect_helix(
    rs_values,
    ts_values,
    angular_rs_values,
    radial_eta,
    angular_eta,
    angular_zeta,
    crystal_symmetry,
    n_residues=10,
    residue_code="G",
):
    """
  Compute AEV values for the perfect helix.
  """
    perfect_helix_ph = ssb.secondary_structure_from_sequence(
        ssb.alpha_helix_str, residue_code * n_residues)
    model = mmtbx.model.manager(model_input=None,
                                crystal_symmetry=crystal_symmetry,
                                pdb_hierarchy=perfect_helix_ph,
                                log=null_out())
    model.crystal_symmetry()
    return AEV(
        model=model,
        rs_values=rs_values,
        ts_values=ts_values,
        angular_rs_values=angular_rs_values,
        radial_eta=radial_eta,
        angular_eta=angular_eta,
        angular_zeta=angular_zeta,
    ).get_values()
Beispiel #2
0
def summary(pdb_file=None, pdb_hierarchy=None, crystal_symmetry=None):
    header_info = None
    if (pdb_hierarchy is None):
        assert (pdb_file is not None)
        pdb_in = file_reader.any_file(pdb_file, force_type="pdb")
        pdb_in.assert_file_type("pdb")
        pdb_hierarchy = pdb_in.file_object.hierarchy
        pdb_hierarchy.atoms().reset_i_seq()
        header_info = molprobity.pdb_header_info(pdb_file=pdb_file)
        crystal_symmetry = pdb_in.file_object.crystal_symmetry()
    else:
        assert (pdb_file is None)
    #
    cache = pdb_hierarchy.atom_selection_cache()
    sel = cache.selection('protein')
    pdb_hierarchy = pdb_hierarchy.select(sel)
    #
    model = mmtbx.model.manager(model_input=pdb_hierarchy.as_pdb_input())
    if crystal_symmetry and model.crystal_symmetry() is None:
        model.set_crystal_symmetry(
            crystal_symmetry)  # Somehow pdb_hiearchy lacks cs
    if not model.crystal_symmetry():
        aaa = bbb
    return molprobity.molprobity(model=model,
                                 keep_hydrogens=False,
                                 header_info=header_info).summarize()
Beispiel #3
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)
Beispiel #4
0
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)
Beispiel #5
0
def run(prefix):
    """
  Exercise combined energy and gradients from cluster qm.
  """
    for restraints in ["cctbx", "qm"]:
        if 0:
            print("Using restraints:", restraints)
        result = []
        for clustering in [True, False]:
            if 0:
                print("  clustering", clustering, "-" * 30)
            model = get_model()
            if (restraints == "qm"):
                fq = from_qm(pdb_hierarchy=model.get_hierarchy(),
                             qm_engine_name="mopac",
                             method="PM3",
                             crystal_symmetry=model.crystal_symmetry(),
                             clustering=clustering)
            else:
                fq = from_cctbx(
                    restraints_manager=model.get_restraints_manager())
            if (clustering):
                fm = fragments(
                    working_folder=os.path.split("./ase/tmp_ase.pdb")[0] + "/",
                    clustering_method=betweenness_centrality_clustering,
                    maxnum_residues_in_cluster=8,
                    charge_embedding=False,
                    two_buffers=False,
                    fast_interaction=True,
                    pdb_hierarchy=model.get_hierarchy().deep_copy(
                    ),  # deep copy just in case
                    qm_engine_name="mopac",
                    crystal_symmetry=model.crystal_symmetry())
                fc = from_cluster(restraints_manager=fq,
                                  fragment_manager=fm,
                                  parallel_params=get_master_phil().extract())
            else:
                fc = fq
            energy, gradients = fc.target_and_gradients(
                sites_cart=model.get_sites_cart())
            if (restraints == "qm"):
                energy = energy * (kcal / mol) * (kcal / mol) / Hartree
                gradients = gradients * (kcal / mol) * (kcal / mol) * (Bohr /
                                                                       Hartree)
            gradients = gradients.as_double()
            result.append(gradients.deep_copy())
        #
        diff = flex.abs(result[0] - result[1])
        max_diff = flex.max(diff)
Beispiel #6
0
    def apply_to_model(self, model):
        '''
       Apply boxing to a model that is similar to the one used to generate
       this around_model object

       Changes the model in place
    '''

        assert isinstance(model, mmtbx.model.manager)

        # This one should have similar unit_cell_crystal_symmetry for map and
        #  model and model original_crystal_symmetry should match
        #   self.map_crystal_symmetry_at_initialization

        if model.shift_cart() is None:  # model not yet initialized for shifts
            assert self.map_manager().unit_cell_crystal_symmetry(
            ).is_similar_symmetry(model.crystal_symmetry())

        else:  # model is initialized: should match
            assert model.unit_cell_crystal_symmetry()
            assert self.map_manager().unit_cell_crystal_symmetry(
            ).is_similar_symmetry(model.unit_cell_crystal_symmetry())

        # Shift the model and add self.shift_cart on to whatever shift was there
        model.shift_model_and_set_crystal_symmetry(
            shift_cart=self.shift_cart,  # shift to apply
            crystal_symmetry=self.crystal_symmetry,  # new crystal_symmetry
        )

        # if wrapping is False, check to see if model is outside the box
        if not self.map_manager().wrapping():
            if not model.is_inside_working_cell():
                self._warning_message += "\nWARNING: Model is not entirely "+\
                  "inside working cell and wrapping is False"
        return model
  def run(self):
    model = self.data_manager.get_model()
    self.cif_blocks = list()

    # sequence block
    print ('Creating mmCIF block for sequence', file=self.logger)
    sequence = self.data_manager.get_sequence()
    hierarchy = model._pdb_hierarchy
    seq_block = hierarchy.as_cif_block_with_sequence(
      sequence, crystal_symmetry=model.crystal_symmetry(),
      alignment_params=self.params.sequence_alignment)
    self.cif_blocks.append(seq_block)

    # create additional cif blocks?

    # add cif blocks together
    print ('Creating complete mmCIF', file=self.logger)
    self.cif_model = model.model_as_mmcif(additional_blocks=self.cif_blocks)

    # write output file
    self.output_file = os.path.splitext(
      self.data_manager.get_default_model_name())[0] + '.deposit.cif'
    print ('Writing mmCIF', file=self.logger)
    print ('  Output file = %s' % self.output_file, file=self.logger)
    with open(self.output_file, 'wb') as f:
      f.write(self.cif_model)

    # update data manager for any downstream applications
    pdb_input = iotbx.pdb.input(self.output_file)
    model = mmtbx.model.manager(model_input=pdb_input, log=self.logger)
    self.data_manager.add_model(self.output_file, model)
    self.data_manager.set_default_model(self.output_file)
Beispiel #8
0
def run(maxnum_residues_in_cluster):
  result = []
  for clustering in [True, False]:
    if 0: print("  clustering", clustering, "-"*30)
    model = get_model()
    fq = from_cctbx(restraints_manager = model.get_restraints_manager())
    if(clustering):
      fm = fragments(
       working_folder             = os.path.split("./ase/tmp_ase.pdb")[0]+ "/",
       clustering_method          = betweenness_centrality_clustering,
       maxnum_residues_in_cluster = maxnum_residues_in_cluster,
       altloc_method              = "subtract",
       charge_embedding           = False,
       two_buffers                = False,
       clustering                 = clustering,
       pdb_hierarchy              = model.get_hierarchy().deep_copy(),
       qm_engine_name             = "mopac",
       fast_interaction           = True,
       crystal_symmetry           = model.crystal_symmetry())
    else:
      fc = fq
    fc = from_cluster(
      restraints_manager = fq,
      fragment_manager   = fm,
      parallel_params    = get_master_phil().extract())
    energy, gradients = fc.target_and_gradients(sites_cart=model.get_sites_cart())
    gradients = gradients.as_double()
    result.append(gradients.deep_copy())
  diff = flex.abs(result[0] - result[1])
  max_diff = flex.max(diff)
  #print "  max(diff_grad):", max_diff
  assert max_diff < 1.e-9
Beispiel #9
0
def check_and_set_crystal_symmetry(models=[], map_inps=[], miller_arrays=[]):
    # XXX This should go into a central place
    # XXX Check map gridding here!
    for it in [models, map_inps, miller_arrays]:
        assert isinstance(it, (list, tuple))
    crystal_symmetry = None
    css = []
    all_inputs = models + map_inps + miller_arrays
    for it in all_inputs:
        if (it is not None):
            it = it.crystal_symmetry()
            if (it is None): continue
            if (not [it.unit_cell(), it.space_group()].count(None) in [0, 2]):
                raise Sorry("Inconsistent box (aka crystal symmetry) info.")
            if ([it.unit_cell(), it.space_group()].count(None) == 0):
                css.append(it)
    if (len(css) > 1):
        cs0 = css[0]
        for cs in css[1:]:
            if (not cs0.is_similar_symmetry(cs)):
                raise Sorry(
                    "Box info (aka crystal symmetry) mismatch across inputs.")
    if (len(css) == 0):
        raise Sorry("No box info (aka crystal symmetry) available.")
    crystal_symmetry = css[0]
    for model in models:
        if (model is None): continue
        cs = model.crystal_symmetry()
        if (cs is None or [cs.unit_cell(), cs.space_group()].count(None) == 2):
            model.set_crystal_symmetry_if_undefined(crystal_symmetry)
    if (len(map_inps) > 1):
        m0 = map_inps[0].map_data()
        for m in map_inps[1:]:
            if (m is None): continue
            maptbx.assert_same_gridding(map_1=m0, map_2=m.map_data())
Beispiel #10
0
 def __init__(
     self,
     model,
     rs_values=[2.0, 3.8, 5.2, 5.5, 6.2, 7.0, 8.6, 10.0],
     # probe distances (A) for radial
     radial_eta=4,
     cutoff=8.1,
     # radial cutoff distance
     ts_values=[0.392699, 1.178097, 1.963495, 2.748894],
     # probe angles (rad) for angular
     angular_rs_values=[3.8, 5.2, 5.5, 6.2],
     # probe distances (A) for angular
     angular_eta=4,
     angular_zeta=8,
     # parameters for probe angles
 ):
     self.hierarchy = model.get_hierarchy()
     self.rs_values = rs_values
     self.crystal_symmetry = model.crystal_symmetry()
     self.radial_eta = radial_eta
     self.cutoff = cutoff
     self.ts_values = ts_values
     self.angular_rs_values = angular_rs_values
     self.angular_eta = angular_eta
     self.angular_zeta = angular_zeta
     self.EAEVs = format_class(length_of_radial=len(self.rs_values))
     self.MAEVs = format_class(length_of_radial=len(self.rs_values))
     self.BAEVs = format_class(length_of_radial=len(self.rs_values))
     self.center_atom = None
     self.chain_hierarchy = None
     self.generate_AEV()
Beispiel #11
0
def run(model,
        max_cutoff=4.0,
        min_cutoff=1.5,
        hd=["H", "D"],
        acceptors=["O", "N", "S", "F", "CL"],
        protein_only=True):
    atoms = list(model.get_hierarchy().atoms())
    sites_cart = model.get_sites_cart()
    crystal_symmetry = model.crystal_symmetry()
    fm = crystal_symmetry.unit_cell().fractionalization_matrix()
    om = crystal_symmetry.unit_cell().orthogonalization_matrix()
    pg = get_pair_generator(crystal_symmetry=crystal_symmetry,
                            buffer_thickness=max_cutoff,
                            sites_cart=sites_cart)
    get_class = iotbx.pdb.common_residue_names_get_class
    for p in pg.pair_generator:
        i, j = p.i_seq, p.j_seq
        ei, ej = atoms[i].element, atoms[j].element
        altloc_i = atoms[i].parent().altloc
        altloc_j = atoms[j].parent().altloc
        resseq_i = atoms[i].parent().parent().resseq
        resseq_j = atoms[j].parent().parent().resseq
        # pre-screen candidates begin
        one_is_hd = ei in hd or ej in hd
        other_is_acceptor = ei in acceptors or ej in acceptors
        dist = math.sqrt(p.dist_sq)
        assert dist <= max_cutoff
        is_candidate = one_is_hd and other_is_acceptor and dist >= min_cutoff and \
          altloc_i == altloc_j and resseq_i != resseq_j
        if (protein_only):
            for it in [i, j]:
                resname = atoms[it].parent().resname
                is_candidate &= get_class(name=resname) == "common_amino_acid"
        if (not is_candidate): continue
        # pre-screen candidates end
        rt_mx_i = pg.conn_asu_mappings.get_rt_mx_i(p)
        rt_mx_j = pg.conn_asu_mappings.get_rt_mx_j(p)
        rt_mx_ji = rt_mx_i.inverse().multiply(rt_mx_j)
        print "%5.3f"%math.sqrt(p.dist_sq), \
          "<", atoms[i].parent().resname, resseq_i, ei, atoms[i].name, ">", \
          "<", atoms[j].parent().resname, resseq_j, ej, atoms[j].name, ">", \
          rt_mx_ji, i, j,
        ### re-confirm distance between pairs
        ai = atoms[i]
        aj = atoms[j]
        if (str(rt_mx_ji) == "x,y,z"):
            d = math.sqrt((ai.xyz[0] - aj.xyz[0])**2 +
                          (ai.xyz[1] - aj.xyz[1])**2 +
                          (ai.xyz[2] - aj.xyz[2])**2)
        else:
            t1 = fm * flex.vec3_double([aj.xyz])
            t2 = rt_mx_ji * t1[0]
            t3 = om * flex.vec3_double([t2])
            d = math.sqrt((ai.xyz[0] - t3[0][0])**2 +
                          (ai.xyz[1] - t3[0][1])**2 +
                          (ai.xyz[2] - t3[0][2])**2)
        print "dist=%5.3f" % d
Beispiel #12
0
    def apply_to_model(self, model=None):
        if (model is None):
            # Apply to model already present
            model = self.model
        else:
            # Apply to similar model
            assert model.crystal_symmetry().is_similar_symmetry(
                self.map_manager.crystal_symmetry())

        box_uc = self.crystal_symmetry.unit_cell()
        uc = model.crystal_symmetry().unit_cell()
        sites_frac = model.get_sites_frac()
        sites_frac_new = box_uc.fractionalize(
            uc.orthogonalize(sites_frac + self.shift_frac))
        sites_cart_new = box_uc.orthogonalize(sites_frac_new)
        pdb_hierarchy = model.get_hierarchy().deep_copy()
        pdb_hierarchy.atoms().set_xyz(sites_cart_new)
        return mmtbx.model.manager(model_input=None,
                                   pdb_hierarchy=pdb_hierarchy,
                                   crystal_symmetry=self.crystal_symmetry,
                                   log=null_out())
Beispiel #13
0
def run(args, log=sys.stdout):
    if (len(args) == 0):
        parsed = defaults(log=log)
        parsed.show(prefix="  ", out=log)
        return
    parsed = defaults(log=log)
    processed_args = mmtbx.utils.process_command_line_args(
        args=args, log=sys.stdout, master_params=parsed)
    processed_args.params.show()
    params = processed_args.params.extract()
    if (len(processed_args.pdb_file_names) == 0):
        raise Sorry("No PDB file found.")
    if (len(processed_args.pdb_file_names) > 1):
        raise Sorry("More than one PDB file found.")
    pdb_file_name = processed_args.pdb_file_names[0]
    if (params.f_obs.f_calc.atomic_model.add_hydrogens):
        pdb_file_name_r = os.path.basename(pdb_file_name) + "_reduce"
        # easy_run.go("phenix.reduce %s > %s"% (pdb_file_name, pdb_file_name_r))
        run_reduce_with_timeout(file_name=pdb_file_name,
                                parameters=" > %s" % pdb_file_name_r)
        pdb_file_name = pdb_file_name_r
    pdbi_params = mmtbx.model.manager.get_default_pdb_interpretation_params()
    if (params.f_obs.f_calc.atomic_model.use_ramachandran_plot_restraints):
        pdbi_params.pdb_interpretation.ramachandran_plot_restraints.enabled = True
    model = mmtbx.model.manager(model_input=iotbx.pdb.input(
        file_name=pdb_file_name))
    model.process(make_restraints=True, pdb_interpretation_params=pdbi_params)
    root = iotbx.pdb.hierarchy.root()
    loop_1(params=params,
           root=root,
           xray_structure=model.get_xray_structure(),
           pdb_hierarchy=model.get_hierarchy(),
           restraints_manager=model.get_restraints_manager())
    root.write_pdb_file(
        file_name=params.f_obs.f_calc.atomic_model.output_file_name,
        crystal_symmetry=model.crystal_symmetry())
    simulate_f_obs(root=root,
                   crystal_symmetry=model.crystal_symmetry(),
                   params=params)
Beispiel #14
0
def check_scattering_type_registry():
    pdb_inp = iotbx.pdb.input(source_info=None, lines=pdb_str)
    model = mmtbx.model.manager(model_input=pdb_inp, log=null_out())
    model.process(make_restraints=True)
    xrs1 = model.get_xray_structure()
    xrs2 = model.get_hierarchy().extract_xray_structure(
        crystal_symmetry=model.crystal_symmetry())
    xrs1.scattering_type_registry(table="electron")
    xrs2.scattering_type_registry(table="electron")
    xrs1.scattering_type_registry().show()
    xrs2.scattering_type_registry().show()
    # TODO: Assert to the same value once added
    assert (xrs1.scattering_type_registry().gaussian("O1-") is None)
    assert (xrs2.scattering_type_registry().gaussian("O1-") is None)
Beispiel #15
0
def attribute_water_to_chains(model):
    h = model.get_hierarchy()
    wsel = h.atom_selection_cache().selection(string="water")
    wh = h.select(wsel)
    nonw = h.select(~wsel)
    nonwa = nonw.atoms()
    #
    # chain ID <> max residue number mapping
    can = {}
    for c in nonw.chains():
        last = list(c.residue_groups())[-1]
        can.setdefault(c.id, []).append(last.resseq_as_int())
    for k in can.keys():
        can[k] = max(can[k])
    #
    dic = {}
    for aw in wh.atoms():
        d_min = 1.e9
        b_iso = None
        chain_id = None
        for ap in nonwa:
            d = aw.distance(ap)
            if (d < d_min):
                d_min = d
                b_iso = ap.b
                chain_id = ap.parent().parent().parent().id
        aw.set_b(b_iso)
        dic.setdefault(chain_id, []).append(aw)
    #
    pdb_model = nonw.only_model()
    for chain_id, atoms in zip(dic.keys(), dic.values()):
        new_chain = iotbx.pdb.hierarchy.chain(id=chain_id)
        for i_seq, new_atom in enumerate(atoms):
            new_atom_group = iotbx.pdb.hierarchy.atom_group(altloc="",
                                                            resname="HOH")
            new_atom_group.append_atom(atom=new_atom.detached_copy())
            i_seq_ = i_seq + 1 + can[chain_id]
            new_residue_group = iotbx.pdb.hierarchy.residue_group(
                resseq=iotbx.pdb.resseq_encode(value=i_seq_), icode=" ")
            new_residue_group.append_atom_group(atom_group=new_atom_group)
            new_chain.append_residue_group(residue_group=new_residue_group)
        pdb_model.append_chain(chain=new_chain)
    #
    new_model = mmtbx.model.manager(model_input=None,
                                    pdb_hierarchy=nonw,
                                    crystal_symmetry=model.crystal_symmetry())
    new_model.set_shift_cart(model.shift_cart())
    new_model.get_hierarchy().atoms().reset_i_seq()
    return new_model
def run(args, params=None, out=sys.stdout, model=None):
  if model is None:
    if ( ((len(args) == 0) and (params is None)) or
         ((len(args) > 0) and ((args[0] == "-h") or (args[0] == "--help"))) ):
      show_usage()
      return

    if (params is None):
      pcl = iotbx.phil.process_command_line_with_files(
        args=args,
        master_phil_string=master_phil_str,
        pdb_file_def="file_name")
      work_params = pcl.work.extract()
    # or use parameters defined by GUI
    else:
      work_params = params
    pdb_inp = iotbx.pdb.input(file_name=work_params.file_name)

    pdb_int_params = mmtbx.model.manager.get_default_pdb_interpretation_params()
    pdb_int_params.pdb_interpretation.clash_guard.nonbonded_distance_threshold=None
    model = mmtbx.model.manager(
        model_input = pdb_inp,
        pdb_interpretation_params = pdb_int_params,
        build_grm = True)
  else:
    work_params = params
    if params is None:
      work_params = master_phil.extract()

  result = mmtbx.refinement.real_space.fit_residues.run(
      pdb_hierarchy     = model.get_hierarchy(),
      crystal_symmetry  = model.crystal_symmetry(),
      map_data          = None,
      rotamer_manager   = mmtbx.idealized_aa_residues.rotamer_manager.load(
        rotamers="favored_allowed"),
      sin_cos_table     = scitbx.math.sin_cos_table(n=10000),
      backbone_sample   = False,
      rotatable_hd      = model.rotatable_hd_selection(iselection=False),
      mon_lib_srv       = model.get_mon_lib_srv(),
      log               = out)
  model.set_sites_cart(
      sites_cart = result.pdb_hierarchy.atoms().extract_xyz(),
      update_grm = False)
  res_pdb_str = model.model_as_pdb()
  with open("%s.pdb" % work_params.output_prefix, "w") as f:
    f.write(res_pdb_str)
  return model
Beispiel #17
0
def exercise_06():
    """ Test that when building bio-molecule and then finding NCS relations
  from it, we get the same rotation and translation"""
    pdb_strings = [pdb_str_4, pdb_str_5]
    for method, pdb_string in enumerate(pdb_strings):
        pdb_inp = pdb.input(source_info=None, lines=pdb_string)
        model = mmtbx.model.manager(pdb_inp, expand_with_mtrix=False)
        crystal_symmetry = model.crystal_symmetry()
        # The exact transforms from pdb_string
        r1_expected = matrix.sqr([
            0.309017, -0.951057, 0.0, 0.951057, 0.309017, -0.0, 0.0, 0.0, 1.0
        ])
        r2_expected = matrix.sqr([
            -0.809017, -0.587785, 0.0, 0.587785, -0.809017, -0.0, 0.0, 0.0, 1.0
        ])
        t1_expected = matrix.col([0, 0, 7])
        t2_expected = matrix.col([0, 0, 0])
        # Look at biomt records retrieved from PDB file
        if method == 0:
            rec = model._model_input.process_BIOMT_records()
            model.expand_with_BIOMT_records()
            h = model.get_hierarchy()
        else:
            rec = model._model_input.process_MTRIX_records()
            model.expand_with_MTRIX_records()
            h = model.get_hierarchy()
        r1 = rec.r[1]
        r2 = rec.r[2]
        t1 = rec.t[1]
        t2 = rec.t[2]
        assert approx_equal(r1, r1_expected, eps=0.001)
        assert approx_equal(t1, t1_expected, eps=0.1)
        assert approx_equal(r2, r2_expected, eps=0.001)
        assert approx_equal(t2, t2_expected, eps=0.1)
        # Look at the rotation and translation found by the NCS search
        s = h.as_pdb_string(crystal_symmetry=crystal_symmetry)
        ncs_obj = ncs.input(hierarchy=pdb.input(source_info=None,
                                                lines=s).construct_hierarchy())
        nrgl = ncs_obj.get_ncs_restraints_group_list()
        assert approx_equal(r1_expected, nrgl[0].copies[0].r, eps=0.001)
        assert approx_equal(t1_expected, nrgl[0].copies[0].t, eps=0.1)
        assert approx_equal(r2_expected, nrgl[0].copies[1].r, eps=0.001)
        assert approx_equal(t2_expected, nrgl[0].copies[1].t, eps=0.1)
        if method == 0:
            assert nrgl.get_n_groups() == 1
        elif method == 1:
            assert nrgl.get_n_groups() == 2
Beispiel #18
0
    def __init__(self, map_manager, model, cushion, wrapping, log=sys.stdout):
        adopt_init_args(self, locals())
        self.basis_for_boxing_string = 'using model, wrapping=%s' % (wrapping)
        # safeguards
        assert isinstance(wrapping, bool)
        assert isinstance(map_manager, iotbx.map_manager.map_manager)
        assert isinstance(model, mmtbx.model.manager)
        assert self.map_manager.map_data().accessor().origin() == (0, 0, 0)

        # Make sure original map_manager symmetry matches model or original model
        original_uc_symmetry = map_manager.original_unit_cell_crystal_symmetry
        assert (original_uc_symmetry.is_similar_symmetry(
            model.crystal_symmetry())
                or (model.get_shift_manager()
                    and original_uc_symmetry.is_similar_symmetry(
                        model.get_shift_manager().get_original_cs())))

        assert cushion >= 0
        if wrapping:
            assert map_manager.unit_cell_grid == map_manager.map_data().all()
        # get items needed to do the shift
        cs = map_manager.crystal_symmetry()
        uc = cs.unit_cell()
        sites_frac = model.get_sites_frac()
        map_data = map_manager.map_data()
        # convert cushion into fractional vector
        cushion_frac = flex.double(uc.fractionalize((cushion, ) * 3))
        # find fractional corners
        frac_min = sites_frac.min()
        frac_max = sites_frac.max()
        frac_max = list(flex.double(frac_max) + cushion_frac)
        frac_min = list(flex.double(frac_min) - cushion_frac)
        # find corner grid nodes
        all_orig = map_data.all()
        self.gridding_first = [
            ifloor(f * n) for f, n in zip(frac_min, all_orig)
        ]
        self.gridding_last = [iceil(f * n) for f, n in zip(frac_max, all_orig)]

        # Ready with gridding...set up shifts and box crystal_symmetry
        self.set_shifts_and_crystal_symmetry()

        # Apply to model and to map_manager so that self.model()
        #  and self.map_manager are boxed versions

        self.map_manager = self.apply_to_map(self.map_manager)
        self.model = self.apply_to_model(self.model)
Beispiel #19
0
    def __init__(self,
                 map_manager=None,
                 model=None,
                 cushion=None,
                 wrapping=None):
        self.map_manager = map_manager
        self.model = model
        self.wrapping = wrapping

        self.basis_for_boxing_string = 'using model, wrapping=%s' % (wrapping)

        # safeguards
        assert wrapping is not None
        assert isinstance(map_manager, iotbx.map_manager.map_manager)
        assert isinstance(model, mmtbx.model.manager)
        assert self.map_manager.map_data().accessor().origin() == (0, 0, 0)
        assert map_manager.crystal_symmetry().is_similar_symmetry(
            model.crystal_symmetry())
        assert cushion >= 0

        if wrapping:
            assert map_manager.unit_cell_grid == map_manager.map_data().all()

        # get items needed to do the shift
        cs = map_manager.crystal_symmetry()
        uc = cs.unit_cell()
        sites_frac = model.get_sites_frac()
        map_data = map_manager.map_data()
        # convert cushion into fractional vector
        cushion_frac = flex.double(uc.fractionalize((cushion, ) * 3))
        # find fractional corners
        frac_min = sites_frac.min()
        frac_max = sites_frac.max()
        frac_max = list(flex.double(frac_max) + cushion_frac)
        frac_min = list(flex.double(frac_min) - cushion_frac)

        # find corner grid nodes
        all_orig = map_data.all()
        self.gridding_first = [
            ifloor(f * n) for f, n in zip(frac_min, all_orig)
        ]
        self.gridding_last = [iceil(f * n) for f, n in zip(frac_max, all_orig)]

        # Ready with gridding...set up shifts and box crystal_symmetry
        self.set_shifts_and_crystal_symmetry()
Beispiel #20
0
def test_file_with_unknown_pair_type():
  '''
  Verify that ready_set can fix issues with unknown_pair_type
  '''
  model = obtain_model(raw_records = unknown_pairs_pdb_str,
                       stop_for_unknowns = False)
  ph = model.get_hierarchy()
  pdb_with_h, h_were_added = mvc.check_and_add_hydrogen(
    pdb_hierarchy         = ph,
    allow_multiple_models = False,
    crystal_symmetry      = model.crystal_symmetry(),
    log                   = null_out())
  sorry = None
  try:
    model = obtain_model(raw_records=pdb_with_h)
  except Sorry as e:
    sorry = e
  assert(sorry is not None)
Beispiel #21
0
    def apply_to_model(self, model):
        # Apply to a model that is similar to the one used to generate
        #   this around_model object

        assert model is not None
        # Allow models where either original or current symmetry  XXX
        #  match this object's current or original symmetry
        # This is because some routines do not propagate original symmetry yet

        original_uc_symmetry = self.map_manager.original_unit_cell_crystal_symmetry
        assert (original_uc_symmetry.is_similar_symmetry(
            model.crystal_symmetry())
                or (model.get_shift_manager()
                    and original_uc_symmetry.is_similar_symmetry(
                        model.get_shift_manager().get_original_cs())))

        model.shift_model_and_set_crystal_symmetry(
            shift_cart=self.shift_cart,  # shift to apply
            crystal_symmetry=self.crystal_symmetry,  # new crystal_symmetry
        )

        return model
Beispiel #22
0
    def __init__(self,
                 map_manager,
                 lower_bounds,
                 upper_bounds,
                 wrapping,
                 model=None,
                 log=sys.stdout):
        adopt_init_args(self, locals())

        # safeguards
        assert lower_bounds is not None
        assert upper_bounds is not None
        assert upper_bounds is not None
        assert isinstance(wrapping, bool)
        assert isinstance(map_manager, iotbx.map_manager.map_manager)
        assert self.map_manager.map_data().accessor().origin() == (0, 0, 0)
        if model:
            assert isinstance(model, mmtbx.model.manager)
            assert map_manager.crystal_symmetry().is_similar_symmetry(
                model.crystal_symmetry())
        if wrapping:
            assert map_manager.unit_cell_grid == map_manager.map_data().all()

        self.basis_for_boxing_string = 'supplied bounds, wrapping=%s' % (
            wrapping)

        self.gridding_first = lower_bounds
        self.gridding_last = upper_bounds

        # Ready with gridding...set up shifts and box crystal_symmetry
        self.set_shifts_and_crystal_symmetry()

        # Apply to model (if present)  and to map_manager so that self.model
        #  and self.map_manager are boxed versions

        self.map_manager = self.apply_to_map(self.map_manager)
        if self.model:
            self.model = self.apply_to_model(self.model)
Beispiel #23
0
def models_as_chains(model):
    ph = model.get_hierarchy()
    r = iotbx.pdb.hierarchy.root()
    m = iotbx.pdb.hierarchy.model()
    for m_ in ph.models():
        for c_ in m_.chains():
            c_ = c_.detached_copy()
            m.append_chain(c_)
    r.append_model(m)
    #
    wat_sel = r.atom_selection_cache().selection("water")
    mm = r.select(~wat_sel)
    for m in r.select(wat_sel).models():
        for c in m.chains():
            c_ = c.detached_copy()
            mm.models()[0].append_chain(c_)
    r = mm
    #
    new_model = mmtbx.model.manager(model_input=None,
                                    pdb_hierarchy=r,
                                    crystal_symmetry=model.crystal_symmetry())
    new_model.set_shift_cart(shift_cart=model.shift_cart())
    return new_model
Beispiel #24
0
def run(args, out=None, verbose=True):
  t0 = time.time()
  if (out is None) : out = sys.stdout
  from iotbx import file_reader
  import iotbx.phil
  cmdline = iotbx.phil.process_command_line_with_files(
    args=args,
    master_phil=master_phil,
    pdb_file_def="model",
    reflection_file_def="map_coeffs",
    map_file_def="map_file",
    cif_file_def="cif_file",
    usage_string="""\
mmtbx.ringer model.pdb map_coeffs.mtz [cif_file ...] [options]

%s
""" % __doc__)
  cmdline.work.show()
  params = cmdline.work.extract()
  validate_params(params)
  pdb_in = file_reader.any_file(params.model, force_type="pdb")
  pdb_in.check_file_type("pdb")

  pdb_inp = iotbx.pdb.input(file_name=params.model)
  model = mmtbx.model.manager(
    model_input      = pdb_inp)
  crystal_symmetry_model = model.crystal_symmetry()
  if crystal_symmetry_model is not None:
    crystal_symmetry_model.show_summary()

  hierarchy = model.get_hierarchy()
  map_coeffs = map_inp = difference_map_coeffs = None
  map_data, unit_cell = None, None
  # get miller array if map coefficients are provided
  if (params.map_coeffs is not None):
    mtz_in = file_reader.any_file(params.map_coeffs, force_type="hkl")
    mtz_in.check_file_type("hkl")
    best_guess = None
    best_labels = []
    all_labels = []
    for array in mtz_in.file_server.miller_arrays :
      if (array.is_complex_array()):
        labels = array.info().label_string()
        if (labels == params.map_label):
          map_coeffs = array
        elif (labels == params.difference_map_label):
          difference_map_coeffs = array
        else :
          if (params.map_label is None):
            all_labels.append(labels)
            if (labels.startswith("2FOFCWT") or labels.startswith("2mFoDFc") or
                labels.startswith("FWT")):
              best_guess = array
              best_labels.append(labels)
          if (params.difference_map_label is None):
            if (labels.startswith("FOFCWT") or labels.startswith("DELFWT")):
              difference_map_coeffs = array
    if (map_coeffs is None):
      if (len(all_labels) == 0):
        raise Sorry("No valid (pre-weighted) map coefficients found in file.")
      elif (best_guess is None):
        raise Sorry("Couldn't automatically determine appropriate map labels. "+
          "Choices:\n  %s" % "  \n".join(all_labels))
      elif (len(best_labels) > 1):
        raise Sorry("Multiple appropriate map coefficients found in file. "+
          "Choices:\n  %s" % "\n  ".join(best_labels))
      map_coeffs = best_guess
      print("  Guessing %s for input map coefficients" % best_labels[0], file=out)
  # get map_inp object and do sanity checks if map is provided
  else :
    ccp4_map_in = file_reader.any_file(params.map_file, force_type="ccp4_map")
    ccp4_map_in.check_file_type("ccp4_map")
    map_inp = ccp4_map_in.file_object
    base = map_model_manager(
      map_manager               = map_inp,
      model            = model,
      ignore_symmetry_conflicts = params.ignore_symmetry_conflicts)
    cs_consensus = base.crystal_symmetry()
    hierarchy = base.model().get_hierarchy()
    map_data = base.map_data()
    unit_cell = map_inp.grid_unit_cell()

  hierarchy.atoms().reset_i_seq()

  make_header("Iterating over residues", out=out)
  t1 = time.time()
  results = iterate_over_residues(
    pdb_hierarchy=hierarchy,
    map_coeffs=map_coeffs,
    difference_map_coeffs=difference_map_coeffs,
    map_data  = map_data,
    unit_cell = unit_cell,
    params=params,
    log=out).results
  t2 = time.time()
  if (verbose):
    print("Time excluding I/O: %8.1fs" % (t2 - t1), file=out)
    print("Overall runtime:    %8.1fs" % (t2 - t0), file=out)
  if (params.output_base is None):
    pdb_base = os.path.basename(params.model)
    params.output_base = os.path.splitext(pdb_base)[0] + "_ringer"
  easy_pickle.dump("%s.pkl" % params.output_base, results)
  print("Wrote %s.pkl" % params.output_base, file=out)
  csv = "\n".join([ r.format_csv() for r in results ])
  open("%s.csv" % params.output_base, "w").write(csv)
  print("Wrote %s.csv" % params.output_base, file=out)
  print("\nReference:", file=out)
  print("""\
  Lang PT, Ng HL, Fraser JS, Corn JE, Echols N, Sales M, Holton JM, Alber T.
  Automated electron-density sampling reveals widespread conformational
  polymorphism in proteins. Protein Sci. 2010 Jul;19(7):1420-31. PubMed PMID:
  20499387""", file=out)
  if (params.gui):
    run_app(results)
  else :
    return results
Beispiel #25
0
 def __init__(
         self,
         model,
         Hs=["H", "D"],
         As=["O", "N", "S", "F", "CL"],
         Ds=["O", "N", "S"],
         d_HA_cutoff=[1.4, 3.0],  # original: [1.4, 2.4],
         d_DA_cutoff=[2.5, 3.5],  # not used
         a_DHA_cutoff=120,  # should be greater than this
         a_YAH_cutoff=[90, 180],  # should be within this interval, not used
         protein_only=False):
     self.result = []
     self.atoms = model.get_hierarchy().atoms()
     geometry = model.get_restraints_manager()
     bond_proxies_simple, asu = geometry.geometry.get_all_bond_proxies(
         sites_cart=model.get_sites_cart())
     h_bonded_to = {}
     for p in bond_proxies_simple:
         i, j = p.i_seqs
         ei, ej = self.atoms[p.i_seqs[0]].element, self.atoms[
             p.i_seqs[1]].element
         if (ei in Hs): h_bonded_to[i] = self.atoms[j]
         if (ej in Hs): h_bonded_to[j] = self.atoms[i]
     #
     sites_cart = model.get_sites_cart()
     crystal_symmetry = model.crystal_symmetry()
     fm = crystal_symmetry.unit_cell().fractionalization_matrix()
     om = crystal_symmetry.unit_cell().orthogonalization_matrix()
     pg = get_pair_generator(crystal_symmetry=crystal_symmetry,
                             buffer_thickness=d_HA_cutoff[1],
                             sites_cart=sites_cart)
     get_class = iotbx.pdb.common_residue_names_get_class
     for p in pg.pair_generator:
         i, j = p.i_seq, p.j_seq
         ei, ej = self.atoms[i].element, self.atoms[j].element
         altloc_i = self.atoms[i].parent().altloc
         altloc_j = self.atoms[j].parent().altloc
         resseq_i = self.atoms[i].parent().parent().resseq
         resseq_j = self.atoms[j].parent().parent().resseq
         # pre-screen candidates begin
         one_is_Hs = ei in Hs or ej in Hs
         other_is_acceptor = ei in As or ej in As
         d_HA = math.sqrt(p.dist_sq)
         assert d_HA <= d_HA_cutoff[1]
         is_candidate = one_is_Hs and other_is_acceptor and \
           d_HA >= d_HA_cutoff[0] and \
           altloc_i == altloc_j and resseq_i != resseq_j
         if (protein_only):
             for it in [i, j]:
                 resname = self.atoms[it].parent().resname
                 is_candidate &= get_class(
                     name=resname) == "common_amino_acid"
         if (not is_candidate): continue
         if (ei in Hs and not h_bonded_to[i].element in As): continue
         if (ej in Hs and not h_bonded_to[j].element in As): continue
         # pre-screen candidates end
         rt_mx_i = pg.conn_asu_mappings.get_rt_mx_i(p)
         rt_mx_j = pg.conn_asu_mappings.get_rt_mx_j(p)
         rt_mx_ji = rt_mx_i.inverse().multiply(rt_mx_j)
         #
         if (ei in Hs):
             H = self.atoms[i]
             D = self.atoms[h_bonded_to[H.i_seq].i_seq]
             A = self.atoms[j]
             if (str(rt_mx_ji) != "x,y,z"):
                 A = apply_symop_to_copy(A, rt_mx_ji, fm, om)
         if (ej in Hs):
             H = self.atoms[j]
             D = self.atoms[h_bonded_to[H.i_seq].i_seq]
             A = self.atoms[i]
             if (str(rt_mx_ji) != "x,y,z"):
                 H = apply_symop_to_copy(H, rt_mx_ji, fm, om)
                 D = apply_symop_to_copy(D, rt_mx_ji, fm, om)
         assert H.distance(D) < 1.15
         # filter by a_DHA
         a_DHA = H.angle(A, D, deg=True)
         if (a_DHA < a_DHA_cutoff): continue
         #
         assert approx_equal(d_HA, H.distance(A), 1.e-3)
         self.result.append(
             group_args(i=i,
                        j=j,
                        symop=rt_mx_ji,
                        d_HA=d_HA,
                        a_DHA=a_DHA,
                        d_AD=A.distance(D)))
Beispiel #26
0
    def __init__(
            self,
            # I suggest we use map_input with symmetries here instead of
            # raw map_data and call something like mtriage.py:check_and_set_crystal_symmetry
            # to set CS consistently for maps and model.
            # Especially because DataManager is supposed to provide these
            # map_input objects.
            # consider reusing/replacing crystal.select_crystal_symmetry()

            # Warning! Model and all map_data are being changed in place.
            # This warning should remain here
        map_data=None,  # whole_map_input would be a better name?
            map_data_1=None,  # half_map_input_1 would be a better name?
            map_data_2=None,  # half_map_input_2 would be a better name?
            model=None,
            # where this CS is supposed to come from? After agreing on picking
            # CS here, the only thing it could be useful - to pass CS
            # obtained from command-line args or from parameters. Consider
            # renaming parameter accordingly.
            crystal_symmetry=None,
            box=True,
            ignore_symmetry_conflicts=False):
        #
        # We should be able to work without symmetry at all. Why not just box
        # model?
        assert [model, crystal_symmetry].count(None) != 2
        if (crystal_symmetry is None and model is not None):
            crystal_symmetry = model.crystal_symmetry()
        if ([model, crystal_symmetry].count(None) == 0):
            if ignore_symmetry_conflicts:  # Take crystal_symmetry if necessary
                if not (model.crystal_symmetry().is_similar_symmetry(
                        crystal_symmetry)):
                    model = mmtbx.model.manager(
                        model_input=model.get_hierarchy().as_pdb_input(),
                        crystal_symmetry=crystal_symmetry)
            else:
                assert model.crystal_symmetry().is_similar_symmetry(
                    crystal_symmetry)
        if (not [map_data_1, map_data_2].count(None) in [0, 2]):
            raise Sorry("None or two half-maps are required.")
        #

        # Suggest to get rid of self._model, self._map_data etc to make crystal
        # clear that they are changed in place. Therefore getter functions
        # at the bottom are useless and confusing.
        self._map_data = map_data
        self._half_map_data_1 = map_data_1
        self._half_map_data_2 = map_data_2
        self._model = model
        self._crystal_symmetry = crystal_symmetry
        #
        # I don't see any connection between _counts, map_histograms and main
        # purpose of this class (actually, it is function written using class syntax)
        # - shifting origins, cutting boxes, figuring out crystal symmetries.
        # This can be easily done just before calling this and totally separate.
        # I suggest to remove it from here --->
        self._counts = get_map_counts(map_data=self._map_data,
                                      crystal_symmetry=crystal_symmetry)
        self._map_histograms = get_map_histograms(data=self._map_data,
                                                  n_slots=20,
                                                  data_1=self._half_map_data_1,
                                                  data_2=self._half_map_data_2)
        # <---- End of removing suggestion.
        # Shift origin
        sites_cart = None
        if (self._model is not None):
            sites_cart = self._model.get_sites_cart()
        self.soin = maptbx.shift_origin_if_needed(
            map_data=self._map_data,
            sites_cart=sites_cart,
            crystal_symmetry=crystal_symmetry)
        self._original_origin_cart = self.soin.original_origin_cart
        self._original_origin_grid_units = self.soin.original_origin_grid_units
        self.box = None
        self._map_data = self.soin.map_data
        if (self._model is not None):
            self._model.set_sites_cart(sites_cart=self.soin.sites_cart)
        if (self._half_map_data_1 is not None):
            self._half_map_data_1 = maptbx.shift_origin_if_needed(
                map_data=self._half_map_data_1,
                sites_cart=None,
                crystal_symmetry=None).map_data
            self._half_map_data_2 = maptbx.shift_origin_if_needed(
                map_data=self._half_map_data_2,
                sites_cart=None,
                crystal_symmetry=None).map_data
        # Box
        if (self._model is not None and box):
            xrs = self._model.get_xray_structure()
            if (self._half_map_data_1 is not None):
                self._half_map_data_1 = mmtbx.utils.extract_box_around_model_and_map(
                    xray_structure=xrs,
                    map_data=self._half_map_data_1,
                    box_cushion=5.0).map_box
                self._half_map_data_2 = mmtbx.utils.extract_box_around_model_and_map(
                    xray_structure=xrs,
                    map_data=self._half_map_data_2,
                    box_cushion=5.0).map_box
            self.box = mmtbx.utils.extract_box_around_model_and_map(
                xray_structure=xrs, map_data=self._map_data, box_cushion=5.0)
            # This should be changed to call model.set_shift_manager(shift_manager=box)
            # For now just call _model.unset_restraints_manager() afterwards.
            self._model.set_xray_structure(
                xray_structure=self.box.xray_structure_box)
            self._crystal_symmetry = self._model.crystal_symmetry()
            self._map_data = self.box.map_box
Beispiel #27
0
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 __init__(self,
              map_data         = None,
              map_data_1       = None,
              map_data_2       = None,
              model            = None,
              crystal_symmetry = None,
              box              = True):
   #
   assert [model, crystal_symmetry].count(None) != 2
   if(crystal_symmetry is None and model is not None):
     crystal_symmetry = model.crystal_symmetry()
   if([model, crystal_symmetry].count(None)==0):
     assert model.crystal_symmetry().is_similar_symmetry(crystal_symmetry)
   if(not [map_data_1, map_data_2].count(None) in [0,2]):
     raise Sorry("None or two half-maps are required.")
   #
   self._map_data         = map_data
   self._half_map_data_1  = map_data_1
   self._half_map_data_2  = map_data_2
   self._model            = model
   self._crystal_symmetry = crystal_symmetry
   #
   self._counts = get_map_counts(
     map_data         = self._map_data,
     crystal_symmetry = crystal_symmetry)
   self._map_histograms = get_map_histograms(
     data    = self._map_data,
     n_slots = 20,
     data_1  = self._half_map_data_1,
     data_2  = self._half_map_data_2)
   # Shift origin
   sites_cart = None
   if(self._model is not None):
     sites_cart = self._model.get_sites_cart()
   soin = maptbx.shift_origin_if_needed(
     map_data         = self._map_data,
     sites_cart       = sites_cart,
     crystal_symmetry = crystal_symmetry)
   self._map_data = soin.map_data
   if(self._model is not None):
     self._model.set_sites_cart(sites_cart = soin.sites_cart)
   if(self._half_map_data_1 is not None):
     self._half_map_data_1 = maptbx.shift_origin_if_needed(
       map_data         = self._half_map_data_1,
       sites_cart       = None,
       crystal_symmetry = None).map_data
     self._half_map_data_2 = maptbx.shift_origin_if_needed(
       map_data         = self._half_map_data_2,
       sites_cart       = None,
       crystal_symmetry = None).map_data
   # Box
   if(self._model is not None and box):
     xrs = self._model.get_xray_structure()
     if(self._half_map_data_1 is not None):
       self._half_map_data_1 = mmtbx.utils.extract_box_around_model_and_map(
         xray_structure = xrs,
         map_data       = self._half_map_data_1,
         box_cushion    = 5.0).map_box
       self._half_map_data_2 = mmtbx.utils.extract_box_around_model_and_map(
         xray_structure = xrs,
         map_data       = self._half_map_data_2,
         box_cushion    = 5.0).map_box
     box = mmtbx.utils.extract_box_around_model_and_map(
       xray_structure = xrs,
       map_data       = self._map_data,
       box_cushion    = 5.0)
     self._model.set_xray_structure(xray_structure = box.xray_structure_box)
     self._crystal_symmetry = self._model.crystal_symmetry()
     self._map_data = box.map_box
Beispiel #29
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
Beispiel #30
0
def run(args, log=sys.stdout):
    print >> log, "-" * 79
    print >> log, legend
    print >> log, "-" * 79
    inputs = mmtbx.utils.process_command_line_args(
        args=args, master_params=master_params())
    params = inputs.params.extract()
    # estimate resolution
    d_min = params.resolution
    broadcast(m="Map resolution:", log=log)
    if (d_min is None):
        raise Sorry("Resolution is required.")
    print >> log, "  d_min: %6.4f" % d_min
    # model
    broadcast(m="Input PDB:", log=log)
    file_names = inputs.pdb_file_names
    if (len(file_names) != 1): raise Sorry("PDB file has to given.")
    if (inputs.crystal_symmetry is None):
        raise Sorry("No crystal symmetry defined.")
    pdb_inp = iotbx.pdb.input(file_name=file_names[0])
    model = mmtbx.model.manager(model_input=pdb_inp,
                                crystal_symmetry=inputs.crystal_symmetry,
                                build_grm=True)
    if model.get_number_of_models() > 1:
        raise Sorry("Only one model allowed.")
    model.setup_scattering_dictionaries(
        scattering_table=params.scattering_table)
    model.get_xray_structure().show_summary(f=log, prefix="  ")
    broadcast(m="Input map:", log=log)
    if (inputs.ccp4_map is None): raise Sorry("Map file has to given.")
    inputs.ccp4_map.show_summary(prefix="  ")
    map_data = inputs.ccp4_map.map_data()
    print >> log, "  Actual map (min,max,mean):", \
      map_data.as_1d().min_max_mean().as_tuple()
    make_sub_header("Histogram of map values", out=log)
    md = map_data.as_1d()
    show_histogram(data=md,
                   n_slots=10,
                   data_min=flex.min(md),
                   data_max=flex.max(md),
                   log=log)
    # shift origin if needed
    soin = maptbx.shift_origin_if_needed(
        map_data=map_data,
        sites_cart=model.get_sites_cart(),
        crystal_symmetry=model.crystal_symmetry())
    map_data = soin.map_data
    model.set_sites_cart(soin.sites_cart, update_grm=True)
    ####
    # Compute and show all stats
    ####
    broadcast(m="Model statistics:", log=log)
    make_sub_header("Overall", out=log)
    info = mmtbx.model.statistics.info(model=model)
    info.geometry.show()

    # XXX - these are not available anymore due to refactoring
    # make_sub_header("Histogram of devations from ideal bonds", out=log)
    # show_histogram(data=ms.bond_deltas, n_slots=10, data_min=0, data_max=0.2,
    #   log=log)
    # #
    # make_sub_header("Histogram of devations from ideal angles", out=log)
    # show_histogram(data=ms.angle_deltas, n_slots=10, data_min=0, data_max=30.,
    #   log=log)
    # #
    # make_sub_header("Histogram of non-bonded distances", out=log)
    # show_histogram(data=ms.nonbonded_distances, n_slots=10, data_min=0,
    #   data_max=5., log=log)
    #
    make_sub_header("Histogram of ADPs", out=log)
    info.adp.show(log=log)
    # bs = xrs.extract_u_iso_or_u_equiv()*adptbx.u_as_b(1.)
    # show_histogram(data=bs, n_slots=10, data_min=flex.min(bs),
    #   data_max=flex.max(bs), log=log)
    #
    # Compute CC
    broadcast(m="Map-model CC (overall):", log=log)
    five_cc_result = mmtbx.maps.correlation.five_cc(
        map=map_data, xray_structure=model.get_xray_structure(), d_min=d_min)
    atom_radius = five_cc_result.atom_radius
    if atom_radius is None:
        atom_radius = five_cc_result._atom_radius()
    print >> log, "  CC_mask  : %6.4f" % five_cc_result.result.cc_mask
    print >> log, "  CC_volume: %6.4f" % five_cc_result.result.cc_volume
    print >> log, "  CC_peaks : %6.4f" % five_cc_result.result.cc_peaks
    # Compute FSC(map, model)
    broadcast(m="Model-map FSC:", log=log)
    fsc = mmtbx.maps.correlation.fsc_model_vs_map(
        xray_structure=model.get_xray_structure(),
        map=map_data,
        atom_radius=atom_radius,
        d_min=d_min)
    fsc.show(prefix="  ")
    # Local CC
    cc_calculator = mmtbx.maps.correlation.from_map_and_xray_structure_or_fmodel(
        xray_structure=model.get_xray_structure(),
        map_data=map_data,
        d_min=d_min)
    broadcast(m="Map-model CC (local):", log=log)
    # per residue
    print >> log, "Per residue:"
    residue_results = list()
    ph = model.get_hierarchy()
    xrs = model.get_xray_structure()
    for rg in ph.residue_groups():
        cc = cc_calculator.cc(selection=rg.atoms().extract_i_seq())
        chain_id = rg.parent().id
        print >> log, "  chain id: %s resid %s: %6.4f" % (chain_id, rg.resid(),
                                                          cc)
    # per chain
    print >> log, "Per chain:"
    for chain in ph.chains():
        print >> log, "  chain %s: %6.4f" % (
            chain.id,
            cc_calculator.cc(selection=chain.atoms().extract_i_seq()))
    # per residue detailed counts
    print >> log, "Per residue (histogram):"
    crystal_gridding = maptbx.crystal_gridding(
        unit_cell=xrs.unit_cell(),
        space_group_info=xrs.space_group_info(),
        pre_determined_n_real=map_data.accessor().all())
    f_calc = xrs.structure_factors(d_min=d_min).f_calc()
    fft_map = miller.fft_map(crystal_gridding=crystal_gridding,
                             fourier_coefficients=f_calc)
    fft_map.apply_sigma_scaling()
    map_model = fft_map.real_map_unpadded()
    sites_cart = xrs.sites_cart()
    cc_per_residue = flex.double()
    for rg in ph.residue_groups():
        cc = mmtbx.maps.correlation.from_map_map_atoms(
            map_1=map_data,
            map_2=map_model,
            sites_cart=sites_cart.select(rg.atoms().extract_i_seq()),
            unit_cell=xrs.unit_cell(),
            radius=2.)
        cc_per_residue.append(cc)
    show_histogram(data=cc_per_residue,
                   n_slots=10,
                   data_min=-1.,
                   data_max=1.0,
                   log=log)