Ejemplo n.º 1
0
        def test_rosetta_scripts(self):
            test_protocol = """
            <ROSETTASCRIPTS>
                <TASKOPERATIONS>
                    <RestrictToRepacking name="repack"/>
                </TASKOPERATIONS>
                <MOVERS>
                    <PackRotamersMover name="pack" task_operations="repack"/>
                </MOVERS>
                <PROTOCOLS>
                    <Add mover="pack"/>
                </PROTOCOLS>
            </ROSETTASCRIPTS>
            """

            test_pose = io.pose_from_sequence("TEST")
            test_task = rosetta_scripts.SingleoutputRosettaScriptsTask(
                test_protocol)

            logging.info("dask client: %s", self.client)
            task = self.client.submit(test_task, test_pose)
            result = task.result()
            self.assertEqual(
                packed_pose.to_pose(result).sequence(),
                packed_pose.to_pose(test_pose).sequence())
Ejemplo n.º 2
0
def to_silent(inp, output_filename):
    """Takes a Pose, PackedPose, or a list and outputs them as a silent file.
    This currently only outputs to a binary silent file.

    Inputs:
    poses: Pose object, PackedPose object or list of either.
    output_filename: The desired name of the output silent file.

    Example:
    pyrosetta.distributed.io.to_silent(poses, "mydesigns.silent")

    The decoy name in your silent file is take from pose.pdb_info().name()
    To set a different decoy name, change it in your pose before calling this function.
    To change the name, you must have a Pose object, not a PackedPose
    Example:
    pose = pyrosetta.distributed.packed_pose.to_pose(packed_pose)
    pose.pdb_info().name("my_tag")

    @srgerb
    """
    if isinstance(inp, (list, tuple, set)):
        pose = [to_pose(p) for p in inp]
    else:
        pose = to_pose(inp)
    pyrosetta.io.poses_to_silent(pose, output_filename)
Ejemplo n.º 3
0
    def test_silent_io(self):

        with tempfile.TemporaryDirectory() as workdir:

            # Tests if single pose is written to silent file and returned unchanged.
            test_packed_pose = io.pose_from_sequence("TESTTESTTEST")
            test_pose = packed_pose.to_pose(test_packed_pose)
            tmp_file = os.path.join(workdir, "temp.silent")
            io.to_silent(test_packed_pose, tmp_file)
            returned_poses = [
                packed_pose.to_pose(p) for p in io.poses_from_silent(tmp_file)
            ]

            # Tests that the amino acid sequences does not change after
            # being written to silent file and read back in.
            # Cannot just assert that the two poses are equal,
            # because writing them to the silent file adds score lines.
            self.assertEqual(test_pose.sequence(),
                             returned_poses[0].sequence(),
                             msg="Single sequence recovery failed.")

            # Tests that the positions of atoms are almost identical after
            # being written to silent file and read back in.
            # Rmsd will not quite be equal because the output silent file
            # truncates xyz coordinates to the third decimal place.
            self.assertAlmostEqual(
                0.,
                pyrosetta.rosetta.core.scoring.all_atom_rmsd(
                    test_pose, returned_poses[0]),
                places=3,
                msg="Single position recovery failed.")

            # Test if a list of poses can be written to a silent file
            # and returned unchanged.
            test_packed_poses = [
                io.pose_from_sequence("TEST" * i) for i in range(1, 5)
            ]
            test_poses = [packed_pose.to_pose(p) for p in test_packed_poses]
            tmp_file = os.path.join(workdir, "temp_list.silent")
            io.to_silent(test_packed_poses, tmp_file)
            returned_poses = [
                packed_pose.to_pose(p) for p in io.poses_from_silent(tmp_file)
            ]
            for i in range(len(test_poses)):
                self.assertEqual(test_poses[i].sequence(),
                                 returned_poses[i].sequence(),
                                 msg="List sequence recovery failed.")
                self.assertAlmostEqual(
                    0.,
                    pyrosetta.rosetta.core.scoring.all_atom_rmsd(
                        test_poses[i], returned_poses[i]),
                    places=3,
                    msg="List position recovery failed.")
