コード例 #1
0
def load_mem_pose(filename, opm_filename, params_paths=None):
    with pymol2.PyMOL() as pymol:
        #     pymol.cmd.load('SLC38A3_phyre.pdb', 'S38A3')
        pymol.cmd.load(filename, 'S38A3')
        # pymol.cmd.remove('resi 1-68 or resi 245-282 or resi 494-504')
        #     pymol.cmd.remove('resi 138-207 or resi 318-392')
        map_pdbblock = pymol.cmd.get_pdbstr()
        pymol.cmd.load(opm_filename, 'OPM')
        pymol.cmd.align('S38A3', 'OPM')
        pymol.cmd.remove('resn MEM')  # make sure its not there!
        pymol.cmd.delete('OPM')
        holo_pdbblock = pymol.cmd.get_pdbstr('polymer')
        lig_pdbblock = pymol.cmd.get_pdbstr('not polymer')
    #     pymol.cmd.save('test.pdb')
    pose = pyrosetta.Pose()
    if params_paths:
        pyrosetta.generate_nonstandard_residue_set(pose, params_paths)
    # pyrosetta.rosetta.core.import_pose.pose_from_file(pose, 'phyre.gln_Na.PO4.loop_r.pdb')
    pyrosetta.rosetta.core.import_pose.pose_from_pdbstring(pose, holo_pdbblock)

    addmem = pyrosetta.rosetta.protocols.membrane.AddMembraneMover(
        'from_structure')
    addmem.apply(pose)
    pyrosetta.rosetta.protocols.membrane.AqueousPoreFinder().apply(pose)
    ligpose = pyrosetta.Pose()
    pyrosetta.generate_nonstandard_residue_set(ligpose, params_paths)
    # pyrosetta.rosetta.core.import_pose.pose_from_file(pose, 'phyre.gln_Na.PO4.loop_r.pdb')
    pyrosetta.rosetta.core.import_pose.pose_from_pdbstring(
        ligpose, lig_pdbblock)
    pose.append_pose_by_jump(ligpose, pose.total_residue())
    return pose
コード例 #2
0
ファイル: util.py プロジェクト: weitzner/privileged_residues
def models_from_pdb(fname):
    """Get models from a PDB as individual poses.

    Parameters
    ----------
    fname : str
        Path to a PDB.

    Yields
    ------
    pyrosetta.Pose
        The next model in the PDB.
    """

    p = pyrosetta.Pose()

    with open(fname, "r") as f:
        model = []

        for l in f:
            if (l.startswith("#")):
                continue

            line = l.rstrip()
            model.append(line)

            if (line.startswith("ENDMDL")):
                pose_from_pdbstring(p, pdbcontents="\n".join(model))
                yield p.clone()
                model = []

        if (len(model)):
            pose_from_pdbstring(p, pdbcontents="\n".join(model))
            yield p.clone()
コード例 #3
0
    def from_pdbfile(cls,
                     pdbfile: str,
                     params_file: str,
                     constraint_file: str,
                     ligand_residue: Union[str, int, Tuple[int, str],
                                           pyrosetta.Vector1] = 'LIG',
                     key_residues: Union[None, Sequence[Union[int, str,
                                                              Tuple[int,
                                                                    str]]],
                                         pyrosetta.Vector1] = None):
        """
        Given a PDB with the ligand load it.

        :param pdbfile: pdb file
        :param params_file: params file
        :param constraint_file: filename
        :param ligand_residue: ligand -see class docstring
        :param key_residues: multiple entries -see class docstring
        :return:
        """
        pose = pyrosetta.Pose()
        params_paths = pyrosetta.rosetta.utility.vector1_string()
        params_paths.extend([params_file])
        pyrosetta.generate_nonstandard_residue_set(pose, params_paths)
        pyrosetta.rosetta.core.import_pose.pose_from_file(pose, pdbfile)
        return cls(pose, constraint_file, ligand_residue, key_residues)
コード例 #4
0
def fast_relax_mutant(pose, task_factory, move_map, score_function, decoys=1):
    """
    Runs Fast Relax on the mutant pose instead of just repack an minimize.
    Can modify to take varying amounts of decoys.
    """
    fast_relax = FastRelax(1)
    fast_relax.set_scorefxn(score_function)
    fast_relax.set_task_factory(task_factory)
    fast_relax.set_movemap(move_map)
    score_function(pose)
    packer = task_factory.create_task_and_apply_taskoperations(pose)
    print_out("packer task")
    print_out(packer)
    #sys.exit()
    traj_idx = 0
    lowest_energy = 1000.0
    print_out("emd182::Running Fast Relax")
    while traj_idx < decoys:
        print_out("Round Number: " + str(traj_idx))
        pose_copy = pr.Pose()
        pose_copy.assign(pose)
        print_out("emd182:: pose total residues: " + str(pose.total_residue()))
        fast_relax.apply(pose_copy)
        decoy_energy = total_energy(pose_copy, score_function)
        if traj_idx == '0':
            mutated_pose = pose_copy
            lowest_energy = decoy_energy
        elif decoy_energy < lowest_energy:
            mutated_pose = pose_copy
            lowest_energy = decoy_energy
        traj_idx += 1

    return mutated_pose
