Exemple #1
0
def get_NGL_selection_from_AtomID(pose: pyrosetta.Pose,
                                  atom_id: pyrosetta.AtomID):
    pose_resi = atom_id.rsd()
    residue = pose.residue(pose_resi)
    atom_name = residue.atom_name(atom_id.atomno()).strip()
    pdb_resi, chain = pose.pdb_info().pose2pdb(pose_resi).strip().split()
    return f'[{residue.name3().strip()}]{pdb_resi}:{chain}.{atom_name}'
Exemple #2
0
def xform_pose(pose, xform):
    for ir in range(1, len(pose.residues) + 1):
        res = pose.residue(ir)
        for ia in range(1, res.natoms() + 1):
            old = res.xyz(ia)
            old = np.array([old[0], old[1], old[2], 1])
            new = xform @ old
            pose.set_xyz(AtomID(ia, ir), rVec(new[0], new[1], new[2]))
Exemple #3
0
def name2aid(pose, ires, aname):
    return AtomID(pose.residue(ires).atom_index(aname.strip()), ires)
print(pose.residue(500).name())

print(pose.pdb_info().chain(500))
print(pose.pdb_info().number(500))

print(pose.pdb_info().pdb2pose("A", 100))

print(pose.pdb_info().pose2pdb(25))

pose.display_secstruct()

# Protein Geometry
print(pose.phi(5))
print(pose.psi(5))
print(pose.chi(1, 5))
R5N = AtomID(1, 5)
R5CA = AtomID(2, 5)
R5C = AtomID(3, 5)
print(pose.conformation().bond_length(R5N, R5CA))
print(pose.conformation().bond_length(R5CA, R5C))
N_xyz = pose.residue(5).xyz("N")
CA_xyz = pose.residue(5).xyz("CA")
N_CA_vector = CA_xyz - N_xyz
print(N_CA_vector.norm)

print(pose.conformation().bond_angle(R5N, R5CA, R5C))
pose.set_phi(5, -60)
pose.set_psi(5, -43)
pose.set_chi(1, 5, 180)

