Exemple #1
0
def submain(args_phi_psi=False, args_seq=False, args_name='render'):

    with open(args_phi_psi, 'r') as phi_psi:
        args_phi_psi = phi_psi.readlines()
    torsion_space_iterable = args_phi_psi

    PhiPsi = []

    if args_seq:
        if os.path.isfile(args_seq):
            with open(args_seq, 'r') as seq:
                args_seq = seq.readlines()
                args_seq = [line for line in args_seq if len(line)]
                if len(args_seq) == 1: args_seq = args_seq[0].strip()
        Seq = list(args_seq)
    else:
        Seq = []

    try:
        assert len(torsion_space_iterable) == len(Seq)
    except:
        print('Sequence and torison iteratable must be same length\n', Seq,
              len(Seq), torsion_space_iterable, len(torsion_space_iterable))
        sys.exit()

    # 1st loop through backbone
    for i, element in enumerate(torsion_space_iterable):
        element = element.strip()

        angles = tuple(float(a) for a in element.split())
        if len(angles) == 2:
            phi, psi = angles
            omega = 180
        else:
            assert len(angles) == 3
            phi, psi, omega = angles

        PhiPsi.append((phi, psi, omega))
        if not args_seq:
            Seq.append(AminoAcid)

    assert len(PhiPsi) == len(Seq)

    try:
        pyrosetta
    except NameError:
        import pyrosetta
        pyrosetta.init()

    render_pose = pyrosetta.pose_from_sequence(''.join(Seq))

    for i, torsion_angles in enumerate(PhiPsi):
        phi, psi, omega = torsion_angles
        p = i + 1
        render_pose.set_phi(p, phi)
        render_pose.set_psi(p, psi)
        render_pose.set_omega(p, omega)

    render_pose.dump_pdb('%s.pdb' % args_name)
def run_pyrosetta_with_flags(flags_file_path, mute=False):
    if not flags_file_path:
        pyrosetta.init("-mute all " if mute else "", silent=mute)
        return
    flags = read_flag_file(flags_file_path)
    flags_str = " ".join(flags.replace("\n", " ").split())
    pyrosetta.init(f"-mute all {flags_str}" if mute else flags_str,
                   silent=mute)
Exemple #3
0
def preprocess(path):
    import pyrosetta, logging
    pyrosetta.init(
        extra_options=
        '-no_optH false -mute all -ignore_unrecognized_res true -load_PDB_components false'
    )
    from fragmenstein.mpro import MProVictor
    MProVictor.enable_stdout(logging.INFO)
    MProVictor.work_path = path
Exemple #4
0
    def update_mover(self):
        self.mover = rFastDesign(self.sfxn, self.rounds)
        self.mover.set_up_default_task_factory()
        init(' '.join(self.init_args))
        if self.edited_movemap:
            self.mover.set_movemap(self.movemap)

        if hasattr(self, '_task_factory'):
            self.mover.set_task_factory(self.task_factory)
Exemple #5
0
def main():
    print(len(sys.argv))
    pyrosetta.init()
    report_memuse("init")
    keep = list()
    for posefile in sys.argv[1:]:
        with open(posefile, "rb") as f:
            pose = pickle.load(f)
            # keep.append(pose)
            report_memuse("loaded pose")
Exemple #6
0
def mpi_init(*args, **kargs):

    comm = MPI.COMM_WORLD

    rank = comm.Get_rank()
    size = comm.Get_size()

    kargs['extra_options'] = kargs.get('extra_options', '') + ' -seed_offset {}'.format(rank*10000)

    pyrosetta.init(*args, **kargs)
Exemple #7
0
def init_check(options='-beta_nov15', fail_if_options_dont_match=True):
    global pyrosetta_init_options
    if pyrosetta_init_options is None:
        pyrosetta.init(options=options)
        pyrosetta_init_options = options
    elif options != pyrosetta_init_options:
        if fail_if_options_dont_match:
            raise ReInitError(
                'attempt to init rosetta with different options: previous: {}, thiscall: {}'
                .format(pyrosetta_init_options, options))