コード例 #5
0
def repack_and_minimize_mutant(pose,
                               task_factory,
                               move_map,
                               score_function,
                               rounds=3):
    #Copying the pose
    ram_pose = pr.Pose(pose)

    #preparing repack and applying
    prm = PackRotamersMover()
    prm.score_function(score_function)
    prm.task_factory(task_factory)

    #preparing minimize and applying
    min_mover = MinMover()
    min_mover.movemap(move_map)
    min_mover.score_function(score_function)

    print_out("Checking Packertask")
    packer = task_factory.create_task_and_apply_taskoperations(pose)
    print_out("packer task")
    print_out(packer)
    for rnd in range(rounds):
        print_out("round " + str(rnd + 1) + " of repack and min")
        prm.apply(ram_pose)
        min_mover.apply(ram_pose)
    return ram_pose
コード例 #6
0
def make_point_changes(pose, task_factory, score_function):
    """
    Applies point mutations to a given pose. This is done through a 
    PackRotamersMover, followed by minimization.
    Inputs are a Pose, a TaskFactory, and a ScoreFunction
    """
    # Make PackRotamersMover
    pack_rotamers = PackRotamersMover()
    pack_rotamers.score_function(score_function)
    pack_rotamers.task_factory(task_factory)

    # Make a copy Pose and apply the PackRotamersMover
    mutated_pose = pr.Pose(pose)
    pack_rotamers.apply(mutated_pose)

    # Set up fixed-backbone movemap for minimization
    movemap = pr.MoveMap()
    movemap.set_bb(True)
    movemap.set_chi(True)
    movemap.set_jump(True)

    # Create the MinMover
    min_mover = MinMover()
    min_mover.movemap(movemap)
    min_mover.score_function(score_function)

    # Apply the MinMover to the modified Pose
    min_mover.apply(mutated_pose)

    return mutated_pose
コード例 #7
0
    def __init__(self, native_pose):
        """Constructor

        Args:
            native_pose: A pyrosetta Pose object containing the native
                conformation. This is used for minimum Ca-RMSD
                calculation. If you don't need this calculation, or
                don't have the native conformation, just provide a
                random Pose object.
        """
        self.native_pose = pr.Pose()
        self.native_pose.assign(native_pose)
        self.total_energy_evals = 0
        self.last_op_energy_evals = 0
        self.min_ca_rmsd = math.inf
        self.last_op_min_ca_rmsd = math.inf
        self.min_ca_rmsd_pose = pr.Pose()
        self.last_op_min_ca_rmsd_pose = pr.Pose()
コード例 #8
0
 def score_ligand_alone(self):
     pose = pyrosetta.Pose()
     params_paths = pyrosetta.rosetta.utility.vector1_string()
     params_paths.extend(
         [f'{self.work_path}/{self.name}/{self.name}.params'])
     pyrosetta.generate_nonstandard_residue_set(pose, params_paths)
     pyrosetta.rosetta.core.import_pose.pose_from_file(
         pose, f'{self.work_path}/{self.name}/{self.name}.pdb')
     return pyrosetta.get_fa_scorefxn()(pose)
コード例 #9
0
 def to_polymeric_pose(self, relax=False, sequence: Optional[str] = None):
     if sequence is None:
         sequence = f'AX[{self.name}]A'
     pose = pyrosetta.Pose()
     rts = self.add_residuetype(pose)
     pyrosetta.rosetta.core.pose.make_pose_from_sequence(
         pose, sequence, rts)
     if relax:
         self._relax(pose)
     return pose
コード例 #10
0
 def __init__(self):
     warn('THIS METHOD SHOULD NOT BE RUN. INHERIT _init_')
     self.pose = pyrosetta.Pose()
     self.constraint_file = ''
     self.ligand_residue = []
     self.key_residues = []
     self.atom_pair_constraint = 10
     self.angle_constraint = 10
     self.coordinate_constraint = 1
     self.fa_intra_rep = 0.005  # default
コード例 #11
0
 def to_pose(self, relax=False):
     pose = pyrosetta.Pose()
     # add paramsblock
     rts = self.add_residuetype(pose)
     # add new residue
     lig = pyrosetta.rosetta.core.conformation.ResidueFactory.create_residue(
         rts.name_map(self.NAME))
     pose.append_residue_by_jump(lig, 1)
     if relax:
         self._relax(pose)
     return pose