pose.conformation().set_bond_length(R5N, R5CA, 1.5)
Exemple #5
0
def xtal_build(
      pdb_name,
      xspec,
      aa1,
      aa2,
      pose,
      peptide_sym,
      peptide_orig,
      peptide_axis,
      metal_sym,
      metal_origin,
      metal_sym_axis,
      rpxbody,
      tag,
      clash_dis,
      contact_dis,
      min_contacts,
      max_sym_score,
      debug=False,
      **kw,
):
   kw = rp.Bunch(kw)
   if not kw.timer: kw.timer = rp.Timer().start()

   lj_sfxn = get_sfxn('sterics')

   sym1 = xspec.sym1
   orig1 = xspec.orig1
   axis1 = xspec.axis1
   axis1d = xspec.axis1d

   sym2 = xspec.sym2
   orig2 = xspec.orig2
   axis2 = xspec.axis2
   axis2d = xspec.axis2d

   dihedral = xspec.dihedral

   if np.allclose(orig2, [0, 0, 0, 1]):
      sym1, sym2 = sym2, sym1
      orig1, orig2 = orig2, orig1
      axis1, axis2 = axis2, axis1
      axis1d, axis2d = axis2d, axis1d
      swapped = True  # hopefully won't need this
      assert sym1 == metal_sym
      assert sym2 == peptide_sym
      # axis2 = np.array([0.57735, 0.57735, 0.57735, 0])
      # axis1 = np.array([1, 0, 0, 0])
      # orig2 = np.array([0.5, 0.5, 0, 1])
   elif np.allclose(orig1, [0, 0, 0, 1]):
      # assert np.allclose(orig1, [0, 0, 0, 1])
      assert sym1 == peptide_sym
      assert sym2 == metal_sym
      swapped = False
      # axis1 = np.array([0.57735, 0.57735, 0.57735, 0])
      # assert 0, 'maybe ok, check this new branch'
   else:
      # print('both sym elements not at origin')
      pass
      # raise NotImplementedError('both sym elements not at origin')

   if sym1 == peptide_sym:
      pt1, ax1 = peptide_orig, peptide_axis
      pt2, ax2 = metal_origin, metal_sym_axis
      first_is_peptide = True
   else:
      pt1, ax1 = metal_origin, metal_sym_axis
      pt2, ax2 = peptide_orig, peptide_axis
      first_is_peptide = False

   nfold1 = float(str(sym1)[1])
   nfold2 = float(str(sym2)[1])
   ax1 = ax1 / np.linalg.norm(ax1)
   ax2 = ax2 / np.linalg.norm(ax2)

   # print(rp.homog.line_angle(metal_sym_axis, peptide_axis), np.radians(dihedral))
   assert np.allclose(rp.homog.line_angle(metal_sym_axis, peptide_axis), np.radians(dihedral),
                      atol=1e-3)
   assert np.allclose(rp.homog.line_angle(ax1, ax2), np.radians(dihedral), atol=1e-3)

   # print(rp.homog.line_angle(ax1, ax2), np.radians(dihedral), dihedral)

   # print('sym1', sym1, orig1, axis1, ax1)
   # print('sym2', sym2, orig2, axis2, ax2)

   #
   # print('== xtal_build ==')

   # Xalign, _ = rp.homog.align_lines_isect_axis2(pt1, ax1, pt2, ax2, axis1, orig1, axis2, orig2)
   Xalign, scale = rp.homog.scale_translate_lines_isect_lines(pt1, ax1, pt2, ax2, orig1, axis1,
                                                              orig2, axis2)

   xpt1, xax1 = Xalign @ pt1, Xalign @ ax1
   xpt2, xax2 = Xalign @ pt2, Xalign @ ax2
   # print('aligned1', xpt1, xax1)
   # print('aligned2', xpt2, xax2)
   assert np.allclose(rp.homog.line_angle(xax1, axis1), 0.0, atol=0.001)
   assert np.allclose(rp.homog.line_angle(xax2, axis2), 0.0, atol=0.001)

   # from previous req that ax1 isect the origin??
   # assert np.allclose(rp.homog.line_angle(xpt1, axis1), 0.0, atol=0.001)

   isect_error2 = rp.homog.line_line_distance_pa(xpt2, xax2, [0, 0, 0, 1], orig2)
   assert np.allclose(isect_error2, 0, atol=0.001)

   # isect = rp.homog.line_line_closest_points_pa(xpt2, xax2, [0, 0, 0, 1], orig2)
   # isect = (isect[0] + isect[1]) / 2
   # orig = orig2  # not always??
   # celldims = [isect[i] / o for i, o in enumerate(orig[:3]) if abs(o) > 0.001]
   celldims = scale[:3]
   assert np.allclose(min(celldims), max(celldims), atol=0.001)
   celldim = abs(min(celldims))
   if not (kw.min_cell_size <= celldim <= kw.max_cell_size):
      print('     ', xspec.spacegroup, pdb_name, aa1, aa2, 'Fail on cell_size', celldim)
      return []

   nsym = int(peptide_sym[1])
   assert pose.size() % nsym == 0
   nres_asym = pose.size() // nsym
   xtal_pose = rt.protocols.grafting.return_region(pose, 1, nres_asym)

   solv_frac = mof.filters.approx_solvent_fraction(xtal_pose, xspec, celldim)
   if kw.max_solv_frac < solv_frac:
      print('     ', xspec.spacegroup, pdb_name, aa1, aa2, 'Fail on solv_frac', solv_frac)
      return []

   # rt.numeric.xyzVec(hz[0], hz[1], hz[2]))

   xtal_pose.apply_transform_Rx_plus_v(
      xyzMat.cols(Xalign[0, 0], Xalign[1, 0], Xalign[2, 0], Xalign[0, 1], Xalign[1, 1],
                  Xalign[2, 1], Xalign[0, 2], Xalign[1, 2], Xalign[2, 2]),
      xyzVec(Xalign[0, 3], Xalign[1, 3], Xalign[2, 3]))

   # check ZN sym center location vs zn position?????????

   # print('--------------')
   # print(celldim, orig1[:3], orig2[:3])
   # print('--------------')

   if xspec.frames is None:
      # raise NotImplementedError('no sym frames for', xspec.spacegroup)
      print(f'{f" generate sym frames for {spec.spacegroup} ":}')
      dummy_scale = 100.0
      if sym1 == peptide_sym:
         redundant_point = rp.homog.hpoint(dummy_scale * orig1[:3] + 10 * axis1[:3])
      else:
         redundant_point = rp.homog.hpoint(dummy_scale * orig2[:3] + 10 * axis2[:3])
      # redundant_point = rp.homog.rand_point()
      # redundant_point[:3] *= dummy_scale

      print('redundant_point', redundant_point)
      print(Xalign @ redundant_point)

      g1 = rp.homog.hrot(axis1, (2 * np.pi / nfold1) * np.arange(nfold1), dummy_scale * orig1[:3])
      g2 = rp.homog.hrot(axis2, (2 * np.pi / nfold2) * np.arange(nfold2), dummy_scale * orig2[:3])
      g = np.concatenate([g1, g2])
      symxforms = list()
      count = 0
      for x in rp.homog.expand_xforms(g, redundant_point=redundant_point, N=12,
                                      maxrad=3.0 * dummy_scale):
         symxforms.append(x)
         print(count)
         count += 1
      # rp.dump(list(symxforms), 'i213_redundant111_n16_maxrad2.pickle')
      # symxforms = rp.load('i213_redundant111_n16_maxrad2_ORIG.pickle')
      print('num symframes', len(symxforms), type(symxforms[0]))
      symxforms = np.stack(symxforms, axis=0)
      print('symframes shape', symxforms.shape)
      symxforms[:, :3, 3] /= dummy_scale
      # print(np.around(symxforms[:, :3, 3], 3))

      rp.dump(symxforms, 'new_symframes.pickle')

      symxforms[:, :3, 3] *= celldim
      rpxbody.move_to(Xalign)
      rpxbody.dump_pdb('body_I.pdb')
      for i, x in enumerate(symxforms):
         rpxbody.move_to(x @ Xalign)
         rpxbody.dump_pdb('body_%i.pdb' % i)

      assert 0, "must rerun with newly genrated symframes"

   symxforms = xspec.frames.copy()
   symxforms[:, :3, 3] *= celldim

   # g1 = rp.homog.hrot(axis1, (2 * np.pi / nfold1) * np.arange(0, nfold1), celldim * orig1[:3])
   # g2 = rp.homog.hrot(axis2, (2 * np.pi / nfold2) * np.arange(0, nfold2), celldim * orig2[:3])
   # # # print('g1', axis1.round(3), 360 / nfold1, (celldim * orig1[:3]).round(3))
   # # # print('g2', axis2.round(3), 360 / nfold2, (celldim * orig2[:3]).round(3))
   # if swapped: g1, g2 = g2, g1
   # g = np.concatenate([g1, g2])
   # # print('swapped', swapped)
   # redundant_point = (xpt1 + xax1) if first_is_peptide else (xpt2 + xax2)
   # # redundant_point = xpt1 if first_is_peptide else xpt2
   # # print('redundancy point', redundant_point)
   # # # rpxbody.move_to(np.eye(4))
   # # # rpxbody.dump_pdb('a_body.pdb')
   # rpxbody.move_to(Xalign)
   # # # print(0, Xalign @ rp.homog.hpoint([1, 2, 3]))
   # # rpxbody.dump_pdb('a_body_xalign.pdb')

   kw.timer.checkpoint()

   clash, tot_ncontact = False, 0
   rpxbody_pdb, ir_ic = rpxbody.str_pdb(warn_on_chain_overflow=False, use_orig_coords=False)
   body_xalign = rpxbody.copy()
   body_xalign.move_to(Xalign)
   # body_xalign.dump_pdb('body_xalign.pdb')
   prev = [np.eye(4)]
   for i, x in enumerate(symxforms):
      # rp.homog.expand_xforms(g, redundant_point=redundant_point, N=6, maxrad=30)):
      if np.allclose(x, np.eye(4), atol=1e-4): assert 0
      rpxbody.move_to(x @ Xalign)
      # rpxbody.dump_pdb('clashcheck%02i.pdb' % i)
      if debug:
         pdbstr, ir_ic = rpxbody.str_pdb(start=ir_ic, warn_on_chain_overflow=False,
                                         use_orig_coords=False)
         rpxbody_pdb += pdbstr
      if np.any(rpxbody.intersect(rpxbody,
                                  np.stack(prev) @ Xalign, x @ Xalign, mindis=clash_dis)):
         clash = True
         print('     ', xspec.spacegroup, pdb_name, aa1, aa2, 'Fail on xtal clash', f'sub{i+1}')
         return []

      ncontact = rpxbody.contact_count(body_xalign, maxdis=contact_dis)
      tot_ncontact += ncontact

      prev.append(x)

      #   if clash and debug:
      #    for xprev in prev:
      #       # print(xprev.shape, (xprev @ Xalign).shape, (x @ Xalign).shape)
      #       if rpxbody.intersect(rpxbody, xprev @ Xalign, x @ Xalign, mindis=3.0):
      #          show_body_isect(rpxbody, Xalign, maxdis=3.0)
      #          rp.util.dump_str(rpxbody_pdb, 'sym_bodies.pdb')
      #    assert 0

   if tot_ncontact < min_contacts:
      print('     ', xspec.spacegroup, pdb_name, aa1, aa2, 'Fail on ncontact', tot_ncontact)
      return []

   kw.timer.checkpoint('clash_check')

   # for i, x in enumerate(symxforms):
   #    # print('sym xform %02i' % i, rp.homog.axis_ang_cen_of(x)
   #    rpxbody.move_to(x @ Xalign)
   #    rpxbody.dump_pdb('clashframe_%02i.pdb' % i)

   # assert 0

   # print('!!!!!!!!!!!!!!!! debug clash check  !!!!!!!!!!!!!!!!!!!!!!!!!')
   # rpxbody.move_to(Xalign)
   # rpxbody.dump_pdb('body.pdb')
   # symxforms = rp.homog.expand_xforms(g, redundant_point=redundant_point, N=8, maxrad=30)
   # for i, x in enumerate(symxforms):
   #    # print('sym xform %02i' % i, rp.homog.axis_ang_cen_of(x))
   #    rpxbody.move_to(x @ Xalign)
   #    rpxbody.dump_pdb('clashcheck%02i.pdb' % i)
   #    if rpxbody.intersect(rpxbody, Xalign, x @ Xalign, mindis=3.0):
   #       util.show_body_isect(rpxbody, Xalign, maxdis=3.0)
   #       rp.util.dump_str(rpxbody_pdb, 'sym_bodies.pdb')
   # assert 0

   # assert 0, 'xtal build after clashcheck'

   # fname = f'{tag}_body_xtal.pdb'
   # print('dumping checked bodies', fname)

   ci = rt.core.io.CrystInfo()
   ci.A(celldim)  # cell dimensions
   ci.B(celldim)
   ci.C(celldim)
   ci.alpha(90)  # cell angles
   ci.beta(90)
   ci.gamma(90)
   ci.spacegroup(xspec.spacegroup)  # sace group
   pi = rt.core.pose.PDBInfo(xtal_pose)
   pi.set_crystinfo(ci)
   xtal_pose.pdb_info(pi)

   nonbonded_energy = 0
   if max_sym_score < 1000:
      sympose = xtal_pose.clone()
      rt.protocols.cryst.MakeLatticeMover().apply(sympose)
      syminfo = rt.core.pose.symmetry.symmetry_info(sympose)

      # rp.util.dump_str(rpxbody_pdb, 'symbodies.pdb')
      lj_sfxn(sympose)

      nasym = len(xtal_pose.residues)
      nchain = syminfo.subunits()  # sympose.num_chains()
      bonded_subunits = []
      nterm = sympose.residue(1).xyz('N')
      cterm = sympose.residue(nasym).xyz('C')
      for i in range(1, nchain):
         nres = i * nasym + 1
         cres = i * nasym + nasym
         if 2 > cterm.distance(sympose.residue(nres).xyz('N')):
            bonded_subunits.append(i + 1)
         if 2 > nterm.distance(sympose.residue(cres).xyz('C')):
            bonded_subunits.append(i + 1)

      energy_graph = sympose.energies().energy_graph()
      eweights = sympose.energies().weights()
      nonbonded_energy = 0
      for ichain in range(1, nchain):
         if ichain + 1 in bonded_subunits: continue
         for i in range(nasym):
            ir = ichain + i + 1
            for j in range(nasym):
               jr = j + 1
               edge = energy_graph.find_edge(ir, jr)
               if not edge:
                  continue
               nonbonded_energy += edge.dot(eweights)

      # print('nonbonded_energy', nonbonded_energy)
      if nonbonded_energy > max_sym_score:
         print('     ', xspec.spacegroup, pdb_name, aa1, aa2,
               'Fail on nonbonded_energy(max_sym_score)', nonbonded_energy)
         return []

   kw.timer.checkpoint('make sympose and "nonbonded" score')

   znpos = Xalign @ metal_origin
   znres = make_residue('VZN')
   xtal_pose.append_residue_by_jump(znres, 1)
   znresi = len(xtal_pose.residues)
   znpos = xyzVec(*znpos[:3])
   zndelta = znpos - xtal_pose.residue(znresi).xyz(1)
   for ia in range(1, xtal_pose.residue(znresi).natoms() + 1):
      newxyz = zndelta + xtal_pose.residue(znresi).xyz(ia)
      # print(xtal_pose.residue(znresi).name(), ia, xtal_pose.residue(znresi).atom_name(ia), newxyz)
      xtal_pose.set_xyz(AtomID(ia, znresi), newxyz)
   # xtal_pose.dump_pdb('a_xtal_pose.pdb')
   # assert 0
   # rp.util.dump_str(rpxbody_pdb, 'a_symframes.pdb')
   # assert 0

   return [(Xalign, xtal_pose, rpxbody_pdb, tot_ncontact, nonbonded_energy, solv_frac)]