Exemple #8
0
def main():
    pyrosetta.init('-beta -include_patches patches/VirtualBB.txt')
    chem_manager = rosetta.core.chemical.ChemicalManager
    rts = chem_manager.get_instance().residue_type_set("fa_standard")
    ggg = rosetta.core.pose.Pose()
    core.pose.make_pose_from_sequence(ggg, 'AAA', rts)
    virt_bb = rosetta.core.chemical.VIRTUAL_BB
    core.pose.remove_lower_terminus_type_from_pose_residue(ggg, 1)
    core.pose.remove_upper_terminus_type_from_pose_residue(ggg, 3)
    core.pose.add_variant_type_to_pose_residue(ggg, virt_bb, 1)
def boot_pyrosetta(param_string=None):
    """Boot PyRosetta"""
    if param_string is None:
        param_string = ""

    booted = os.environ.get(PYROSETTA_BOOTED, "no") == "yes"
    if not booted:
        pyrosetta.init(param_string)
        os.environ['PYROSETTA_BOOTED'] = "yes"

    return True
Exemple #10
0
def init_check(options=None, strict=True):
    if options is None:
        strict = False
        options = '-corrections:beta_nov16 -mute all'
    global pyrosetta_init_options
    if pyrosetta_init_options is None:
        pyrosetta.init(options=options)
        pyrosetta_init_options = options
    elif options != pyrosetta_init_options:
        if strict:
            raise ReInitError(
                'attempt to init rosetta with different options: previous: {}, thiscall: {}'
                .format(pyrosetta_init_options, options))
Exemple #11
0
    def __init__(self, pdb_file, rf, tw):
        import pyrosetta
        from pyrosetta import teaching
        import pyrosetta.rosetta.numeric
        self.rose = pyrosetta.rosetta.numeric

        self.rf = rf
        pyrosetta.init()
        with open(pdb_file, 'r') as f:
            self.prior_detail = "".join(f.readlines()[:-1]) # strip off end.
        self.ligand_maker = pyrosetta.pose_from_pdb
        self.score  = teaching.get_fa_scorefxn()
        self.reset(tw)
Exemple #12
0
def worms_main(argv):

    pyrosetta.init("-mute all -beta -preserve_crystinfo --prevent_repacking")
    blosc.set_releasegil(True)

    criteria_list, kw = build_worms_setup_from_cli_args(argv)

    try:
        worms_main2(criteria_list, kw)
    except Exception as e:
        bbdb = kw["db"][0]
        bbdb.clear()
        raise e
Exemple #13
0
def main():
    args = docopt.docopt(__doc__)
    folder = args['<folder>']
    init()
    target = pose_from_file(args['<input>'])
    workspace = pipeline.workspace_from_dir(folder)
    loop = workspace.largest_loop

    #mobile = pose_from_file('/Users/benjaminrjagger/UCSF/cas_des/CPP_sims/4un3_1051_penetratin/input.pdb.gz')

    # ins_len = chain_end_res(mobile, 1) - chain_end_res(target, 1)
    # des_res = list(range(1, int(loop.start)-1)) + list(range(int(loop.end)+1, chain_end_res(mobile, 1)))
    # wt_res = list(range(1,int(loop.start) -1)) + list(range(int(loop.end)+1 - ins_len, chain_end_res(target, 1)))

    # res_map = map_unsigned_long_unsigned_long()
    # for i in range(len(des_res)):
    #     res_map[des_res[i]] = wt_res[i]

    # rmsd = CA_rmsd(mobile, target, res_map)

    for root, dirs, files in os.walk(workspace.output_dir):
        for name in files:
            if name.endswith('.pdb.gz') or name.endswith('.pdb'):
                pdbpath = os.path.join(root, name)
                mobile = pose_from_file(pdbpath)
                ins_len = chain_end_res(mobile, 1) - chain_end_res(target, 1)
                des_res = list(range(
                    1,
                    int(loop.start) - 1)) + list(
                        range(int(loop.end) + 1, chain_end_res(mobile, 1)))
                wt_res = list(range(1,
                                    int(loop.start) - 1)) + list(
                                        range(
                                            int(loop.end) + 1 - ins_len,
                                            chain_end_res(target, 1)))

                res_map = map_unsigned_long_unsigned_long()
                for i in range(len(des_res)):
                    res_map[des_res[i]] = wt_res[i]

                rmsd = CA_rmsd(mobile, target, res_map)
                metric_name = 'EXTRA_METRIC_CA_RMSD_NO_LOOP [[-]]'

                if name.endswith('.pdb.gz'):
                    add_lines_to_gzip(pdbpath, [metric_name + ' ' + str(rmsd)])

                if name.endswith('.pdb'):
                    add_lines_reg(pdbpath, [metric_name + ' ' + str(rmsd)])
                #rmsd = all_atom_rmsd(mobile, target)
                print(rmsd)