コード例 #12
0
 def score_split(self, repack=False):
     split_pose = pyrosetta.Pose()
     split_pose.assign(self.pose)
     ResidueVector = pyrosetta.rosetta.core.select.residue_selector.ResidueVector
     x = self._get_selector(ligand_only=True).apply(split_pose)
     lig_pos = list(
         ResidueVector(
             self._get_selector(ligand_only=True).apply(split_pose)))[0]
     try:
         cys_pos = self.pose.residue(lig_pos).connect_map(1).resid()
         # RESCON: 305 LIG n-conn= 1 n-poly= 0 n-nonpoly= 1 conn# 1 22 145 3
         split_pose.conformation().sever_chemical_bond(seqpos1=cys_pos,
                                                       res1_resconn_index=3,
                                                       seqpos2=lig_pos,
                                                       res2_resconn_index=1)
     except RuntimeError:
         warn('No covalent bond with the ligand.')
     xyz = pyrosetta.rosetta.numeric.xyzVector_double_t()
     xyz.x = 500.0
     xyz.y = 0.0
     xyz.z = 0.0
     for a in range(1, split_pose.residue(lig_pos).natoms() + 1):
         split_pose.residue(lig_pos).set_xyz(
             a,
             split_pose.residue(lig_pos).xyz(a) + xyz)
     scorefxn = pyrosetta.rosetta.core.scoring.ScoreFunctionFactory.create_score_function(
         "ref2015")
     if repack:
         # get neighbourhood
         self._get_selector(ligand_only=True)
         NeighborhoodResidueSelector = pyrosetta.rosetta.core.select.residue_selector.NeighborhoodResidueSelector
         ns = NeighborhoodResidueSelector(
             self._get_selector(ligand_only=True),
             distance=7,
             include_focus_in_subset=True)
         nsv = pyrosetta.rosetta.core.select.residue_selector.ResidueVector(
             ns.apply(self.pose))
         fake_selector = pyrosetta.rosetta.core.select.residue_selector.ResidueIndexSelector(
             nsv)
         ## repack
         operation = pyrosetta.rosetta.core.pack.task.operation
         allow = operation.RestrictToRepackingRLT()
         restrict_to_focus = operation.OperateOnResidueSubset(
             allow, fake_selector, True)
         tf = pyrosetta.rosetta.core.pack.task.TaskFactory()
         tf.push_back(operation.PreventRepacking())
         tf.push_back(restrict_to_focus)
         packer = pyrosetta.rosetta.protocols.minimization_packing.PackRotamersMover(
             scorefxn)
         packer.task_factory(tf)
         packer.apply(split_pose)
     x = scorefxn(split_pose)
     b = scorefxn(self.pose)
     return {'xyz_unbound': x, 'xyz_bound': b, 'xyz_∆∆G': b - x}
コード例 #13
0
    def monte_carlo_fixed(self, pose, mover, score_function, temperature,
                          trajectory, fixed_moves):
        """Performs Metropolis Monte Carlo (MMC) search with a specified
        move, a fixed number of times in different trajectories. Each
        trajectory is created by performing moves from the initial
        conformation passed in the argument.

        Args:
            pose: A pyrosetta Pose object containing initial
                conformation.
            mover: A pyrosetta Mover object derermining the moves in MMC
                search.
            score_function: A pyrosetta ScoreFunction object for scoring
                each move.
            temperature: An int/float defining the temperature of MMC
                search.
            trajectory: A positive int indicating the number of
                trajectories.
            fixed_moves: A positive int indicating the number of moves
                in each trajectory.

        Returns:
            A list containing the population generated by the MMC
            search.
        """
        population = []

        # Perform MMC on all trajectories
        for i in range(trajectory):
            new_pose = pr.Pose()
            new_pose.assign(pose)
            mc = pr.MonteCarlo(new_pose, score_function, temperature)
            trial_mover = pr.TrialMover(mover, mc)

            # Perform MMC for a fixed number of moves
            for j in range(fixed_moves):
                trial_mover.apply(new_pose)
                pose_ca_rmsd = pr.rosetta.core.scoring.CA_rmsd(
                    self.native_pose, new_pose)
                if pose_ca_rmsd < self.last_op_min_ca_rmsd:
                    self.last_op_min_ca_rmsd = pose_ca_rmsd
                    self.last_op_min_ca_rmsd_pose.assign(new_pose)

            population.append(new_pose)

        # Bookkeeping
        self.last_op_energy_evals = (fixed_moves * trajectory)
        self.total_energy_evals += (fixed_moves * trajectory)
        if self.last_op_min_ca_rmsd < self.min_ca_rmsd:
            self.min_ca_rmsd = self.last_op_min_ca_rmsd
            self.min_ca_rmsd_pose.assign(self.last_op_min_ca_rmsd_pose)

        return population
コード例 #14
0
 def make_pose(self, pdbblock) -> pyrosetta.Pose:
     pose = pyrosetta.Pose()
     params_paths = pyrosetta.rosetta.utility.vector1_string()
     params_paths.extend(
         [f"{self.work_path}/{self.name}/{self.name}.params"])
     pyrosetta.generate_nonstandard_residue_set(pose, params_paths)
     pyrosetta.rosetta.core.import_pose.pose_from_pdbstring(pose, pdbblock)
     # fix protonation of HIS41.
     r = pose.pdb_info().pdb2pose(res=41, chain='A')
     MutateResidue = pyrosetta.rosetta.protocols.simple_moves.MutateResidue
     MutateResidue(target=r, new_res='HIS_D').apply(pose)
     MutateResidue(target=r, new_res='HIS').apply(pose)
     return pose
コード例 #15
0
 def create_apo(cls, template_pdbfilename: str):
     with pymol2.PyMOL() as pymol:
         pymol.cmd.load(template_pdbfilename)
         pymol.cmd.remove('solvent')
         pymol.cmd.remove(
             'resn DMS'
         )  # should run it through P Curran\s list of artefacts!
         apo = pymol.cmd.get_pdbstr('not resn LIG')
     pose = pyrosetta.Pose()
     pyrosetta.rosetta.core.import_pose.pose_from_pdbstring(pose, apo)
     scorefxn = pyrosetta.get_fa_scorefxn()
     relax = pyrosetta.rosetta.protocols.relax.FastRelax(scorefxn, 5)
     relax.apply(pose)
     pose.dump_pdb(cls.apo_pdbfilename)