Exemple #6
0
    def load(pose):
        """
        Load a :class:`Pose` object and return a populated :class:`Structure`
        instance

        Parameters
        ----------
        pose : :class:`Pose`
            PyRosetta :class:`Pose` object to convert
        """
        if not Pose or not AtomID:
            raise ImportError('Could not load the PyRosetta module.')
        if not isinstance(pose, Pose):
            raise TypeError('Object is not a PyRosetta Pose object.')

        struct = Structure()

        atnum = 1
        conf = pose.conformation()
        for resid in range(1, pose.total_residue() + 1):
            res = pose.residue(resid)
            resname = res.name3().strip()
            chain = chr(res.chain() + ord('A') - 1)
            for atno, at in enumerate(res.atoms(), start=1):
                try:
                    atinfo = res.atom_type(atno)
                    atname = res.atom_name(atno).strip()
                    if atinfo.is_virtual():
                        atsym = 'EP'
                    else:
                        atsym = atinfo.element()
                    rmin = atinfo.lj_radius()
                    epsilon = atinfo.lj_wdepth()
                    atomic_number = AtomicNum[atsym]
                    mass = Mass[atsym]
                except KeyError:
                    raise RosettaError('Could not recognize element: %s.' %
                                       atsym)

                params = dict(atomic_number=atomic_number,
                              name=atname,
                              charge=0.0,
                              mass=mass,
                              occupancy=0.0,
                              bfactor=0.0,
                              altloc='',
                              number=atnum,
                              rmin=rmin,
                              epsilon=epsilon)

                if atinfo.is_virtual():
                    atom = ExtraPoint(**params)
                else:
                    atom = Atom(**params)

                atom.xx, atom.xy, atom.xz = (at.xyz()[0], at.xyz()[1],
                                             at.xyz()[2])

                struct.add_atom(atom, resname, resid, chain, '')
                atnum += 1
                try:
                    for nbr in conf.bonded_neighbor_all_res(AtomID(
                            atno, resid)):
                        if nbr.rsd() < resid or (nbr.rsd() == resid
                                                 and nbr.atomno() < atno):
                            struct.bonds.append(
                                Bond(struct.atoms[_n_prior(pose, nbr)], atom))
                except:
                    raise RosettaError('Could not add bonds.')

        struct.unchange()
        return struct