Exemple #14
0
def main(nseg, workers=0):
    pyrosetta.init("-corrections:beta_nov16 -mute all")
    helix = Spliceable(poselib.curved_helix, sites=[(1, "N"), ("-4:", "C")])
    dimer = Spliceable(poselib.c2, sites=[("1,:1", "N"), ("2,-1:", "C")])
    segments = ([Segment([helix], exit="C")] +
                [Segment([dimer], entry="N", exit="C")] +
                [Segment([helix], entry="N", exit="C")] * (nseg - 2) +
                [Segment([helix], entry="N")])
    t = perf_counter()

    worms = grow(
        segments,
        Cyclic("C13", lever=40),
        thresh=1.0,
        max_workers=workers,
        executor=ProcessPoolExecutor,
        # executor=dask.distributed.Client,
        max_results=10000,
        max_samples=10000000,
    )
    print("number of results:", len(worms))
    t = perf_counter() - t
    count = np.prod([len(s) for s in segments])
    s = worms.scores

    try:
        ptile = np.percentile(s, range(0, 100, 20))
    except:
        ptile = []
    print("quantile", ptile)
    print("best10  ", s[:10])
    print(
        "nseg %2i" % nseg,
        "best %7.3f" % (s[0] if len(s) else 999),
        "tgrow %7.2f" % t,
        "rate %7.3fM/s" % (count / t / 1000000),
        "npass %8i" % len(s),
    )
    print("going through poses:")
    sys.stdout.flush()

    for i in range(min(10, len(worms))):
        fname = "worm_nseg%i_%i.pdb" % (nseg, i)
        pose, score0 = worms.sympose(i, fullatom=True, score=True)
        print("worm", i, worms.scores[i], score0, worms.indices[i])
        sys.stdout.flush()
        if score0 < 250:
            print("    dumping to", fname)
            pose.dump_pdb(fname)
Exemple #15
0
def design(input_dir,
           data_path,
           selected_designs_file,
           num_jobs,
           job_id,
           num_seq_per_model=1,
           do_ex_rot_run=True):
    pyrosetta.init(options='-mute all')

    # Get all the tasks

    df_selected = pd.read_csv(selected_designs_file, sep='\t')
    tasks = []

    for i, row in df_selected.iterrows():
        for j in range(num_seq_per_model):
            tasks.append(row['design_id'])

    # Make designs

    for i, t in enumerate(tasks):
        if i % num_jobs == job_id:
            output_path = os.path.join(data_path, str(i))
            os.makedirs(output_path, exist_ok=True)

            input_pdb = os.path.join(input_dir, str(t), 'design.pdb.gz')

            with open(os.path.join(input_dir, str(t), 'design_info.json'),
                      'r') as f:
                input_design_info = json.load(f)

            if 'sequence_symmetry_map' in input_design_info.keys():
                ssm_serial = input_design_info['sequence_symmetry_map']
                sequence_symmetry_map = {}

                for x in ssm_serial:
                    sequence_symmetry_map[(x[0], x[1])] = (x[2], x[3])
            else:
                sequence_symmetry_map = None

            LPSD.sequence_design.make_one_design(
                output_path,
                input_pdb,
                input_design_info['bb_remodeled_residues'],
                designable_residues=input_design_info['designable_residues'],
                repackable_residues=input_design_info['repackable_residues'],
                do_ex_rot_run=do_ex_rot_run,
                sequence_symmetry_map=sequence_symmetry_map)