コード例 #16
0
    def load_pose_from_file(self, filename: str) -> pyrosetta.Pose:
        """
        Loads a pose from filename with the params in the params_folder

        :param filename:
        :return:
        """
        pose = pyrosetta.Pose()
        # params_paths = pyrosetta.rosetta.utility.vector1_string()
        # params_paths.extend([os.path.join(self.params_folder, file) for file in os.listdir(self.params_folder)
        #                      if os.path.splitext(file)[1] == '.params'])
        # pyrosetta.generate_nonstandard_residue_set(pose, params_paths)
        pyrosetta.rosetta.core.import_pose.pose_from_file(pose, filename)
        return pose
コード例 #17
0
    def from_pdbblock(cls,
                      pdbblock: str,
                      params_file: str,
                      constraint_file: str,
                      ligand_residue: Union[str, int, Tuple[int, str], pyrosetta.Vector1] = 'LIG',
                      key_residues: Union[None, Sequence[Union[int, str, Tuple[int, str]]], pyrosetta.Vector1] = None):


        pose = pyrosetta.Pose()
        params_paths = pyrosetta.rosetta.utility.vector1_string()
        params_paths.extend([params_file])
        pyrosetta.generate_nonstandard_residue_set(pose, params_paths)
        pyrosetta.rosetta.core.import_pose.pose_from_pdbstring(pose, pdbblock)
        return cls(pose, constraint_file, ligand_residue, key_residues)
コード例 #18
0
 def _load_pose_from_file(cls, filename: str, params_filenames: Optional[List[str]] = None) -> pyrosetta.Pose:
     """
     Loads a pose from filename with the params in the params_folder
     :param filename:
     :param params_filenames:
     :return:
     """
     pose = pyrosetta.Pose()
     if params_filenames:
         params_paths = pyrosetta.rosetta.utility.vector1_string()
         params_paths.extend(params_filenames)
         pyrosetta.generate_nonstandard_residue_set(pose, params_paths)
     pyrosetta.rosetta.core.import_pose.pose_from_file(pose, filename)
     return pose
コード例 #19
0
 def to_pose(self, relax=False):
     pose = pyrosetta.Pose()
     # add paramsblock
     rts = self.add_residuetype(pose)
     # add new residue
     lig = pyrosetta.rosetta.core.conformation.ResidueFactory.create_residue(
         rts.name_map(self.NAME))
     pose.append_residue_by_jump(lig, 1)
     if relax:
         cycles = 15
         scorefxn = pyrosetta.get_fa_scorefxn()
         relax = pyrosetta.rosetta.protocols.relax.FastRelax(
             scorefxn, cycles)
         relax.apply(pose)
     return pose
コード例 #20
0
 def replace_to_pose(self,
                     probe_name: str,
                     probe_smiles: str,
                     probe_resn: str = 'MMX') -> pyrosetta.Pose:
     pdb = self.replace(probe_smiles=probe_smiles,
                        probe_resn=probe_resn,
                        probe_name=probe_name)
     # pyrosetta.init(f'-extra_res_fa {probe_name}.params -mute all')
     pose = pyrosetta.Pose()
     params_paths = pyrosetta.rosetta.utility.vector1_string()
     params_paths.extend([f"{probe_name}.params"])
     nonstandard_residue_set = pyrosetta.generate_nonstandard_residue_set(
         pose, params_paths)
     pyrosetta.rosetta.core.import_pose.pose_from_pdbstring(pose, pdb)
     return pose
コード例 #21
0
    def params_to_pose(paramsfile: str, name: str) -> pyrosetta.Pose:
        """
        Staticmethod to get a pose from a params file.

        :param paramsfile: params file.
        :param name: 3-letter residue name.
        :return:
        """
        pose = pyrosetta.Pose()
        params_paths = pyrosetta.rosetta.utility.vector1_string()
        params_paths.extend([paramsfile])
        resiset = pyrosetta.generate_nonstandard_residue_set(
            pose, params_paths)
        lig = pyrosetta.rosetta.core.conformation.ResidueFactory.create_residue(
            rts.name_map(name))
        pose.append_residue_by_jump(lig, 1)
        return pose
コード例 #22
0
def pose_from_file(pdb_filename: str,
                   params_filenames: Optional[Union[pyrosetta.rosetta.utility.vector1_string, List[str]]] = None) \
        -> pyrosetta.Pose:
    """
    Return a pose like pose_from_file but with params.

    :param pdb_filename:
    :param params_filenames:
    :return:
    """
    pose = pyrosetta.Pose()
    if params_filenames and isinstance(
            params_filenames, pyrosetta.rosetta.utility.vector1_string):
        pyrosetta.generate_nonstandard_residue_set(pose, params_filenames)
    if params_filenames and isinstance(params_filenames, list):
        params_filenames2 = pyrosetta.rosetta.utility.vector1_string()
        params_filenames2.extend(params_filenames)
        pyrosetta.generate_nonstandard_residue_set(pose, params_filenames2)
    else:
        pass
    pyrosetta.rosetta.core.import_pose.pose_from_file(pose, pdb_filename)
    return pose