def pose_coords_as_rows(pack_or_pose, selection=list(), atom_names=list()):
    """Construct an ndarray of x, y, and z coordinates from all residues in selection
        and atom names in <atom_names> from <pose> as rows and return it.

    Args:
        pack_or_pose (pyrosetta.rosetta.core.pose.Pose OR pyrosetta.distributed.packed_pose.PackedPose):
            the `Pose` instance from which coordinates will be extracted.
        selection (list): a list of residue numbers to use. Defaults to all residues.
        atom_names (list): a list of atom names to include. Defaults to all atoms.

    Returns:
        numpy.ndarray: an Nx3 array of coordinates.
    """
    import pyrosetta.distributed.packed_pose as packed_pose
    import numpy as np

    wpose = packed_pose.to_pose(pack_or_pose)

    # default to all residues
    if not selection:
        selection = range(1, wpose.total_residue() + 1)

    coords = np.array([
        res.xyz(atom) for res in [wpose.residues[s] for s in selection]
        for atom in range(1,
                          res.natoms() + 1)
        if (not atom_names or res.atom_name(atom).strip() in atom_names)
    ])
    return coords
Ejemplo n.º 5
0
def circularly_permute(pose, new_Nterm_pdb_res):
    
    lines_list = io.to_pdbstring(pose).split("\n")
    
    new_lines_list = []
    for line in lines_list:
        if line.startswith("ATOM"):
            pdb_res = int(line[22:26].split()[-1])
            if pdb_res >= new_Nterm_pdb_res:
                 new_lines_list.append(line)
    for line in lines_list:
        if line.startswith("ATOM"):
            pdb_res = int(line[22:26].split()[-1])
            if pdb_res < new_Nterm_pdb_res:
                 new_lines_list.append(line)
    for line in lines_list:
        if line.startswith("HETATM"):
            new_lines_list.append(line)
    
    out_pose = packed_pose.to_pose(io.pose_from_pdbstring("\n".join(new_lines_list)))
    
    # Renumber pdb
    for i, s in enumerate(out_pose.sequence(), start=1):
        if s == "Z":
            out_pose.pdb_info().set_resinfo(res=i, chain_id="B", pdb_res=i)
            out_pose.residue(i).chain(2)
        else:
            out_pose.pdb_info().set_resinfo(res=i, chain_id="A", pdb_res=i)
            out_pose.residue(i).chain(1)
    
    return out_pose
Ejemplo n.º 6
0
    def apply(self, pack_or_pose):
        """Apply task returning a pose object."""
        protocol = self.parsed_protocol

        wpose = packed_pose.to_pose(pack_or_pose)

        with self.protocol_lock:
            protocol.apply(wpose)

            if protocol.get_last_move_status() != moves.MoverStatus.MS_SUCCESS:
                return
            else:
                return wpose
Ejemplo n.º 7
0
def mutate_residue(pack_or_pose,
                   mutant_position,
                   mutant_aa,
                   pack_radius=0.,
                   pack_scorefxn=None):
    """Replace the residue at a single position in a Pose with a new amino acid
        and repack any residues within user-defined radius of selected residue's
        center using.

    Args:
        pack_or_pose (pyrosetta.rosetta.core.pose.Pose OR pyrosetta.distributed.packed_pose.PackedPose):
                    the `Pose` instance to use.
        mutant_position (int): Pose-numbered position of the residue to mutate.
        mutant_aa (str): The single letter name for the desired amino acid.
        pack_radius (float): Radius used to define neighboring residues.
        pack_scorefxn (pyrosetta.ScoreFunction): `ScoreFunction` to use when repacking the `Pose`.
            Defaults to the standard `ScoreFunction`.
    """
    import pyrosetta
    import pyrosetta.distributed.packed_pose as packed_pose

    wpose = packed_pose.to_pose(pack_or_pose)

    if not wpose.is_fullatom():
        raise IOError("mutate_residue only works with fullatom poses")

    # create a standard scorefxn by default
    if not pack_scorefxn:
        pack_scorefxn = pyrosetta.get_score_function()

    # the numbers 1-20 correspond individually to the 20 proteogenic amino acids
    from pyrosetta.rosetta.core.chemical import aa_from_oneletter_code

    mutant_aa = int(aa_from_oneletter_code(mutant_aa))
    aa_bool = pyrosetta.Vector1([aa == mutant_aa for aa in range(1, 21)])

    # mutation is performed by using a PackerTask with only the mutant
    # amino acid available during design
    task = pyrosetta.standard_packer_task(wpose)
    task.nonconst_residue_task(mutant_position).restrict_absent_canonical_aas(
        aa_bool)

    # prevent residues from packing by setting the per-residue "options" of the PackerTask
    task = restrict_non_nbrs_from_repacking(wpose, mutant_position, task,
                                            pack_radius)

    # apply the mutation and pack nearby residues
    from pyrosetta.rosetta.protocols.minimization_packing import PackRotamersMover

    packer = PackRotamersMover(pack_scorefxn, task)
    packer.apply(wpose)