Exemple #16
0
def main():
    args = docopt.docopt(__doc__)
    print(args)
    df = pd.DataFrame()
    init('-ignore_unrecognized_res')

    if 'SGE_TASK_ID' in os.environ:
        idx = int(os.environ['SGE_TASK_ID']) - 1
    else:
        idx = int(args['--task']) - 1

    ntasks = int(args['--ntasks'])
    start = idx * ntasks
    stop = idx * ntasks + ntasks - 1
    print('START: {}'.format(start))
    print('STOP: {}'.format(stop))
    folder = args['<pdbfolder>']
    workspace = ws.workspace_from_dir(args['<workspace>'])

    exts = ('.pdb', '.pdb.gz')
    if args['--recursive']:
        files = [
            str(p) for p in Path(folder).rglob('*') if p.name.endswith(exts)
        ]
    else:
        files = [
            str(p) for p in Path(folder).iterdir() if p.name.endswith(exts)
        ]

    print(files)

    for f in files:
        pose = pose_from_file(f)
        scanner = PoseScanner(pose)
        posename = os.path.basename(f).split('.')[0]
        helices = pd.DataFrame(
            scanner.scan_pose_helices(name=posename,
                                      split_chains=args['--split-chains']))
        df = pd.concat([df, helices], ignore_index=True)

    today = date.today()
    outdir = os.path.join(workspace.project_params_dir, 'database')
    os.makedirs(outdir, exist_ok=True)
    out = os.path.join(
        outdir, 'helixdf_custom_{0}.'.format(today.strftime("%m-%d-%Y")))
    df.to_pickle(out + 'pkl')
    # Comment this out later - no need for csv in final
    df.to_csv(out + 'csv')
Exemple #17
0
def main(fasta_path, feature_path, input_dir, output_dir, n_workers):
    pyrosetta.init(
        "-hb_cen_soft -relax:default_repeats 5 -default_max_cycles 200 -out:level 100"
    )
    os.makedirs(output_dir, exist_ok=True)
    seq = open(fasta_path).readlines()[1].strip()
    with Pool(n_workers) as p:
        args = []
        for path in os.listdir(input_dir):
            args.append((
                seq,
                feature_path,
                os.path.join(input_dir, path),
                os.path.join(output_dir, path),
            ))
        p.starmap(relex_from_pdb, args)
Exemple #18
0
def main():
    init()
    pose = pose_from_file('test_files/6r9d.cif')
    # pose = pose_from_file('test_cas9.pdb.gz')
    import time
    start = time.time()
    scanner = PoseScanner(pose)
    helices = scanner.scan_pose_helices(test=False)
    print('CALC TIME = {}'.format(
        time.time() - start
        ))
    helices = pd.DataFrame(helices)
    print(helices)
    print(helices['name'])
    helices.to_pickle('out.pkl')
    helices.to_csv('out.csv')
def runAnnealingProcess(rep, kts, sigma, epsilon):
    import cg_pyrosetta
    import pyrosetta

    pyrosetta.init()
    
    folding_object = cg_pyrosetta.CG_folding.CGFoldingAlgorithm('X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]X[CG11]')
    # folding_object.scorefxn.set_weight(pyrosetta.rosetta.core.scoring.mm_twist, 1)
    # folding_object.scorefxn.set_weight(pyrosetta.rosetta.core.scoring.mm_bend, 1)
    folding_object.add_folding_move('default', folding_object.pymol)

    assert(folding_object.pose.residue(2).atom_type(2).lj_radius() == sigma)  # Throws error if SC isn't actually scanning
    assert(folding_object.pose.residue(2).atom_type(2).lj_wdepth() == epsilon) # Should include more of these in scripts to make sure parameter scans are actually happening

    folding_object.run_anneal_fold('default', 1, kts)
    folding_object.mc.lowest_score_pose().dump_pdb(os.path.join('outputs', 'sigma_'+str(round(sigma, 3)), 'epsilon_'+str(round(epsilon,3)), 'CG11_rep_'+str(rep)+'.pdb'))
Exemple #20
0
def init_rosetta(test_cycles=False, constant_seed=False):
    flags = [
            '-relax:dna_move on',
            '-relax:coord_cst_stdev 0.5',  # default: 0.5
            '-relax:constrain_relax_to_start_coords on',
            '-relax:ramp_constraints off',
            '-run:test_cycles', 'on' if test_cycles else 'off',
            '-dna:specificity:exclude_dna_dna off',
            '-out:levels core.pack.rotamer_set.RotamerSet_.extra_rotamers:500',
    ]

    if constant_seed:
        flags += [
            '-constant_seed',
        ]

    pyrosetta.init(' '.join(flags), set_logging_handler='logging')
Exemple #21
0
def main():
    pyrosetta.init()
    print "foo"
    dirname = os.path.dirname(__file__)
    testfile = dirname + '/1pgx.pdb'
    pose = rosetta.core.import_pose.pose_from_file(testfile)
    print pose
    x = Xform(Mat(), Vec(10, 0, 0))
    for ir in range(1, pose.size() + 1):
        for ia in range(1, pose.residue(ir).natoms() + 1):
            aid = rosetta.core.id.AtomID(ia, ir)
            oldxyz = Vec(pose.xyz(aid))
            # manipulate the atom position here!!!!
            newxyz = x * oldxyz
            pose.set_xyz(aid, newxyz.to_rosetta())
    print 'dumping' + dirname + '/test_out.pdb'
    pose.dump_pdb(dirname + '/test_out.pdb')