コード例 #23
0
 def calculate_score(self):
     split_pose = pyrosetta.Pose()
     split_pose.assign(self.pose)
     cys_pos = split_pose.pdb_info().pdb2pose(chain='A', res=145)
     lig_pos = split_pose.pdb_info().pdb2pose(chain='B', res=1)
     # RESCON: 305 LIG n-conn= 1 n-poly= 0 n-nonpoly= 1 conn# 1 22 145 3
     split_pose.conformation().sever_chemical_bond(seqpos1=cys_pos,
                                                   res1_resconn_index=3,
                                                   seqpos2=lig_pos,
                                                   res2_resconn_index=1)
     xyz = pyrosetta.rosetta.numeric.xyzVector_double_t()
     xyz.x = 500.0
     xyz.y = 0.0
     xyz.z = 0.0
     for a in range(1, split_pose.residue(lig_pos).natoms() + 1):
         split_pose.residue(lig_pos).set_xyz(
             a,
             split_pose.residue(lig_pos).xyz(a) + xyz)
     scorefxn = pyrosetta.rosetta.core.scoring.ScoreFunctionFactory.create_score_function(
         "ref2015")
     x = scorefxn(split_pose)
     b = scorefxn(self.pose)
     alone = self.score_ligand_alone()
     data = self.pose.energies().residue_total_energies_array(
     )  # structured numpy array
     i = lig_pos - 1  ##pose numbering is fortran style. while python is C++
     ligand_data = {
         data.dtype.names[j]: data[i][j]
         for j in range(len(data.dtype))
     }
     return {
         'xyz_unbound': x,
         'bound': b,
         'apriori_ligand': alone,
         'ligand_data': ligand_data,
         'xyz_difference': b - x
     }
コード例 #24
0
switch.apply(pose)
switch.apply(native_pose)

# Create score function for evaluation
score4_function = pr.create_score_function("score3", "score4L")
score4_function.set_weight(pr.rosetta.core.scoring.rama, 1)

population_size = int(conf['init']['population'])

eval_budget = int(conf['init']['evalbudget'])
no_of_decoys = int(conf['init']['noOfDecoys'])

min_ca_rmsd = math.inf
lowest_energy = math.inf

min_ca_rmsd_pose = pr.Pose()
lowest_energy_pose = pr.Pose()

# *****************************
# Generate initial population *
# *****************************

pop = pl.Population(native_pose)

# Create score function for stage1 MMC
scorefxn = pr.create_score_function(conf['initPopulation']['stage1score'])

# Create MFR mover for initial population
mover = pop.mutation_operator(int(conf['initPopulation']['fragmentLength']),
                              conf['initPopulation']['fragmentFile'])
コード例 #25
0
ファイル: ssdoublet.py プロジェクト: yakomaxa/ssdoublet
    sss = list(pose.secstruct())
    return sss, abego_list, aa_list


#prs.init()

args = sys.argv
infilename = args[1]
outfilename = args[2]
file = open(outfilename, mode="w")
file.write(
    "pdbname pdbnameid abego ss1 ss2 ss1_start ss1_end loop_start loop_end ss2_start ss2_end NLangle CLangle HHangle NNangle CCangle HHdihedral NLdihedral CLdihedral distloop aa_seq abego_seq sse_seq\n"
)
with open(infilename) as f:

    #unitcount=0
    for line in f:
        pose = prs.Pose()
        pose = prs.pose_from_pdb(line.split("\n")[0])
        pdbname = line.split("\n")[0].split("/")[-1]
        ss_list, abego_list, aa_list = pose2sseabego(pose)
        #print(aa_list)
        p2f.pose2features(pose,
                          ss_list,
                          abego_list,
                          aa_list=aa_list,
                          pdbname=pdbname,
                          fileobject=file)

    file.close()
コード例 #26
0
ファイル: protocol.py プロジェクト: dacarlin/bagel-benchmark
fmt = dict(
    zip('ANDRCQEGHILKMPFSTWYV', [
        'ALA', 'ASN', 'ASP', 'ARG', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE',
        'LEU', 'LYS', 'MET', 'PRO', 'PHE', 'SER', 'THR', 'TRP', 'TYR', 'VAL'
    ]))

with open('input_files/flags') as fn:
    flags = fn.read().replace('\n', ' ')

# init PyRosetta
pyrosetta.init(''.join(flags))

ligand_params = pyrosetta.Vector1(['input_files/pNPG.params'])
new_res_set = pyrosetta.generate_nonstandard_residue_set(ligand_params)

p = pyrosetta.Pose()
pyrosetta.pose_from_file(p, new_res_set, 'input_files/bglb.pdb')
scorefxn = pyrosetta.create_score_function('beta_cst')

add_cst = rosetta.protocols.enzdes.AddOrRemoveMatchCsts()
add_cst.cstfile('input_files/pNPG.enzdes.cst')
add_cst.set_cst_action(rosetta.protocols.enzdes.CstAction.ADD_NEW)
add_cst.apply(p)