print('accessing atoms from residue 5')
at5N = res5.atom('N')
at5CA = res5.atom("CA")
at5C = res5.atom("C")

print(at5N)
# TODO: above should print atom type key not magic number
# 2/23/9: hm, not sure this is possible b/c atom does not know which AtomTypeSet to use!

print('xyz of at5N:', at5N.xyz().x, at5N.xyz().y, at5N.xyz().z)
print('norm of xyz at5N:', at5N.xyz().norm)

print(res5.atoms())  # <-- Still missing

atomN = AtomID(1, 5)
atomCA = AtomID(2, 5)
atomC = AtomID(3, 5)
print('bond length of N-CA in residue 5 is ')
print(pose.conformation().bond_length(atomN, atomCA))
print('bond angle of N-CA-C in residue 5 is ')
print(pose.conformation().bond_angle(atomN, atomCA, atomC))
print('setting bond length of N-CA in residue 5 to 1.5A ')
pose.conformation().set_bond_length(atomN, atomCA, 1.5)
print('setting bond angle of N-CA-C in residue 5 to 90 ')
pose.conformation().set_bond_angle(atomN, atomCA, atomC, 90)
# TODO: make the above work with atom objects instead of atomIDs

print('pose was generated from this pdb file: ', pose.pdb_info().name())
print('pose numbering for chain A, residue 5, is ',
      pose.pdb_info().pdb2pose('A', 5))