Exemple #22
0
def main(nseg, workers=0):
    pyrosetta.init('-corrections:beta_nov16 -mute all')
    helix = Spliceable(poselib.curved_helix, sites=[(1, 'N'), ('-4:', 'C')])
    dimer = Spliceable(poselib.c2, sites=[('1,:1', 'N'), ('2,-1:', 'C')])
    segments = ([
        Segment([helix], exit='C'),
    ] + [Segment([dimer], entry='N', exit='C')] +
                [Segment([helix], entry='N', exit='C')] *
                (nseg - 2) + [Segment([helix], entry='N')])
    t = perf_counter()

    worms = grow(
        segments,
        Cyclic('C13', lever=40),
        thresh=1.0,
        max_workers=workers,
        executor=ProcessPoolExecutor,
        # executor=dask.distributed.Client,
        max_results=10000,
        max_samples=10000000)
    print('number of results:', len(worms))
    t = perf_counter() - t
    count = np.prod([len(s) for s in segments])
    s = worms.scores

    try:
        ptile = np.percentile(s, range(0, 100, 20))
    except:
        ptile = []
    print('quantile', ptile)
    print('best10  ', s[:10])
    print('nseg %2i' % nseg, 'best %7.3f' % (s[0] if len(s) else 999),
          'tgrow %7.2f' % t, 'rate %7.3fM/s' % (count / t / 1000000),
          'npass %8i' % len(s))
    print('going through poses:')
    sys.stdout.flush()

    for i in range(min(10, len(worms))):
        fname = 'worm_nseg%i_%i.pdb' % (nseg, i)
        pose, score0 = worms.sympose(i, fullatom=True, score=True)
        print('worm', i, worms.scores[i], score0, worms.indices[i])
        sys.stdout.flush()
        if score0 < 250:
            print('    dumping to', fname)
            pose.dump_pdb(fname)
Exemple #23
0
def main():
    # Needed for PyRosetta to work
    pyrosetta.init()

    pdb_files = list(filter(lambda f: '.pdb' in f, os.listdir(PDB_DIR)))
    total = len(pdb_files)
    batch = math.ceil(total / NUM_THREADS)

    thread_list = []
    for i in range(NUM_THREADS):
        pdb_file_batch = pdb_files[i * batch:(i + 1) * batch]
        thread_list.append(PDB2DataThread(pdb_file_batch))

    for t in thread_list:
        t.start()

    for t in thread_list:
        t.join()
def get_metrics(data_path, input_path, num_jobs, job_id):
    '''Get rosetta metrics for all structures in the
    input path.
    '''
    pyrosetta.init('-ignore_unrecognized_res true')

    for i, f in enumerate(os.listdir(input_path)):
        if i % num_jobs != job_id:
            continue

        if f.endswith('.pdb') or f.endswith('.pdb.gz'):
            pose = rosetta.core.pose.Pose()
            rosetta.core.import_pose.pose_from_file(pose, os.path.join(input_path, f))
            print("Here")
            d_of_data = get_metrics_for_one_pose(pose, f.split('.')[0])
            
            for key in d_of_data.keys():
                append_to_csv(d_of_data[key], os.path.join(data_path, '{0}.csv'.format(key)))
def main():
    pyrosetta.init()

    for id, c in enumerate(RESIDUE_LETTERS):
        atom_count = None
        chi_count = None
        try:
            pose = pyrosetta.pose_from_sequence(c, 'fa_standard')
            residue = pose.residue(1)
            atom_count = pose.residue(1).natoms()
            chi_count = len(residue.chi())
        except Exception as e:
            print('Error processing {}: {}'.format(c, e))

        ATOM_COUNT[id] = atom_count
        CHI_COUNT[id] = chi_count

    print('Max atom count: {}'.format(max(ATOM_COUNT)))
    print('Max chi angles count: {}'.format(max(CHI_COUNT)))