target = int(mutant_name[1:-1])
new_res = fmt[mutant_name[-1]]
mut = rosetta.protocols.simple_moves.MutateResidue(target, new_res)
mut.apply(p)

# set up packing task
tf = rosetta.core.pack.task.TaskFactory()
コード例 #27
0
def main(args):

    #Determining if the ligand should be removed or not
    #Need to be moved here as checking if the lig remains is
    #Imperative for how the CST file is dealt with.
    out_ligand_file = 'yeslig'
    if args.remove_ligand:
        args.rigid_ligand = False
        out_ligand_file = 'nolig'

    params = [args.unnatural]
    uaa = params[0].split('/')[-1].strip(".params")
    if args.ligand_type == 'ligand':
        params.append(args.ligand_name)
        lig_name = args.ligand_name.split('/')[-1].strip('.params')

    init_args = ' '.join(['-run:preserve_header', '-extra_res_fa'] + params)

    #Adding enzdes constraint file - and editing it - if necessary
    if args.enzdes_constraint_file:
        if out_ligand_file == 'nolig':
            if args.ligand_type == 'protein':
                lig_search = args.residue_set
            elif args.ligand_type == 'ligand':
                lig_search = args.ligand_name
            args.input_pdb, args.enzdes_constraint_file = enzdes_constraint_eliminator(\
                    args.input_pdb, args.enzdes_constraint_file, ligand=lig_search )

        #init_args = init_args + " -enzdes::cstfile " + str(args.enzdes_constraint_file)


