示例#1
0
def _minimize_step(sf, pose):
    mmap = MoveMap()
    mmap.set_bb(True)
    mmap.set_chi(False)
    mmap.set_jump(True)

    min_mover = MinMover(mmap, sf, "lbfgs_armijo_nonmonotone", 0.0001, True)
    min_mover.max_iter(1000)
    min_mover.apply(pose)
示例#2
0
def relax(pose):
    sf = create_score_function("ref2015")
    sf.set_weight(rosetta.core.scoring.atom_pair_constraint, 5)
    sf.set_weight(rosetta.core.scoring.dihedral_constraint, 1)
    sf.set_weight(rosetta.core.scoring.angle_constraint, 1)

    mmap = MoveMap()
    mmap.set_bb(True)
    mmap.set_chi(True)
    mmap.set_jump(True)

    relax = rosetta.protocols.relax.FastRelax()
    relax.set_scorefxn(sf)
    relax.max_iter(200)
    relax.dualspace(True)
    relax.set_movemap(mmap)

    switch = SwitchResidueTypeSetMover("fa_standard")
    switch.apply(pose)
    relax.apply(pose)
示例#3
0
  def __init__(self, net, pose, fix=None, glycinate=False, max_iter=100,
               n_moves=1, scorefxn=None, kT=0.1, k=15, dropout=0.5, relax=True):
    super(NetPackMover, self).__init__(net, pose, k=k, dropout=dropout)
    self.relax = relax
    self.n_moves = n_moves
    self.max_iter = max_iter
    self.kT = kT
    self.scorefxn = scorefxn
    self.fix = fix if fix is not None else []
    self.step = 0

    self.fastrelax = ...
    if relax or glycinate:
      fastrelax = FastRelax()
      fastrelax.set_scorefxn(self.scorefxn)
      mm = MoveMap()
      mm.set_bb(False)
      mm.set_chi(True)
      #for fixed in self.fix:
      #  mm.set_chi(fixed, False)
      fastrelax.set_movemap(mm)
      self.fastrelax = fastrelax

    if glycinate:
      self.dropout = 1.0
      mask = torch.tensor([
        1 - int(self.fixed_position(idx))
        for idx in range(len(pose.sequence()))
      ], dtype=torch.bool)
      for idx, residue in enumerate(pose.residues):
        residue_name = self.sample_residue(pose, idx, mask=mask, argmax=True)
        if not self.fixed_position(idx):
          mutate_residue(pose, idx + 1, residue_name, pack_radius=10.0, pack_scorefxn=scorefxn)
        mask[idx] = 0
      self.dropout = dropout
      self.fastrelax.apply(pose)
    self.monte_carlo = MonteCarlo(pose, scorefxn, kT)
    self.glycinate = glycinate