Exemple #26
0
def buildProtein(sequence, outdir, start_idx=1):
    from htmd.builder.preparation import proteinPrepare
    from htmd.ui import Molecule, amber
    import sys
    sys.path.append(
        "/home/pablo/PyRosetta4.Release.python36.linux.release-197")
    import pyrosetta
    pyrosetta.init()
    pose = pyrosetta.pose_from_sequence(sequence, 'fa_standard')
    pose.dump_pdb('/tmp/test.pdb')
    mol = Molecule('/tmp/test.pdb')
    mol = proteinPrepare(mol)
    mol.resid = mol.resid + start_idx
    mol.set('segid', 'P1')
    mol.filter('backbone')
    _ = amber.build(mol, outdir=outdir, ionize=False
                    # , caps=None
                    )
    return outdir + '/structure.prmtop'
def select_linkers(data_path,
                   input_pdb,
                   input_insertion_points_file,
                   insertion_ids_for_selection=None):
    pyrosetta.init()

    # Load insertion points

    with open(input_insertion_points_file, 'r') as f:
        insertion_points = json.load(f)

    if insertion_ids_for_selection is None:
        insertion_ids_for_selection = range(len(insertion_points))

    for insertion_id in insertion_ids_for_selection:
        start_ss = insertion_points[insertion_id]['start_ss']
        stop_ss = insertion_points[insertion_id]['stop_ss']

        for linker_length in [2, 3, 4, 5]:

            # Select front linkers

            input_database = 'database/linker_database/linker_{0}_helix_{1}_non_redundant.json'.format(
                start_ss, linker_length)
            output_database = os.path.join(
                data_path, 'selected_linkers_{0}_{1}_front.json'.format(
                    insertion_id, linker_length))
            select_and_dump_linkers(input_pdb, input_database, output_database,
                                    linker_length,
                                    copy.deepcopy(insertion_points),
                                    insertion_id, True)

            # Select back linkers

            input_database = 'database/linker_database/linker_helix_{0}_{1}_non_redundant.json'.format(
                stop_ss, linker_length)
            output_database = os.path.join(
                data_path, 'selected_linkers_{0}_{1}_back.json'.format(
                    insertion_id, linker_length))
            select_and_dump_linkers(input_pdb, input_database, output_database,
                                    linker_length,
                                    copy.deepcopy(insertion_points),
                                    insertion_id, False)
Exemple #28
0
def test():
    args = docopt.docopt(__doc__)
    results = pd.read_pickle(args['<results>'])
    df = pd.read_pickle(args['--dataframe'])
    # Re-build query dataframe
    init()
    helixpath = os.path.expanduser('~/intelligent_design/helix_matcher')
    helices = pd.read_pickle(
        os.path.join(
            helixpath,
            'test_files/boundary/cluster_representatives/query_helices.pkl'))

    results = results.sort_values(by='matches', ascending=False)
    alphapath = helices.iloc[0]['path']
    alpha = clash.get_alphashape(alphapath, chain='B')
    for i in range(0, 100):  # Review top 100 matches for now.
        testrow = results.iloc[i]
        # testgraph = testrow['graph']

        session_from_graph(testrow, helices, df, alpha)
def compare_openmm_energy_pyrosetta_score(cgmodel):
    """
        Given a cgmodel class object, this function determines if PyRosetta and OpenMM give the same score/energy with identical model settings.

        Parameters
        ----------

        cgmodel: Coarse grained model class object.

        """

    #build_params_files(cgmodel)
    pyrosetta.init()

    pyrosetta_sequence = ''.join([
        str('X[' + str(monomer['monomer_name']) + ']')
        for monomer in cgmodel.sequence
    ])
    # Build a PyRosetta pose
    pose = pyrosetta.pose_from_sequence(pyrosetta_sequence)
    # Define a PyRosetta scoring function
    pose.dump_pdb("test_pyrosetta.pdb")
    scorefxn = build_scorefxn(cgmodel)
    cgmodel.positions = PDBFile("test_pyrosetta.pdb").getPositions()
    cgmodel.topology = build_topology(cgmodel)
    write_pdbfile_without_topology(cgmodel, "test_foldamers.pdb")
    # get the PyRosetta score
    score = scorefxn(pose)
    # Build an OpenMM simulation object so that we can calculate the energy using a simulation Context()
    temperature = 300.0 * unit.kelvin
    simulation = build_mm_simulation(cgmodel.topology,
                                     cgmodel.system,
                                     cgmodel.positions,
                                     temperature=temperature,
                                     simulation_time_step=5.0 *
                                     unit.femtosecond)
    # Obtain a state for our simulation context
    energy = simulation.context.getState(getEnergy=True).getPotentialEnergy()
    print("The PyRosetta score is: " + str(score) + "\n")
    print("The OpenMM potential energy is: " + str(energy) + "\n")
    return