#Starting up rosetta with the appropriate params files -
#-- need both unnatural aa and ligand file to be added (if the ligand isn't a protein).
    print_out("emd182::Starting rosetta with the following parameters: " +
              init_args)
    pr.init(init_args)
    file_options = pr.rosetta.core.io.StructFileRepOptions()
    file_options.set_preserve_header(bool(True))

    pose = pr.pose_from_pdb(args.input_pdb)

    #Residue selection
    if args.residue_number != '0':
        delta_resi = ResidueIndexSelector(args.residue_number)

    #Determining if the interacting ligand is a protein or small molecule
    #and selecting the appropriate residues
    if args.ligand_type == 'protein':
        ligand = ResidueIndexSelector(args.residue_set)
    elif args.ligand_type == 'ligand':
        ligand = ResidueNameSelector()
        ligand.set_residue_name3(lig_name)

    #Adding the unnatural at the mutation site
    print_out("Loading Unnatural " + uaa + \
        " onto residue number " + args.residue_number )

    if args.residue_number in selector_to_vector(ligand, pose):
        print_out(
            "Selected residue number IS a part of the ligand. Don't do that. \
                Chosen residue number: " + str(args.residue_number))
    #Setting up Mutation function on the correct residue, so long as the
    #residue isn't #0
    if args.residue_number != '0':
        mutater = pr.rosetta.protocols.simple_moves.MutateResidue()
        mutating_residue = ResidueIndexSelector(args.residue_number)
        mutater.set_selector(mutating_residue)
        mutater.set_res_name(uaa)
        print_out("emd182::loading residue to mutate into: " +
                  str(args.residue_number))

    lig_vector = selector_to_vector(ligand, pose)
    if args.residue_number != '0':
        if args.ligand_type == 'protein' and delta_resi in lig_vector:
            print_out("Selected residue for mutation is part of input selection: " + \
                    delta_resi + " is selected, but is contained in " \
                    + str(lig_vector))
            print_out("Exiting the python script")
            sys.exit()

    print_out("emd182::Start mutations and relaxation script " \
        + str(args.nstruct) + " times.")

    if args.residue_number == '0':
        args.nstruct = 1

    for struct in range(0, args.nstruct):
        print_out(struct)
        mutant_pose = pr.Pose(pose)
        #Residue selection
        if args.residue_number != '0':
            delta_resi = ResidueIndexSelector(args.residue_number)

        #apply mutation
        if args.residue_number != '0':
            mutater.apply(mutant_pose)
            if args.dihedral_constraint_atoms:
                dihedral_atoms = args.dihedral_constraint_atoms.split(';')
                dihedral_values = args.dihedral_constraint_degrees.split(';')
                dihedral_cst_stdev = args.dihedral_constraint_stdev.split(';')
                for dihedrals in range(len(dihedral_atoms)):
                    apply_dihedral_constraint(dihedral_atoms[dihedrals].split(','), \
                                delta_resi, mutant_pose, dihedral_values[dihedrals],\
                                dihedral_cst_stdev[dihedrals])

        move_map = build_move_map(True, True, True)

        #Scoring the pose
        sf = pr.rosetta.core.scoring.ScoreFunction()
        if args.symmdef_file:
            #Setting a residueindexselector to eliminate all extra aa post design
            pre_symm_ris = ResidueIndexSelector()
            all_aa = []
            for i in range(1, mutant_pose.total_residue() + 1):
                all_aa.append(''.join(
                    mutant_pose.pdb_info().pose2pdb(i).split()))
            pre_symm_ris.set_index(','.join(all_aa))
            #sys.exit()
            #Symmetrizing
            sfsm = SetupForSymmetryMover(args.symmdef_file)
            sfsm.apply(mutant_pose)
            sf = pr.rosetta.core.scoring.symmetry.SymmetricScoreFunction()
            sf.add_weights_from_file('ref2015_cst')
        else:
            sf = pr.rosetta.core.scoring.ScoreFunction()
        sf.add_weights_from_file('ref2015_cst')

        sf(mutant_pose)

        #apply mutation
        if args.residue_number != '0':
            mutater.apply(mutant_pose)
            if args.dihedral_constraint_atoms:
                dihedral_atoms = args.dihedral_constraint_atoms.split(';')
                dihedral_values = args.dihedral_constraint_degrees.split(';')
                dihedral_cst_stdev = args.dihedral_constraint_stdev.split(';')
                for dihedrals in range(len(dihedral_atoms)):
                    apply_dihedral_constraint(dihedral_atoms[dihedrals].split(','), \
                                delta_resi, mutant_pose, dihedral_values[dihedrals],\
                                dihedral_cst_stdev[dihedrals])

        #Making appropriate residue selections base on if the ligand will be
        #Removed or not, as well as if the ligand is rigid or not.
        residues_around_ligand = ligand_neighbor_selection(ligand, args.radius, \
                mutant_pose, bool(args.rigid_ligand) )

        if args.residue_number != '0':
            residues_around_mutant = ligand_neighbor_selection(mutating_residue, \
                    args.radius, mutant_pose, True)

        design_around_mutant = None
        #if design is turned on, will design around the mutant.
        #Can add more variability later
        if args.design and args.residue_number != '0':
            designing_residues = ligand_neighbor_selection(mutating_residue, \
                    args.design, mutant_pose, False)

        #Combining the repacking neighborhoods around the ligand and mutant
        if args.residue_number != '0':
            repacking_neighbors = residue_selection(residues_around_ligand, \
                    residues_around_mutant)
        else:
            repacking_neighbors = ResidueIndexSelector(residues_around_ligand)

        #Specifically converting residue selectors to vectors, and removing the
        #Appropriate residue ids from the lists of repacking or designing residues
        repacking_resids = selector_to_vector(repacking_neighbors, mutant_pose)
        if args.rigid_ligand:
            lig_resids = selector_to_vector(ligand, mutant_pose)
            for res in lig_resids:
                if res in repacking_resids:
                    repacking_resids.remove(res)
            if args.design:
                designing_resids = selector_to_vector(designing_residues,
                                                      mutant_pose)
                for res in lig_resids:
                    if res in designing_resids:
                        repacking_resids.remove(res)

        #If the remove-ligand is called, will remove the ligand from the mutant pose
        #Change 'remove-ligand' to 'translate region - makes for
        if args.remove_ligand:
            used_xyzs = []
            for chain in args.remove_ligand.split(','):
                x, y, z = random_direction_selector(used_xyzs)
                used_xyzs.append(np.array([x, y, z]))
                trans_vec = pr.rosetta.numeric.xyzVector_double_t(x, y, z)
                trans = pr.rosetta.protocols.rigid.RigidBodyTransMover(
                    trans_vec)
                jump_id = pr.rosetta.core.pose.get_jump_id_from_chain(
                    chain, mutant_pose)
                trans.rb_jump(jump_id)
                trans.step_size(500.0)
                trans.apply(mutant_pose)

        tf = task_factory_builder(repacking_residues=repacking_resids, \
                designing_residues=design_around_mutant)

        move_map = build_move_map(True, True, True)

        #turn on match constraints if needed:
        if args.enzdes_constraint_file:
            if not args.remove_ligand:
                print_out(
                    'The code will break if the constraint file is attached \
                        to the ligand that is being removed')
            apply_match_constraints(mutant_pose, args.enzdes_constraint_file)
            print('just checking')

        #turn off constraints if requested - default is on
        if not args.no_constraints:
            mutant_pose = coord_constrain_pose(mutant_pose)

        #Repack or minimize if selected
        if args.fast_relax:
            print_out("Running With Fast Relax")
            new_pose = fast_relax_mutant(mutant_pose, tf, move_map, sf)
        else:
            print_out("Running repack and minimize")
            new_pose = repack_and_minimize_mutant(mutant_pose, tf, move_map,
                                                  sf)

        #output the name of the file
        #Includes original pdb namne, residue number and uaa, nstruct number,
        #and if the ligand is included or not.
        base_pdb_filename = args.input_pdb.split('/')[-1].split(
            '_')[0].replace('.pdb', '')
        outname = '{}_{}_{}_{}_{}.pdb'.format(base_pdb_filename, \
                args.residue_number, uaa, out_ligand_file, str(struct))
        if args.residue_number == '0':
            outname = '{}_{}_min.pdb'.format(base_pdb_filename, \
                    out_ligand_file)
        if args.out_suffix:
            outname = outname.replace(".pdb", args.out_suffix + ".pdb")
        print_out("Outputting protein file as : " + outname)

        out_dir = out_directory(args.out_directory)
        outname = '/'.join([out_dir, outname])
        print_out("Writing Outputting protein file as : " + outname)

        #Symmetry needs to be broken to load the proteins in another
        #script to analyze them symmetrically.
        if args.symmdef_file:
            full_out = outname.replace('.pdb', 'sym.pdb')
            new_pose.dump_pdb(full_out)
            not_symm = NotResidueSelector(pre_symm_ris)
            remove_symmetrized_aa = DeleteRegionMover()
            remove_symmetrized_aa.set_residue_selector(not_symm)
            remove_symmetrized_aa.apply(new_pose)
            new_pose.dump_pdb(outname)
        else:
            new_pose.dump_pdb(outname)
