示例#1
0
    def __init__(self,
                 model,
                 h_bond_params=None,
                 protein_only=False,
                 pair_proxies=None,
                 write_eff_file=True):
        if (h_bond_params is None):
            import cctbx.geometry_restraints.process_nonbonded_proxies as pnp
            h_bond_params = pnp.h_bond()
        Hs = h_bond_params.Hs
        As = h_bond_params.As
        Ds = h_bond_params.Ds
        d_HA_cutoff = h_bond_params.d_HA_cutoff
        d_DA_cutoff = h_bond_params.d_DA_cutoff
        a_DHA_cutoff = h_bond_params.a_DHA_cutoff
        a_YAH_cutoff = h_bond_params.a_YAH_cutoff
        #
        self.result = []
        self.model = model
        self.pair_proxies = pair_proxies
        self.external_proxies = False
        if (self.pair_proxies is not None):
            self.external_proxies = True
        atoms = self.model.get_hierarchy().atoms()
        geometry = self.model.get_restraints_manager()
        fsc0 = geometry.geometry.shell_sym_tables[0].full_simple_connectivity()
        bond_proxies_simple, asu = geometry.geometry.get_all_bond_proxies(
            sites_cart=self.model.get_sites_cart())
        sites_cart = self.model.get_sites_cart()
        crystal_symmetry = self.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
        # find proxies if not provided
        if (self.pair_proxies is None):
            pp = []
            self.pair_proxies = []
            pp = [p for p in pg.pair_generator]
        else:
            pp = self.pair_proxies
        # now loop over proxies
        for p in pp:
            i, j = p.i_seq, p.j_seq
            if (self.external_proxies
                ):  # making sure proxies point to same atoms
                a_i = make_atom_id(atom=atoms[i], index=i).id_str
                a_j = make_atom_id(atom=atoms[j], index=j).id_str
                assert a_i == p.atom_A.id_str, [a_i, p.atom_A.id_str]
                assert a_j == p.atom_H.id_str, [a_j, p.atom_H.id_str]
            # presecreen candidates
            ei, ej = atoms[i].element, atoms[j].element
            is_candidate = precheck(atoms=atoms,
                                    i=i,
                                    j=j,
                                    Hs=Hs,
                                    As=As,
                                    Ds=Ds,
                                    fsc0=fsc0)
            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
            # symop tp map onto symmetry related
            rt_mx_ji = None
            if (not self.external_proxies):
                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)
            else:
                rt_mx_ji = p.rt_mx_ji
            #
            D, H, A, Y, atom_A, atom_H, atom_D = get_D_H_A_Y(i=i,
                                                             j=j,
                                                             Hs=Hs,
                                                             fsc0=fsc0,
                                                             rt_mx_ji=rt_mx_ji,
                                                             fm=fm,
                                                             om=om,
                                                             atoms=atoms)
            if (len(Y) == 0): continue  # don't use 'lone' acceptors
            #
            d_DA = D.distance(A)
            if (not self.external_proxies):
                if (d_DA < d_DA_cutoff[0] or d_DA > d_DA_cutoff[1]):
                    continue
            #
            d_HA = A.distance(H)
            if (not self.external_proxies):
                assert d_HA <= d_HA_cutoff[1]
                assert approx_equal(math.sqrt(p.dist_sq), d_HA, 1.e-3)
                if (d_HA < d_HA_cutoff[0]): continue