Exemple #30
0
    def __init__(self, pdb_file: str, sigmoid_center: float,
                 sigmoid_norm_value: float):
        """
        Create a RosettaFolding landscape from a .pdb file with structure.

        Args:
            pdb_file: Path to .pdb file with structure information.
            sigmoid_center: Center of sigmoid function.
            sigmoid_norm_value: 1 / scale of sigmoid function.

        """
        super().__init__(name="RosettaFolding")

        # Inform the user if pyrosetta is not available.
        try:
            prs
        except NameError as e:
            raise ImportError(
                "Error: Pyrosetta not installed. "
                "Source, binary, and conda installations available "
                "at http://www.pyrosetta.org/dow") from e

        # Initialize pyrosetta and suppress output messages
        prs.init("-mute all")

        # We will reuse this pose over and over, mutating it to match
        # whatever sequence we are given to measure.
        # This is necessary since sequence identity can only be mutated
        # one residue at a time in Rosetta, because the atom coords of the
        # backbone of the previous residue are copied into the new one.
        self.pose = prs.pose_from_pdb(pdb_file)
        self.wt_pose = self.pose.clone()

        # Change self.pose from full-atom to centroid representation
        to_centroid_mover = prs.SwitchResidueTypeSetMover("centroid")
        to_centroid_mover.apply(self.pose)

        # Use 1 - sigmoid(centroid energy / norm_value) as the fitness score
        self.score_function = prs.create_score_function("cen_std")
        self.sigmoid_center = sigmoid_center
        self.sigmoid_norm_value = sigmoid_norm_value
Exemple #31
0
print( mutant_name ) 

import pyrosetta 
import rosetta 
from sys import argv

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 ] ] 
import rosetta
import pyrosetta
import math
from pyrosetta.toolbox import mutate_residue
from itertools import groupby
from operator import itemgetter
pyrosetta.init()

def resi_within(pose, angstrom, the_sun):
    
    def resi_atom_coords(res_in_pose): # input = the pose.residue(number) object
        xyz_coords_list = [float(i) for i in str(res_in_pose.atoms())[31:-1].split(',')] # All atom coords in a residue
        atoms_coords_list = [xyz_coords_list[j:j+3] for j in range(0, len(xyz_coords_list), 3)] # List of lists. xyz of individual residue
        return atoms_coords_list
    
    def distance_between_two_xyz_coords(a,b):
        distance = math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2)
        return distance
    
    resi_within = []
    center = resi_atom_coords(pose.residue(the_sun))
    for resi in range(1, pose.total_residue()+1): # loop over protein
        planets = resi_atom_coords(pose.residue(resi))
        for coords in center:
            for other_coords in planets:
                distance = distance_between_two_xyz_coords(coords,other_coords)
                if distance <= angstrom:
                    resi_within.append(resi)
                
    return sorted(list(set(resi_within)))[0:-1]
import pyrosetta
import math
pyrosetta.init('')

def resi_within(pose, angstrom, the_sun):

    def resi_atom_coords(res_in_pose): # input = the pose.residue(number) object                                                                                                                   
        xyz_coords_list = [float(i) for i in str(res_in_pose.atoms())[31:-1].split(',')] # All atom coords in a residue                                                                            
        atoms_coords_list = [xyz_coords_list[j:j+3] for j in range(0, len(xyz_coords_list), 3)] # List of lists. xyz of individual residue                                                         
        return atoms_coords_list

    def distance_between_two_xyz_coords(a,b):
        distance = math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2)
        return distance

    resi_within = []
    center = resi_atom_coords(pose.residue(the_sun))
    for resi in range(1, pose.total_residue()+1): # loop over protein                                                                                                                              
        planets = resi_atom_coords(pose.residue(resi))
        for coords in center:
            for other_coords in planets:
                distance = distance_between_two_xyz_coords(coords,other_coords)
                if distance <= angstrom:
                    resi_within.append(resi)

    return sorted(list(set(resi_within)))[0:-1]


def CA_distance(pose, res_num_1, res_num_2):

    res_1 = {}