コード例 #28
0
import pyrosetta
import pyrosetta.rosetta as rosetta

pyrosetta.init()

if hasattr(rosetta, 'cereal'):  # check if this is a cereliazation build

    pose1 = pyrosetta.pose_from_sequence("ARNDCEQGHILKMFPSTWYV")
    pose2 = pyrosetta.pose_from_sequence("DDDDDD")

    # saving into oss stream
    oss = rosetta.std.ostringstream()
    arc = rosetta.cereal.BinaryOutputArchive(oss)
    pose1.save(arc)
    pose2.save(arc)

    # loading from oss stream
    pose1_l = pyrosetta.Pose()
    pose2_l = pyrosetta.Pose()
    iss = rosetta.std.istringstream(oss.bytes())
    arc = rosetta.cereal.BinaryInputArchive(iss)
    pose1_l.load(arc)
    pose2_l.load(arc)

    print('Pose1  :\n{}-----------------\n'.format(pose1))
    print('Pose1_l:\n{}-----------------\n'.format(pose1_l))
    print('Pose2  :\n{}-----------------\n'.format(pose2))
    print('Pose2_l:\n{}-----------------\n'.format(pose2_l))
    assert (pose1_l.sequence() == pose1.sequence())
    assert (pose2_l.sequence() == pose2.sequence())
コード例 #29
0
    def local_search(self, pose, mover, score_function, successive_failures):
        """Performs greedy local search to improve fitness of a
        conformation.

        This local search performs specific moves to map a conformation
        to a nearby local minimum in the energy surface. The search is
        terminated when a specific number of moves fail to improve the
        score based on a specific fitness function.

        Args:
            pose: A pyrosetta Pose object containing initial
                conformation.
            mover: A pyrosetta Mover object determining the moves in
                local search.
            score_function: A pyrosetta ScoreFunction object for scoring
                each move.
            successive_failures: An int indicating the threshold for
                consecutive number of failed moves in each trajectory.

        Returns:
            A pyrosetta Pose object containing the conformation with
            locally minimum fitness.
        """
        local_minima = pr.Pose()
        local_minima.assign(pose)

        new_pose = pr.Pose()
        new_pose.assign(pose)

        self.last_op_min_ca_rmsd = pr.rosetta.core.scoring.CA_rmsd(
            self.native_pose, new_pose)

        local_minima_score = score_function(local_minima)
        self.last_op_energy_evals = 1

        failed = 0
        # Perform greedy local search
        while failed < successive_failures:
            mover.apply(new_pose)

            pose_ca_rmsd = pr.rosetta.core.scoring.CA_rmsd(
                self.native_pose, new_pose)
            if pose_ca_rmsd < self.last_op_min_ca_rmsd:
                self.last_op_min_ca_rmsd = pose_ca_rmsd
                self.last_op_min_ca_rmsd_pose.assign(new_pose)

            current_score = score_function(new_pose)
            self.last_op_energy_evals += 1

            if current_score < local_minima_score:
                local_minima.assign(new_pose)
                local_minima_score = current_score
                failed = 0
            else:
                failed += 1

        # Bookkeeping
        self.total_energy_evals += self.last_op_energy_evals
        if self.last_op_min_ca_rmsd < self.min_ca_rmsd:
            self.min_ca_rmsd = self.last_op_min_ca_rmsd
            self.min_ca_rmsd_pose.assign(self.last_op_min_ca_rmsd_pose)

        return local_minima
コード例 #30
0
# ======== Pose ========================================================================================================
filename = 'SLC38A3_phyre.pdb'
import pymol2

with pymol2.PyMOL() as pymol:
    pymol.cmd.load(filename, 'S38A3')
    pymol.cmd.remove('resi 1-68 or resi 245-282 or resi 494-504')
    pymol.cmd.alter('*', 'chain="A"')
    pymol.cmd.sort()
    pymol.cmd.fetch('6C08')
    pymol.cmd.align('S38A3', '6C08 and chain C')
    pymol.cmd.delete('6C08')
    pdbblock = pymol.cmd.get_pdbstr()

pose = pyrosetta.Pose()
pyrosetta.rosetta.core.import_pose.pose_from_pdbstring(pose, pdbblock)

# ======== scorefxn ====================================================================================================

scorefxnED = pyrosetta.get_fa_scorefxn()  # ref2015 --> franklin2019
ED = pyrosetta.rosetta.core.scoring.electron_density.getDensityMap('6c08.ccp4')  # from PDBe
sdsm = pyrosetta.rosetta.protocols.electron_density.SetupForDensityScoringMover()
sdsm.apply(pose)
elec_dens_fast = pyrosetta.rosetta.core.scoring.ScoreType.elec_dens_fast
scorefxnED.set_weight(elec_dens_fast, 30)

# ======== relax =======================================================================================================

for w in (30, 20, 10):
    scorefxnED.set_weight(elec_dens_fast, w)