示例#4
0
def movemap(pose, PDB_out=False):
    """
    Demonstrates the syntax necessary for basic usage of the MoveMap object
        performs these changes with a demonstrative backbone minimization
        using  <pose>  and writes structures to PDB files if  <PDB_out>  is True

    """

    #########
    # MoveMap
    # a MoveMap encodes what data is allowed to change in a Pose, referred to as
    #    its degrees of freedom
    # a MoveMap is separate from a Pose and is usually required by a Mover so
    #    that the correct degrees of freedom are manipulated, in this way,
    #    MoveMap and Pose objects often work in parallel
    # several MoveMap's can correspond to the same Pose
    # a MoveMap stores information on a per-residue basis about the
    #    backbone ({phi, psi, omega}) and chi ({chi_i}) torsion angle sets
    #    the MoveMap can only set these sets of torsions to True or False, it
    #    cannot set freedom for the individual angles (such as phi free and psi
    #    fixed)
    # the MoveMap has no upper-limit on its residue information, it defaults to
    #    all residues (up to residue 99999999) backbone and chi False
    # you can view the MoveMap per-residue torsion settings by using the
    #    MoveMap.show( Pose.total_residue() ) method (the input argument is the
    #    highest residue to output, it does not support viewing a range)
    pose_move_map = MoveMap()
    # change all backbone torsion angles
    pose_move_map.set_bb(True)
    # change all chi angle torsion angles (False by default)
    pose_move_map.set_chi(False)
    # change a single backbone torsion angles
    #pose_move_map.set_bb(1, True)    # example syntax
    # change a single residue's chi torsion angles
    #pose_move_map.set_chi(1, True)    # example syntax
    pose_move_map.show(pose.total_residue())

    # perform gradient based minimization on the "median" residues, this
    #    method (MinMover) determines the gradient of an input pose using a
    #    ScoreFunction for evaluation and a MoveMap to define the degrees of
    #    freedom
    # create a standard ScoreFunction
    scorefxn = get_fa_scorefxn(
    )  #  create_score_function_ws_patch('standard', 'score12')
    # redefine the MoveMap to include the median half of the residues
    # turn "off" all backbone torsion angles
    pose_move_map.set_bb(False)  # reset to backbone False
    # turn "on" a range of residue backbone torsion angles
    pose_move_map.set_bb_true_range(int(pose.total_residue() / 4),
                                    int(pose.total_residue() * 3 / 4))
    # create the MinMover
    minmover = protocols.minimization_packing.MinMover()
    minmover.score_function(scorefxn)
    minmover.movemap(pose_move_map)

    # create a copy of the pose
    test_pose = Pose()
    test_pose.assign(pose)
    # apply minimization
    scorefxn(test_pose)  # to prevent verbose output on the next line

    pymover = PyMOLMover()
    #### uncomment the line below and "comment-out" the two lines below to
    ####    export the structures into different PyMOL states of the same object
    #pymover.keep_history = True    # enables viewing across states

    #### comment-out the line below, changing PDBInfo names tells the
    ####    PyMOLMover to produce new objects
    test_pose.pdb_info().name('original')
    pymover.apply(test_pose)
    print('\nPre minimization score:', scorefxn(test_pose))

    minmover.apply(test_pose)
    if PDB_out:
        test_pose.dump_pdb('minimized.pdb')

    print('Post minimization score:', scorefxn(test_pose))
    #### comment-out the line below
    test_pose.pdb_info().name('minimized')
    pymover.apply(test_pose)
示例#5
0
cleaning.cleanATOM(name)
clean_name = pdb_file + ".clean.pdb"
#rna_set = core.chemical.ChemicalManager.get_instance().residue_type_set("coarse_rna").get()
#rna_set = core.chemical.ChemicalManager.get_instance().residue_type_set("fa_standard")

initial_pose = pose_from_pdb(clean_name)
print initial_pose
print toolbox.get_secstruct(initial_pose)
#Set up ScoreFunction
sf = get_fa_scorefxn()

#Set up MoveMap.
mm = MoveMap()
#change these for more or less flexability
mm.set_bb(True)
mm.set_chi(True)

#Pack and minimize initial pose to remove clashes.
pre_pre_packing_score = sf(initial_pose)
print "1"
task = standard_packer_task(initial_pose)
task.restrict_to_repacking()
task.or_include_current(True)
print "2"
pack_rotamers_mover = protocols.simple_moves.RotamerTrialsMover(sf, task)
pack_rotamers_mover.apply(initial_pose)
print "3"

min_mover = protocols.simple_moves.MinMover()
print "4"
示例#6
0
pymol = PyMOLMover()  # If Pymol server is running, centroid stage will display

loop_begin = 145
loop_end = 155
loop_cut = 150
my_loop = protocols.loops.Loop(loop_begin, loop_end, loop_cut)
my_loops = protocols.loops.Loops()
my_loops.add_loop(my_loop)
print(my_loop)

protocols.loops.set_single_loop_fold_tree(p, my_loop)

movemap = MoveMap()
movemap.set_bb_true_range(loop_begin, loop_end)
movemap.set_chi(True)

print(p.fold_tree())

print("setting up movers")
# use the KinematicMover explicitly in centroid stage
kic_mover = KinematicMover()