Ejemplo n.º 8
0
def to_pdbstring(inp):
    """Convert to pdb-formatted string with score and energy data.
    """
    from pyrosetta.rosetta.core.io.pdb import dump_pdb
    from pyrosetta.rosetta.core.io import StructFileRepOptions
    from pyrosetta.rosetta.std import ostringstream

    sfro = StructFileRepOptions()
    sfro.set_output_pose_cache_data(True)
    sfro.set_output_pose_energies_table(True)

    oss = ostringstream()
    dump_pdb(to_pose(inp), oss, sfro)

    return oss.bytes().decode()
Ejemplo n.º 9
0
    def apply(self, pack_or_pose):
        """Apply task generating pose objects."""
        protocol = self.parsed_protocol

        wpose = packed_pose.to_pose(pack_or_pose)

        with self.protocol_lock:
            protocol.apply(wpose)

            if protocol.get_last_move_status() != moves.MoverStatus.MS_SUCCESS:
                return

            while wpose:
                yield wpose
                wpose = protocol.get_additional_output()
Ejemplo n.º 10
0
def generate_resfile_from_pose(
    pack_or_pose,
    resfilename,
    pack=True,
    design=False,
    input_sc=True,
    freeze=list(),
    specific=dict(),
):
    """Generate a resfile from a pose and write it to a file.

    Args:
        pack_or_pose (pyrosetta.rosetta.core.pose.Pose OR pyrosetta.distributed.packed_pose.PackedPose):
            the `Pose` instance to use to for resfile creation.

        pack (bool): True allows packing, False disallows. Defaults to True.

        design (bool): True allows design using all amino acids, False disables design.
            Defaults to False.

        input_sc (bool): Toggles the inclusion of the original side-chain conformations.
            Defaults to True.

        freeze (list): An optional list of residue numbers to exclude from packing and/or
            design.

        specific (dict): An optional dictionary with residue numbers and resfile keywords
            as key-value pairs.
    """
    # determine the header, default settings
    to_write = (
        (
            "NATAA\n"
            if not design
            else "ALLAA\n# ALLAA will NOT work on bridged Cysteines\n"
        )
        if pack
        else "NATRO\n"
    )
    to_write += ("USE_INPUT_SC\n" if input_sc else "") + "start\n"

    # use frozen list to update dict
    specific.update({resNo: "NATRO" for resNo in freeze})

    # use PDB numbering if possible
    import pyrosetta.distributed.packed_pose as packed_pose

    wpose = packed_pose.to_pose(pack_or_pose)
    info = wpose.pdb_info()
    if info and info.nres():
        res = [
            (info.number(resNo), info.chain(resNo), keyword)
            for resNo, keyword in specific.items()
        ]
    else:
        res = [(resNo, " ", keyword) for resNo, keyword in specific.items()]
    to_write += "\n".join(
        [
            str(num).rjust(4) + str(chain).rjust(3) + "  " + keyword + "  "
            for num, chain, keyword in res
        ]
    )

    with open(resfilename, "w") as f:
        f.write(to_write)