#      assert H.distance(D) < 1.15, [H.distance(D), H.name, D.name]
# filter by a_DHA
            a_DHA = H.angle(A, D, deg=True)
            if (not self.external_proxies):
                if (a_DHA < a_DHA_cutoff): continue
            # filter by a_YAH
            a_YAH = []
            if (len(Y) > 0):
                for Y_ in Y:
                    a_YAH_ = A.angle(Y_, H, deg=True)
                    a_YAH.append(a_YAH_)
            if (not self.external_proxies):
                flags = []
                for a_YAH_ in a_YAH:
                    flags.append(not (a_YAH_ >= a_YAH_cutoff[0]
                                      and a_YAH_ <= a_YAH_cutoff[1]))
                flags = list(set(flags))
                if (len(flags) > 1 or (len(flags) == 1 and flags[0])): continue
            #
            assert approx_equal(d_HA, H.distance(A), 1.e-3)
            #a_YAD = []
            #if(len(Y)>0):
            #  for Y_ in Y:
            #    a_YAD_ = A.angle(Y_, D, deg=True)
            #    a_YAD.append(a_YAD_)
            self.result.append(
                group_args(
                    i=i,
                    j=j,
                    atom_H=atom_H,
                    atom_A=atom_A,
                    atom_D=atom_D,
                    symop=rt_mx_ji,
                    d_HA=d_HA,
                    a_DHA=a_DHA,
                    a_YAH=a_YAH,
                    #a_YAD   = a_YAD,
                    d_AD=A.distance(D)))
            if (not self.external_proxies):
                proxy_custom = group_args(i_seq=i,
                                          j_seq=j,
                                          rt_mx_ji=rt_mx_ji,
                                          atom_H=atom_H,
                                          atom_A=atom_A)
                self.pair_proxies.append(proxy_custom)
        #
        if (write_eff_file):
            self.as_restraints()