Exemple #8
0
def minimize_mof_xtal(sfxn, xspec, pose, debug=False, **kw):
    kw = rp.Bunch(kw)
    #    try:
    #       print('''
    # minimize.py score initial....................      687.825
    # minimize.py: score before chem bonds.........      687.825
    # minimize.py: score after chem bonds..........      166.551
    # minimize.py: score after chainbreaks.........      166.551
    # minimize.py: score after metal olap .........      166.551
    # minimize.py: score after metal dist .........      176.766
    # minimize.py: score after metal dir...........      275.546
    # minimize.py: score after lig angle added.....      290.724
    # minimize.py: score after min no scale........      111.465
    # ==========================================================
    # '''.strip())
    #       os.remove('before.pdb')
    #       os.remove('zafter.pdb')
    #    except:
    #       pass

    nresasym = pose.size()
    beg = 1
    end = nresasym - 1
    metalres = rts.name_map('ZN')
    metalname = 'ZN'
    metalresnos = [nresasym, 2 * nresasym]  # TODO.. make not stupid
    metalnbonds = 4

    metalaid = AtomID(1, metalresnos[0])

    # cst_ang_metal = 109.47
    # cst_dis_metal = 2.2
    # cst_sd_metal_olap = 0.01
    # cst_sd_metal_dir = 0.4
    # cst_sd_metal_lig_dist = 0.2
    # cst_sd_metal_lig_ang = 0.4
    # cst_sd_metal_coo = 0.5
    # cst_sd_cut_dis = 0.01
    # cst_sd_cut_ang = 0.01
    # cst_sd_cut_dih = 0.1

    pose = pose.clone()
    r.core.pose.remove_lower_terminus_type_from_pose_residue(pose, beg)
    r.core.pose.remove_upper_terminus_type_from_pose_residue(pose, end)
    for ir in range(1, pose.size() + 1):
        if 'HIS' in pose.residue(ir).name():
            newname = pose.residue(ir).name().replace('HIS', 'HIS_D')
            newname = newname.replace('_D_D', '')
            r.core.pose.replace_pose_residue_copying_existing_coordinates(
                pose, ir, rts.name_map(newname))

    if False:
        tmp = pose.clone()
        r.core.pose.replace_pose_residue_copying_existing_coordinates(
            tmp, metalresnos[0], metalres)
        makelattice(tmp)
        tmp.dump_pdb('before.pdb')
    makelattice(pose)
    if debug:
        print(
            f'minimize.py score initial.................... {sfxn(pose):10.3f}'
        )
    # print_nonzero_energies(sfxn, pose)

    syminfo = r.core.pose.symmetry.symmetry_info(pose)
    symdofs = syminfo.get_dofs()
    allowed_jumps = list()
    # for jid, dofinfo in symdofs.items():
    #    # if dofinfo.allow_dof(1) and not any(dofinfo.allow_dof(i) for i in range(2, 7)):
    #    allowed_jumps.append(jid)
    # print('minimize_mof_xtal allowed jumps:', allowed_jumps)
    nxyz = pose.residue(beg).xyz('N')
    cxyz = pose.residue(end).xyz('C')
    nac, cac = None, None  # (N/C)-(a)djacent (c)hain
    for isub in range(1, syminfo.subunits()):
        othern = pose.residue((isub + 0) * nresasym + 1).xyz('N')
        otherc = pose.residue((isub + 1) * nresasym - 1).xyz('C')
        if nxyz.distance(otherc) < 2.0: cac = (isub + 1) * nresasym - 1
        if cxyz.distance(othern) < 2.0: nac = (isub + 0) * nresasym + 1
    assert nac and cac, 'backbone is weird?'
    if debug: print('peptide connection 1:', cac, beg)
    if debug: print('peptide_connection 2:', end, nac)
    # pose.dump_pdb('check_cuts.pdb')
    # assert 0

    f_metal_lig_dist = r.core.scoring.func.HarmonicFunc(
        kw.cst_dis_metal, kw.cst_sd_metal_lig_dist)
    f_metal_lig_ang = r.core.scoring.func.HarmonicFunc(
        np.radians(kw.cst_ang_metal), kw.cst_sd_metal_lig_ang)
    f_metal_olap = r.core.scoring.func.HarmonicFunc(0.0, kw.cst_sd_metal_olap)
    f_point_at_metal = r.core.scoring.func.HarmonicFunc(
        0.0, kw.cst_sd_metal_dir)
    f_metal_coo = r.core.scoring.func.CircularHarmonicFunc(
        0.0, kw.cst_sd_metal_coo)
    f_cut_dis = r.core.scoring.func.HarmonicFunc(1.328685, kw.cst_sd_cut_dis)
    f_cut_ang_cacn = r.core.scoring.func.HarmonicFunc(2.028, kw.cst_sd_cut_ang)
    f_cut_ang_cnca = r.core.scoring.func.HarmonicFunc(2.124, kw.cst_sd_cut_ang)
    f_cut_dih = r.core.scoring.func.CircularHarmonicFunc(
        np.pi, kw.cst_sd_cut_dih)
    f_cut_dihO = r.core.scoring.func.CircularHarmonicFunc(
        0.00, kw.cst_sd_cut_dih)

    ################### check cutpoint ##################

    conf = pose.conformation().clone()
    assert r.core.conformation.symmetry.is_symmetric(conf)
    # print(pose.pdb_info().crystinfo())
    pi = pose.pdb_info()
    # conf.detect_bonds()
    conf.declare_chemical_bond(cac, 'C', beg, 'N')
    # conf.declare_chemical_bond(end, 'N', nac, 'N')
    pose.set_new_conformation(conf)
    pose.set_new_energies_object(r.core.scoring.symmetry.SymmetricEnergies())
    pose.pdb_info(pi)
    if debug:
        print(
            f'minimize.py: score after chem bonds.......... {sfxn(pose):10.3f}'
        )

    #############################################3

    cst_cut, cst_lig_dis, cst_lig_ang, cst_lig_ori = list(), list(), list(
    ), list()

    ############### chainbreaks ################3

    # this doesn't behave well...
    # # 39 C / 1 OVU1
    # # 39 OVL1 / 1 N
    # # 29 OVL2 / CA
    # r.core.pose.add_variant_type_to_pose_residue(pose, 'CUTPOINT_UPPER', beg)
    # r.core.pose.add_variant_type_to_pose_residue(pose, 'CUTPOINT_LOWER', end)
    # cres1 = pose.residue(cac)
    # nres1 = pose.residue(1)
    # cres2 = pose.residue(end)
    # nres2 = pose.residue(nac)
    # # Apc = r.core.scoring.constraints.AtomPairConstraint
    # # getaid = lambda p, n, i: AtomID(p.residue(i).atom_index(n.strip()), i)
    # for cst in [
    #       Apc(getaid(pose, 'C   ', cac), getaid(pose, 'OVU1', beg), f_cut),
    #       Apc(getaid(pose, 'OVL1', cac), getaid(pose, 'N   ', beg), f_cut),
    #       Apc(getaid(pose, 'OVL2', cac), getaid(pose, 'CA  ', beg), f_cut),
    #       Apc(getaid(pose, 'C   ', end), getaid(pose, 'OVU1', nac), f_cut),
    #       Apc(getaid(pose, 'OVL1', end), getaid(pose, 'N   ', nac), f_cut),
    #       Apc(getaid(pose, 'OVL2', end), getaid(pose, 'CA  ', nac), f_cut),
    # ]:
    #    pose.add_constraint(cst)

    cst_cut.append(addcst_dis(pose, cac, 'C ', beg, 'N', f_cut_dis))
    cst_cut.append(addcst_dis(pose, end, 'C ', nac, 'N', f_cut_dis))
    if debug:
        print(
            f'minimize.py: score after chainbreak dis...... {sfxn(pose):10.3f}'
        )
    cst_cut.append(
        addcst_ang(pose, cac, 'CA', cac, 'C', beg, 'N ', f_cut_ang_cacn))
    cst_cut.append(
        addcst_ang(pose, cac, 'C ', beg, 'N', beg, 'CA', f_cut_ang_cnca))
    cst_cut.append(
        addcst_ang(pose, end, 'CA', end, 'C', nac, 'N ', f_cut_ang_cacn))
    cst_cut.append(
        addcst_ang(pose, end, 'C ', nac, 'N', nac, 'CA', f_cut_ang_cnca))
    if debug:
        print(
            f'minimize.py: score after chainbreak ang...... {sfxn(pose):10.3f}'
        )
    # print(r.numeric.dihedral(
    #       pose.residue(cac).xyz('CA'),
    #       pose.residue(cac).xyz('C'),
    #       pose.residue(beg).xyz('N'),
    #       pose.residue(beg).xyz('CA'),
    #    ))
    cst_cut.append(
        addcst_dih(pose, cac, 'CA', cac, 'C', beg, 'N ', beg, 'CA', f_cut_dih))
    cst_cut.append(
        addcst_dih(pose, end, 'CA', end, 'C', nac, 'N ', nac, 'CA', f_cut_dih))
    cst_cut.append(
        addcst_dih(pose, cac, 'O ', cac, 'C', beg, 'N ', beg, 'CA',
                   f_cut_dihO))
    cst_cut.append(
        addcst_dih(pose, end, 'O ', end, 'C', nac, 'N ', nac, 'CA',
                   f_cut_dihO))
    if debug:
        print(
            f'minimize.py: score after chainbreak dihedral. {sfxn(pose):10.3f}'
        )

    ############## metal constraints ################

    for i, j in [(i, j) for i in metalresnos for j in metalresnos if i < j]:
        addcst_dis(pose, i, metalname, j, metalname, f_metal_olap)
    if debug:
        print(
            f'minimize.py: score after metal olap ......... {sfxn(pose):10.3f}'
        )

    allowed_elems = 'NOS'
    znpos = pose.residue(metalresnos[0]).xyz(1)
    znbonded = list()
    for ir in range(1, len(pose.residues) + 1):
        res = pose.residue(ir)
        if not res.is_protein(): continue
        for ia in range(5, res.nheavyatoms() + 1):
            aid = AtomID(ia, ir)
            elem = res.atom_name(ia).strip()[0]
            if elem in allowed_elems:
                xyz = pose.xyz(aid)
                dist = xyz.distance(znpos)
                if dist < 3.5:
                    if res.atom_name(ia) in (
                            ' OD2', ' OE2'):  # other COO O sometimes closeish
                        continue
                    znbonded.append(aid)
    if len(znbonded) != metalnbonds:
        print('WRONG NO OF LIGANDING ATOMS', len(znbonded))
        for aid in znbonded:
            print(
                pose.residue(aid.rsd()).name(),
                pose.residue(aid.rsd()).atom_name(aid.atomno()))
            pose.dump_pdb('WRONG_NO_OF_LIGANDING_ATOMS.pdb')
            return None, None
        # raise ValueError(f'WRONG NO OF LIGANDING ATOMS {len(znbonded)}')

    # metal/lig distance constraints
    for i, aid in enumerate(znbonded):
        cst = r.core.scoring.constraints.AtomPairConstraint(
            metalaid, aid, f_metal_lig_dist)
        cst_lig_dis.append(cst)
        pose.add_constraint(cst)

    if debug:
        print(
            f'minimize.py: score after metal dist ......... {sfxn(pose):10.3f}'
        )

    # for aid in znbonded:
    #    print(aid.rsd(), aid.atomno(),
    #          pose.residue(aid.rsd()).name(),
    #          pose.residue(aid.rsd()).atom_name(aid.atomno()))
    # assert 0

    # lig/metal/lig angle constraints (or dihedral in-place constraint for COO)
    # TODO kinda hacky... will need to be more general?
    for i, aid in enumerate(znbonded):
        ir, res = aid.rsd(), pose.residue(aid.rsd())
        if all(_ not in res.name() for _ in 'ASP CYS HIS GLU'.split()):
            assert 0, f'unrecognized res {res.name()}'
        if any(_ in res.name() for _ in 'ASP GLU'.split()):
            # metal comes off of OD1/OE1
            ir, coo = aid.rsd(), ('OD1 CG OD2' if 'ASP' in res.name() else
                                  'OE1 CD OE2').split()
            cst_lig_ori.append(
                addcst_dih(pose, ir, coo[0], ir, coo[1], ir, coo[2],
                           metalaid.rsd(), metalname, f_metal_coo))
        else:
            if 'HIS' in res.name(): aname = 'HD1' if res.has('HD1') else 'HE2'
            if 'CYS' in res.name(): aname = 'HG'
            cst_lig_ori.append(
                addcst_ang(pose, ir, res.atom_name(aid.atomno()),
                           metalaid.rsd(), metalname, ir, aname,
                           f_point_at_metal))
            # cst = r.core.scoring.constraints.AngleConstraint(aid, metalaid, aid2, f_point_at_metal)
            # pose.add_constraint(cst)
    if debug:
        print(
            f'minimize.py: score after metal dir........... {sfxn(pose):10.3f}'
        )

    for i, iaid in enumerate(znbonded):
        for j, jaid in enumerate(znbonded[:i]):
            # pripnt(i, j)
            cst = r.core.scoring.constraints.AngleConstraint(
                iaid, metalaid, jaid, f_metal_lig_ang)
            cst_lig_ang.append(cst)
            pose.add_constraint(cst)

    if debug:
        print(
            f'minimize.py: score after lig angle added..... {sfxn(pose):10.3f}'
        )

    ################ minimization #########################

    movemap = r.core.kinematics.MoveMap()
    movemap.set_bb(True)
    movemap.set_chi(True)
    movemap.set_jump(False)
    for i in allowed_jumps:
        movemap.set_jump(True, i)
    minimizer = r.protocols.minimization_packing.symmetry.SymMinMover(
        movemap, sfxn, 'lbfgs_armijo_nonmonotone', 0.01, True)  # tol, nblist
    if sfxn.has_nonzero_weight(r.core.scoring.ScoreType.cart_bonded):
        minimizer.cartesian(True)
    minimizer.apply(pose)
    if debug:
        print(
            f'minimize.py: score after min no scale........ {sfxn(pose):10.3f}'
        )

    # printscores(sfxn, pose)

    kw.timer.checkpoint(f'min scale 1.0')

    asym = r.core.pose.Pose()
    r.core.pose.symmetry.extract_asymmetric_unit(pose, asym, False)
    r.core.pose.replace_pose_residue_copying_existing_coordinates(
        asym, metalresnos[0], metalres)
    # asym.dump_pdb('asym.pdb')

    # for ir in metalresnos:
    #    r.core.pose.replace_pose_residue_copying_existing_coordinates(pose, ir, metalres)
    # pose.dump_pdb('zafter.pdb')

    if debug: print(kw.timer)

    info = rp.Bunch()
    info.score = sfxn(pose)

    ############### score component stuff ################
    st = r.core.scoring.ScoreType
    etot = pose.energies().total_energies()
    info.score_fa_atr = (etot[st.fa_atr])
    info.score_fa_rep = (etot[st.fa_rep])
    info.score_fa_sol = (etot[st.fa_sol])
    info.score_lk_ball = (etot[st.lk_ball] + etot[st.lk_ball_iso] +
                          etot[st.lk_ball_bridge] +
                          etot[st.lk_ball_bridge_uncpl])
    info.score_fa_elec = (etot[st.fa_elec] + etot[st.fa_intra_elec])
    info.score_hbond_sr_bb = (etot[st.hbond_sr_bb] + etot[st.hbond_lr_bb] +
                              etot[st.hbond_bb_sc] + etot[st.hbond_sc])
    info.score_dslf_fa13 = (etot[st.dslf_fa13])
    info.score_atom_pair_constraint = (etot[st.atom_pair_constraint])
    info.score_angle_constraint = (etot[st.angle_constraint])
    info.score_dihedral_constraint = (etot[st.dihedral_constraint])
    info.score_omega = (etot[st.omega])
    info.score_rotamer = (etot[st.fa_dun] + etot[st.fa_dun_dev] +
                          etot[st.fa_dun_rot] + etot[st.fa_dun_semi] +
                          etot[st.fa_intra_elec] + etot[st.fa_intra_rep] +
                          etot[st.fa_intra_atr_xover4] +
                          etot[st.fa_intra_rep_xover4] +
                          etot[st.fa_intra_sol_xover4])
    info.score_ref = (etot[st.ref])
    info.score_rama_prepro = (etot[st.rama_prepro])
    info.score_cart_bonded = (etot[st.cart_bonded])
    info.score_gen_bonded = (etot[st.gen_bonded])

    ############### cst stuff ################
    pose.remove_constraints()
    info.score_wo_cst = sfxn(pose)

    [pose.add_constraint(cst) for cst in cst_cut]
    info.score_cst_cut = sfxn(pose) - info.score_wo_cst
    pose.remove_constraints()

    [pose.add_constraint(cst) for cst in cst_lig_dis]
    [pose.add_constraint(cst) for cst in cst_lig_ang]
    [pose.add_constraint(cst) for cst in cst_lig_ori]
    info.score_cst_lig_ori = sfxn(pose) - info.score_wo_cst
    pose.remove_constraints()

    [pose.add_constraint(cst) for cst in cst_lig_dis]
    info.score_cst_lig_dis = sfxn(pose) - info.score_wo_cst
    pose.remove_constraints()

    [pose.add_constraint(cst) for cst in cst_lig_ang]
    info.score_cst_lig_ang = sfxn(pose) - info.score_wo_cst
    pose.remove_constraints()

    [pose.add_constraint(cst) for cst in cst_lig_ori]
    info.score_cst_lig_ori = sfxn(pose) - info.score_wo_cst
    pose.remove_constraints()

    return asym, info
Exemple #9
0
import pyrosetta.rosetta as rosetta

from pyrosetta import init, get_fa_scorefxn, AtomID
from pyrosetta.rosetta import core, protocols

init(
    extra_options="-constant_seed"
)  # WARNING: option '-constant_seed' is for testing only! MAKE SURE TO REMOVE IT IN PRODUCTION RUNS!!!!!
import os
os.chdir('.test.output')

print('constraints ----------------------------------------------')

pose = core.import_pose.pose_from_file("../test/data/test_in.pdb")

scorefxn = get_fa_scorefxn()  #  create_score_function('standard')
scorefxn.set_weight(core.scoring.atom_pair_constraint, 10)
scorefxn(pose)

print()
print('Score before constraints applied:', scorefxn(pose))

hterm2 = AtomID(1, 55)
gterm2 = AtomID(1, 5)

GF = core.scoring.func.GaussianFunc(4.0, 2.0)
apc = core.scoring.constraints.AtomPairConstraint(hterm2, gterm2, GF)
pose.add_constraint(apc)

print('Score after constraints applied:', scorefxn(pose))