#centroid/fullatom conversion movers
to_centroid = protocols.simple_moves.SwitchResidueTypeSetMover('centroid')
to_fullatom = protocols.simple_moves.SwitchResidueTypeSetMover('fa_standard')
recover_sidechains = protocols.simple_moves.ReturnSidechainMover(starting_p)

#set up sidechain packer movers
task_pack = core.pack.task.TaskFactory.create_packer_task(starting_p)
task_pack.restrict_to_repacking()
def sample_single_loop_modeling(pdb_filename,
                                loop_begin,
                                loop_end,
                                loop_cutpoint,
                                frag_filename,
                                frag_length,
                                outer_cycles_low=2,
                                inner_cycles_low=5,
                                init_temp_low=2.0,
                                final_temp_low=0.8,
                                outer_cycles_high=5,
                                inner_cycles_high=10,
                                init_temp_high=2.2,
                                final_temp_high=0.6,
                                jobs=1,
                                job_output='loop_output'):
    """
    Performs simple single loop construction on the input  <pdb_filename>
        with loop from  <loop_begin>  to  <loop_end>  with a
        cutpoint at  <loop_cutpoint>  using fragments of length  <frag_length>
        in the file  <frag_filename>.  <jobs>  trajectories are performed,
        each using a low resolution (centroid) simulated annealing with
        <outer_cycles>  rounds and  <inner_cycles>  steps per round decrementing
        "temperature" from  <init_temp>  to  <final_temp>  geometrically.
        Output structures are named  <job_output>_(job#).pdb.

    """
    # 1. create a pose from the desired PDB file
    p = Pose()
    pose_from_file(p, pdb_filename)

    # 2. create a reference copy of the pose in fullatom
    starting_p = Pose()
    starting_p.assign(p)

    #### if you are constructing multiple loops simultaneously, changes will
    ####    occur in most of the steps below

    # 3. create the Loop object
    #    (note: Loop objects merely specify residues, they contain no
    #         conformation data)
    my_loop = protocols.loops.Loop(loop_begin, loop_end, loop_cutpoint)
    #### if using multiple loops, add additional Loop objects
    # 4. use the Loop to set the pose FoldTree
    protocols.loops.set_single_loop_fold_tree(p, my_loop)
    #### alternate FoldTree setup, if you uncomment the lines below,
    ####    comment-out the set_single_loop_foldtree line above (line 189)
    #### -create an empty FoldTree
    #ft = FoldTree()
    #### -make it a single edge the length of pose
    #ft.simple_tree(p.total_residue())
    #### -insert a jump corresponding to the single loop region
    #ft.add_jump(loop_begin - 2, loop_end + 2, loop_cutpoint)
    #### -give the pose this FoldTree (set it to this object), this will
    ####     erase any previous FoldTree held by the pose
    #p.fold_tree(ft)
    #### there is also a fold_tree_from_loops method in exposed which sets up
    ####    a FoldTree but it is different from set_single_loop_foldtree in
    ####    that is creates jumps +/- 1 residue from their corresponding loop
    ####    endpoints and requires a third argument, the FoldTree to setup

    # 5. sets the cut-point residues as cut-point variants
    protocols.loops.add_single_cutpoint_variant(p, my_loop)

    # 6. create the MoveMap, allow the loop region backbone and
    #    all chi torsions to be free
    movemap = MoveMap()
    movemap.set_bb_true_range(loop_begin, loop_end)
    movemap.set_chi(True)  # sets all chi torsions free

    # 7. setup the fragment Mover
    # this "try--except" is used to catch improper fragment files
    try:
        fragset = core.fragment.ConstantLengthFragSet(frag_length,
                                                      frag_filename)
        #### the ConstantLengthFragSet is overloaded, this same
        ####    ConstantLengthFragSet can be obtained with different syntax
        # to obtain custom fragments, see Generating Fragment Files below
    except:
        raise IOError('Make sure frag_length matches the fragments in\n\
            frag_file and that frag_file is valid')
    fragment_mover = protocols.simple_moves.ClassicFragmentMover(
        fragset, movemap)

    # 8. create a Mover for loop modeling using CCD (low resolution)
    ccd_closure = protocols.loops.loop_closure.ccd.CCDLoopClosureMover(
        my_loop, movemap)

    # 9. create ScoreFunctions
    # for centroid, use the default centroid ScoreFunction with chainbreak on
    scorefxn_low = create_score_function('cen_std')
    # the chainbreak ScoreType exists to penalize broken bonds
    # try creating a broken pose in the interpreter and use a ScoreFunction
    #    with a chainbreak score to investigate its impact, the score is 0.0
    #    except when a bond is broken
    # this penalizes failures caused by CCD failing to close the loop
    scorefxn_low.set_weight(core.scoring.chainbreak, 1)
    # for fullatom, used for packing and scoring final output
    scorefxn_high = get_fa_scorefxn(
    )  #  create_score_function_ws_patch('standard', 'score12')

    # 10. setup sidechain packing Mover
    task_pack = core.pack.task.TaskFactory.create_packer_task(starting_p)
    task_pack.restrict_to_repacking()  # prevents design, packing only
    task_pack.or_include_current(True)  # considers original sidechains
    pack = protocols.minimization_packing.PackRotamersMover(
        scorefxn_high, task_pack)

    # 11. setup the high resolution refinement
    # by creating a Loops object,
    #    (note: Loops is basically a list of Loop objects),
    sample_loops = protocols.loops.Loops()
    # giving it the loop to remodel,
    sample_loops.add_loop(my_loop)
    # and creating a fullatom CCD Mover (high resolution)
    # this Mover is somewhat abnormal since it handles everything itself, it:
    #    -creates its own MoveMap for the loop regions
    #    -creates its own ScoreFunction (default to get_fa_scorefxn())
    #    -creates its own FoldTree for the pose based on the loops
    #    -creates its own MonteCarlo object for monitoring the pose
    #    -performs "simulated annealing" with 3 outer cycles and 90 inner
    #        cycles, very similar to the protocol outlined ere
    #    -creates its own backbone Movers (SmallMover, ShearMover)
    #    -creates its own PackRotamersMover, it does NOT restrict repacking
    #        to the loop regions and can alter all sidechain conformations
    loop_refine = LoopMover_Refine_CCD(sample_loops)
    # some of these parameters or objects can be set but the protocol
    #    executed by this Mover is effectively untouchable
    #loop_refine.set_score_function(scorefxn_high)    # in beta v2 and above
    loop_refine.temp_initial(init_temp_high)
    loop_refine.temp_final(init_temp_high)
    loop_refine.outer_cycles(outer_cycles_high)
    loop_refine.max_inner_cycles(inner_cycles_high)

    # 12. create centroid <--> fullatom conversion Movers
    to_centroid = SwitchResidueTypeSetMover('centroid')
    to_fullatom = SwitchResidueTypeSetMover('fa_standard')
    # and a Mover to recover sidechain conformations
    #    when a protocol samples backbone torsion space in centroid,
    #    the sidechain conformations are neglected, when it is transferred
    #    to fullatom, we typically set the sidechain conformations to their
    #    "original" values and perform sidechain packing,
    #    a ReturnSidechainMover saves a pose's sidechains (in this case
    #    staring_pose) and when applied, inserts these conformations
    #    into the input pose
    recover_sidechains = protocols.simple_moves.ReturnSidechainMover(
        starting_p)

    # 13. create a reference copy of the pose in centroid
    # the first stage of each trajectory is in centroid
    #    so a centroid reference is needed and the pose must start in centroid
    to_centroid.apply(p)
    starting_p_centroid = Pose()
    starting_p_centroid.assign(p)

    # 14. create the geometric "temperature" increment for simulated annealing
    gamma = pow((final_temp_low / init_temp_low),
                (1.0 / (outer_cycles_low * inner_cycles_low)))

    # 15. create a PyMOLMover for exporting structures to PyMOL
    pymov = PyMOLMover()
    # uncomment the line below to load structures into successive states
    #pymov.keep_history(True)
    scorefxn_high(starting_p)  # for exporting the scores
    pymov.apply(starting_p)
    pymov.send_energy(starting_p)

    # 16. create a (Py)JobDistributor
    # a PyJobDistributor uses the job_output argument to name all output files
    #    and performs the specified number (int) of jobs
    # a ScoreFunction is required since the PyJobDistributor output .fasc file
    #    contains scoring information about each output PDB
    jd = PyJobDistributor(job_output, jobs, scorefxn_high)
    jd.native_pose = starting_p

    # 17. perform the loop modeling protocol
    counter = 0  # for exporting to PyMOL
    while not jd.job_complete:
        # a. set necessary variables for the new trajectory
        # -reload the starting pose (centroid)
        p.assign(starting_p_centroid)
        # -change the pose's PDBInfo.name, for exporting to PyMOL
        counter += 1
        p.pdb_info().name(job_output + '_' + str(counter) + '_cen')
        # -reset the starting "temperature" (to init_temp)
        kT = init_temp_low
        # -create a MonteCarlo object for this trajectory
        #    a MonteCarlo object assesses pass/fail by the Metropolis Criteria
        #    and also records information on the lowest scoring pose
        mc = MonteCarlo(p, scorefxn_low, kT)

        # b. "randomize" the loop
        #### this section may change if you intend to use multiple loops or
        ####    alter the sampling method to "randomize" the loop
        # -by breaking it open,
        for i in range(loop_begin, loop_end + 1):
            p.set_phi(i, -180)
            p.set_psi(i, 180)
        pymov.apply(p)
        # -and then inserting fragments
        #    the number of insertions performed is somewhat arbitrary
        for i in range(loop_begin, loop_end + 1):
            fragment_mover.apply(p)
        pymov.apply(p)
        ####

        # low resolution loop modeling:
        # c. simulated annealing incrementing kT geometrically
        #    from init_temp to final_temp
        #### this section may change if you intend to use multiple loops or
        ####    alter the sampling method for low resolution modeling
        for i in range(1, outer_cycles_low + 1):
            # -start with the lowest scoring pose
            mc.recover_low(p)  # loads mc's lowest scoring pose into p
            # -take several steps of in the simulated annealing by
            for j in range(1, inner_cycles_low + 1):
                # >increasing the "temperature"
                kT = kT * gamma
                mc.set_temperature(kT)
                # >inserting a fragment,
                fragment_mover.apply(p)
                pymov.apply(p)
                # >performing CCD,
                ccd_closure.apply(p)
                pymov.apply(p)
                # >and assessing the Metropolis Criteria
                mc.boltzmann(p)
        ####

        # the LoopMover_Refine_CCD makes A LOT of moves, DO NOT expect to
        #    see useful results if you use the PyMOLMover keep_history option, the large
        #    number of intermediates will slow processing to a halt

        # d. convert the best structure (lowest scoring) into fullatom by:
        # -recovering the best (centroid) structure (lowest scoring),
        mc.recover_low(p)  # loads mc's lowest scoring pose into p
        # -switching the ResidueTypeSet to fullatom (from centroid),
        to_fullatom.apply(p)
        # -recovering the original sidechain conformations,
        recover_sidechains.apply(p)
        # -and packing the result (since the backbone conformation has changed)
        pack.apply(p)
        pymov.apply(p)
        p.pdb_info().name(job_output + '_' + str(counter) + '_fa')

        # high-resolution refinement:
        #### this section may change if you intend to use multiple loops or
        ####    alter the sampling method for high resolution refinement
        # e. apply the LoopMover_Refine_CCD
        loop_refine.apply(p)

        # f. output the decoy (pose result from this trajectory)
        #    include the loop RMSD (Lrsmd)
        # -output a PDB file using the PyJobDistributor
        lrms = protocols.loops.loop_rmsd(p, starting_p, sample_loops, True)
        jd.additional_decoy_info = ' Lrmsd: ' + str(lrms)
        jd.output_decoy(p)
        # -export the structure to PyMOL
        pymov.apply(p)
        pymov.send_energy(p)