def stats(model, prefix, no_ticks=True):
    # Get rid of H, multi-model, no-protein and single-atom residue models
    if (model.percent_of_single_atom_residues() > 20):
        return None
    sel = model.selection(string="protein")
    if (sel.count(True) == 0):
        return None
    ssr = "protein and not (element H or element D or resname UNX or resname UNK or resname UNL)"
    sel = model.selection(string=ssr)
    model = model.select(sel)
    if (len(model.get_hierarchy().models()) > 1):
        return None
    # Add H; this looses CRYST1 !
    rr = run_reduce_with_timeout(
        stdin_lines=model.get_hierarchy().as_pdb_string().splitlines(),
        file_name=None,
        parameters="-oh -his -flip -keep -allalt -pen9999 -",
        override_auto_timeout_with=None)
    # Create model; this is a single-model pure protein with new H added
    pdb_inp = iotbx.pdb.input(source_info=None, lines=rr.stdout_lines)
    model = mmtbx.model.manager(model_input=None,
                                build_grm=True,
                                pdb_hierarchy=pdb_inp.construct_hierarchy(),
                                process_input=True,
                                log=null_out())
    box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center(
        sites_cart=model.get_sites_cart(), buffer_layer=5)
    model.set_sites_cart(box.sites_cart)
    model._crystal_symmetry = box.crystal_symmetry()
    #
    N = 10
    #
    import cctbx.geometry_restraints.process_nonbonded_proxies as pnp
    h_bond_params = pnp.h_bond()
    h_bond_params.a_DHA_cutoff = 90
    #
    SS = get_ss_selections(hierarchy=model.get_hierarchy())
    HB_all = find(model=model.select(flex.bool(model.size(), True)),
                  h_bond_params=h_bond_params).get_params_as_arrays(
                      replace_with_empty_threshold=N)
    HB_alpha = find(model=model.select(SS.both.h_sel),
                    h_bond_params=h_bond_params).get_params_as_arrays(
                        replace_with_empty_threshold=N)
    HB_beta = find(model=model.select(SS.both.s_sel),
                   h_bond_params=h_bond_params).get_params_as_arrays(
                       replace_with_empty_threshold=N)
    print(HB_all.d_HA.size())
    result_dict = {}
    result_dict["all"] = HB_all
    result_dict["alpha"] = HB_alpha
    result_dict["beta"] = HB_beta
    #  result_dict["loop"]  = get_selected(sel=loop_sel)
    # Load histograms for reference high-resolution d_HA and a_DHA
    pkl_fn = libtbx.env.find_in_repositories(
        relative_path="mmtbx") + "/nci/d_HA_and_a_DHA_high_res.pkl"
    assert os.path.isfile(pkl_fn)
    ref = easy_pickle.load(pkl_fn)
    #
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(10, 10))
    kwargs = dict(histtype='bar', bins=20, range=[1.6, 3.0], alpha=.8)
    for j, it in enumerate([["alpha", 1], ["beta", 3], ["all", 5]]):
        key, i = it
        ax = plt.subplot(int("32%d" % i))
        if (no_ticks):
            #ax.set_xticks([])
            ax.set_yticks([])
        if (j in [0, 1]):
            ax.tick_params(bottom=False)
            ax.set_xticklabels([])
        ax.tick_params(axis="x", labelsize=12)
        ax.tick_params(axis="y", labelsize=12, left=False, pad=-2)
        ax.text(0.98,
                0.92,
                key,
                size=12,
                horizontalalignment='right',
                transform=ax.transAxes)
        HB = result_dict[key]
        if HB is None: continue
        w1 = np.ones_like(HB.d_HA) / HB.d_HA.size()
        ax.hist(HB.d_HA, color="orangered", weights=w1, rwidth=0.3, **kwargs)
        #
        start, end1, end2 = 0, max(ref.distances[key].vals), \
          round(max(ref.distances[key].vals),2)
        if (not no_ticks):
            plt.yticks([0.01, end1], ["0", end2],
                       visible=True,
                       rotation="horizontal")

        if (key == "alpha"): plt.ylim(0, end2 + 0.02)
        elif (key == "beta"): plt.ylim(0, end2 + 0.02)
        elif (key == "all"): plt.ylim(0, end2 + 0.02)
        else: assert 0
        #
        if (j == 0): ax.set_title("Distance", size=15)
        bins = list(flex.double(ref.distances[key].bins))
        ax.bar(bins, ref.distances[key].vals, alpha=.3, width=0.07)
    #
    kwargs = dict(histtype='bar', bins=20, range=[90, 180], alpha=.8)
    for j, it in enumerate([["alpha", 2], ["beta", 4], ["all", 6]]):
        key, i = it
        ax = plt.subplot(int("32%d" % i))
        if (j in [0, 1]):
            ax.tick_params(bottom=False)
            ax.set_xticklabels([])
        if (no_ticks):
            #ax.set_xticks([])
            ax.set_yticks([])
        ax.tick_params(axis="x", labelsize=12)
        ax.tick_params(axis="y", labelsize=12, left=False, pad=-2)
        ax.text(0.98,
                0.92,
                key,
                size=12,
                horizontalalignment='right',
                transform=ax.transAxes)

        ax.text(0.98,
                0.92,
                key,
                size=12,
                horizontalalignment='right',
                transform=ax.transAxes)
        #if(j in [0,1]): ax.plot_params(bottom=False)
        HB = result_dict[key]
        if HB is None: continue
        w1 = np.ones_like(HB.a_DHA) / HB.a_DHA.size()
        ax.hist(HB.a_DHA, color="orangered", weights=w1, rwidth=0.3, **kwargs)
        #
        start, end1, end2 = 0, max(ref.angles[key].vals), \
          round(max(ref.angles[key].vals),2)
        if (not no_ticks):
            plt.yticks([0.01, end1], ["0", end2],
                       visible=True,
                       rotation="horizontal")

        if (key == "alpha"): plt.ylim(0, end2 + 0.02)
        elif (key == "beta"): plt.ylim(0, end2 + 0.02)
        elif (key == "all"): plt.ylim(0, end2 + 0.02)
        else: assert 0
        #
        if (j == 0): ax.set_title("Angle", size=15)
        ax.bar(ref.angles[key].bins, ref.angles[key].vals, width=4.5, alpha=.3)
    plt.subplots_adjust(wspace=0.12, hspace=0.025)
    if (no_ticks):
        plt.subplots_adjust(wspace=0.025, hspace=0.025)
    #fig.savefig("%s.png"%prefix, dpi=1000)
    fig.savefig("%s.pdf" % prefix)