示例#8
0
def mutate(pdb_name, n_muts=100):
    OUT = open(mydir + '/data/deltas.txt', 'w')
    #takes name of pdb file without the extention
    init(extra_options='-mute basic -mute core')
    # Constants
    PACK_RADIUS = 10.0
    #Amino acids, notice there is no C
    AAs = ("A", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q",
           "R", "S", "T", "V", "W", "Y")
    #Number of mutations to accept
    max_accept_mut = 600
    #Population size
    N = 100
    #Beta (temp term)
    beta = 1
    pdb = pdb_name + ".pdb"
    cleanATOM(pdb)
    pdb_clean_name = pdb_name + '.clean.pdb'
    initial_pose = pose_from_pdb(pdb_clean_name)

    #Set up ScoreFunction
    sf = get_fa_scorefxn()

    #Set up MoveMap.
    mm = MoveMap()
    #change these for more or less flexability
    mm.set_bb(True)
    mm.set_chi(True)

    #Pack and minimize initial pose to remove clashes.
    pre_pre_packing_score = sf(initial_pose)

    task = standard_packer_task(initial_pose)
    task.restrict_to_repacking()
    task.or_include_current(True)
    pack_rotamers_mover = RotamerTrialsMover(sf, task)
    pack_rotamers_mover.apply(initial_pose)

    min_mover = MinMover()
    min_mover.movemap(mm)
    min_mover.score_function(sf)
    min_mover.min_type('dfpmin_armijo_nonmonotone')
    min_mover.apply(initial_pose)

    post_pre_packing_score = sf(initial_pose)

    #Set threshold for selection
    threshold = pre_pre_packing_score / 2

    #number of residues to select from
    n_res = initial_pose.total_residue()

    max_accept_mut = 1500
    #start sim
    i = 0
    gen = 0
    columns = ['Number', 'Selection', 'P_fix', 'P_fix_MH']
    print >> OUT, '\t'.join(columns)
    while i < max_accept_mut:
        #update the number of generations that have pased
        gen += 1

        #pick a place to mutate
        mut_location = random.randint(1, n_res)

        #get the amino acid at that position
        res = initial_pose.residue(mut_location)
        #don't mess with C, just choose again
        if res.name1() == 'C':
            mut_location = random.randint(1, n_res)
            #get the amino acid at that position
            res = initial_pose.residue(mut_location)

        #choose the amino acid to mutate to
        new_mut_key = random.randint(0, len(AAs) - 1)

        proposed_res = AAs[new_mut_key]

        #don't bother mutating to the same amino acid it just takes more time
        if proposed_res == res.name1():
            new_mut_key = random.randint(0, len(AAs) - 1)
            proposed_res = AAs[new_mut_key]

        #make the mutation
        mutant_pose = mutate_residue(initial_pose, mut_location, proposed_res,
                                     PACK_RADIUS, sf)
        #score mutant
        variant_score = sf(mutant_pose)

        probability = calc_prob_fix(variant_score, post_pre_packing_score, N,
                                    beta, threshold)
        probability_mh = calc_prob_mh(variant_score, post_pre_packing_score, N,
                                      beta, threshold)
        f_i = calc_x_fix(post_pre_packing_score, beta, threshold)
        f_j = calc_x_fix(variant_score, beta, threshold)
        s = math.log(f_j) - math.log(f_i)
        #test to see if mutation is accepted
        if np.isnan(probability) == True:
            continue
        rndm = random.random()
        if (i < 100):
            if (rndm < probability):
                initial_pose = mutant_pose
                post_pre_packing_score = variant_score
            else:
                continue
        # Assuming 100 burn in phase, take this if out if you want to store everything
        else:
            data = [str(i), str(s), str(probability), str(probability_mh)]
            print >> OUT, '\t'.join(data)
            #save name and energy change
            #data.append(variant_name + "," + str(variant_score) + "," + str(variant_score - post_pre_packing_score) + "," + str(probability) + "," + str(gen) + "\n")
            #pdb_name=str(i)+".pdb"
            #mutant_pose.dump_pdb(pdb_name)

        print i, s, probability, rndm
        #update number of accepts
        i += 1

    OUT.close()