Ejemplo n.º 1
0
    def save_merged_ligand_protein(self, raw_protein_file, raw_ligand_file):
        """
		Merge structures from files and save to save directory
		:param raw_ligand_file: absolute paths
		:return:
		"""
        prot_st = next(StructureReader(raw_protein_file))
        alpha = 'ABCDEFGHIJKMNOPQRST'
        alpha_count = 0
        for c in prot_st.chain:
            if c.name.strip() == '': continue
            c.name = alpha[alpha_count]
            alpha_count += 1

        if raw_ligand_file != '':
            lig_st = next(StructureReader(raw_ligand_file))
            # standardize chain naming
            for c in lig_st.chain:
                c.name = 'L'
            merged_st = lig_st.merge(prot_st)
        else:
            merged_st = prot_st

        st_wr = StructureWriter(self.path + self.raw_complex)
        st_wr.append(merged_st)
        st_wr.close()
Ejemplo n.º 2
0
def get_residues_from_radius(radius, ref):
    asl = 'fillres ((within %i ligand ) and not (res.ptype "T3P"))' % (int(float(radius)))
    st=StructureReader(ref).next()
    atoms=evaluate_asl(st, asl)
    if len(atoms)==0:
        print "NO LIGAND IN REFERENCE FILE"
        print "no ligand in reference file"
        sys.exit()
    pocket=st.extract(atoms)
    resnames=[i.pdbres for i in pocket.residue]
    resnums=[i.resnum for i in pocket.residue]
    chains=[i.chain for i in pocket.residue]
    data=dict()
    for chain in set(chains):
        for (n,c) in zip(resnums, chains):
            if c not in data.keys():
                data[c]=[]
            if str(n) not in data[c]:
                data[c].append(str(n))
    selection=[]
    for chain in data.keys():
        selection.append(','.join(data[chain]) + '.%s' % chain)
    if len(selection)==1:
        selection=[selection,]
    return selection
Ejemplo n.º 3
0
 def write_grid_in_file(self,
                        mode,
                        grid_ligand='',
                        xyz=False,
                        receptor_file=''):
     if mode == 'other_ligand':
         st_2 = next(StructureReader(grid_ligand))
         c2 = get_centroid(st_2)
         x, y, z = c2[:3]
     elif mode == 'xyz':
         x, y, z = xyz
     else:
         st_2 = next(StructureReader(self.path + self.split_ligand))
         c2 = get_centroid(st_2)
         x, y, z = c2[:3]
     if receptor_file == '':
         use_file = self.split_protein
     else:
         use_file = receptor_file
     with open(self.path + self.grid_in, 'w') as f:
         f.write('GRID_CENTER {},{},{}\n'.format(x, y, z))
         f.write('GRIDFILE {}\n'.format(self.grid_file))
         f.write('INNERBOX 15,15,15\n')
         f.write('OUTERBOX 30,30,30\n')
         f.write('RECEP_FILE {}\n'.format(use_file))
Ejemplo n.º 4
0
def get_residues_from_radius(radius, ref):
    asl = 'fillres ((within %i ligand ) and not (res.ptype "T3P"))' % (int(
        float(radius)))
    st = StructureReader(ref).next()
    atoms = evaluate_asl(st, asl)
    if len(atoms) == 0:
        print "NO LIGAND IN REFERENCE FILE"
        print "no ligand in reference file"
        sys.exit()
    pocket = st.extract(atoms)
    resnames = [i.pdbres for i in pocket.residue]
    resnums = [i.resnum for i in pocket.residue]
    chains = [i.chain for i in pocket.residue]
    data = dict()
    for chain in set(chains):
        for (n, c) in zip(resnums, chains):
            if c not in data.keys():
                data[c] = []
            if str(n) not in data[c]:
                data[c].append(str(n))
    selection = []
    for chain in data.keys():
        selection.append(','.join(data[chain]) + '.%s' % chain)
    if len(selection) == 1:
        selection = [
            selection,
        ]
    return selection
Ejemplo n.º 5
0
    def extract_prot_lig(self, structure_set_info):
        '''
        Setup and start running a set of docking task
        structure_set_info: (list of dicts) 
            [{'folder', 'pdb', 'prot':['A','B'], 'lig':'L'}]
        :return: (None)

        for structure in structure_set_info:
            with StructureReader(input_pdb) as st:
                        st = list(st)[0]
            
        '''
        print(structure_set_info)
        for task in structure_set_info:
            base = task['folder'] + '/' + task['name']
            if task['method'] == 'by_chain':
                #extract specific chains
                with StructureReader(base + '.pdb') as st:
                    st = list(st)[0]
                    st_prot = st.chain[task['P']].extractStructure(
                        copy_props=True)
                    st_prot.write(base + '_prot.mae')

                    st_lig = st.chain[task['L']].extractStructure(
                        copy_props=True)
                    st_lig.write(base + '_lig.mae')
            if task['method'] == 'by_res':
                #extract specific chains
                with StructureReader(base + '.pdb') as st:
                    st = list(st)[0]
                    lig = [
                        a.index for a in st.atom
                        if a.getResidue().pdbres == task['L']
                    ]
                    print(lig)
                    st_lig = st.extract(lig)
                    st_lig.write(base + '_lig.mae')

                    st_prot = st.extract([
                        a.index for a in st.atom
                        if a.getResidue().pdbres != task['L']
                    ])
                    st_prot.write(base + '_prot.mae')
            if task['method'] == 'from_PDBBind':
                print(task['method'])
                name_lower = task['name'].lower()
                with StructureReader(task['folder'] + '/' + name_lower +
                                     '_protein.pdb') as st:
                    st = list(st)[0]
                    st.write(base + '_prot.mae')
                with StructureReader(task['folder'] + '/' + name_lower +
                                     '_ligand.mol2') as st:
                    st = list(st)[0]
                    st.write(base + '_lig.mae')

        return False
def create_feature_vector(protein, ligand, pickle_file, combind_root):
    ending_1 = '{}/structures/aligned_files/{}/{}_out.mae'.format(
        protein, ligand, ligand)
    s = list(StructureReader(combind_root + ending_1))[0]
    rot_s = list(StructureReader(combind_root + '/' + ending_1))[0]
    residues = get_all_res(s, rot_s)
    print(residues)
    outfile = open(pickle_file, 'wb')
    pickle.dump(residues, outfile)
    outfile.close()
Ejemplo n.º 7
0
def check_selection_boolean(ref, target):
    st=StructureReader(ref).next()
    atoms=evaluate_asl(st, 'all')
    sub=st.extract(atoms)
    resnames=[i.pdbres.rstrip() for i in sub.residue]
    if target in resnames:
        verdict=True
    else:
        verdict=False
    return verdict
Ejemplo n.º 8
0
def check_selection_boolean(ref, target):
    st = StructureReader(ref).next()
    atoms = evaluate_asl(st, 'all')
    sub = st.extract(atoms)
    resnames = [i.pdbres.rstrip() for i in sub.residue]
    if target in resnames:
        verdict = True
    else:
        verdict = False
    return verdict
Ejemplo n.º 9
0
def load_pdb_struct(path,residue_cls  = BaseResidue):
    st = StructureReader(path).next()

    st = mystructure(st)
    if residue_cls is not None:
        residues = map(residue_cls,st.residue)
        #use custom Residue class
        st.residues = residues
        st.src = path

    return st
Ejemplo n.º 10
0
def compute_protein_mcss(protein, ligands, save_folder):
    init_file = '{}/{}_mcss.csv'.format(save_folder, protein)
    for i in range(len(ligands)):
        for j in range(i + 1, len(ligands)):
            l1, l2 = ligands[i], ligands[j]
            l1_path = '/scratch/PI/rondror/combind/bpp_data/MAPK14/ligands/prepared_ligands/{}_lig/{}_lig.mae'.format(
                l1, l1)
            l2_path = '/scratch/PI/rondror/combind/bpp_data/MAPK14/ligands/prepared_ligands/{}_lig/{}_lig.mae'.format(
                l2, l2)
            mcss_types_file = 'mcss_type_file.typ'
            mcss = MCSS(l1, l2)
            with StructureReader(l1_path) as ligand1, StructureReader(
                    l2_path) as ligand2:
                ligands = {l1: next(ligand1), l2: next(ligand2)}
                mcss.compute_mcss(ligands, init_file, mcss_types_file)
Ejemplo n.º 11
0
def generate_tree(maefile, origin, charge):
    """
    A helper function to generate tree structure from a given maefile and origin

    :type  maefile: str
    :param maefile: name of the maefile, endwith .mae

    :type  origin: int
    :param origin: atom of interest

    :type  charge: bool
    :param charge: use ESP charge for atomic descriptor

    return tree structure
    """
    print(f'Processing {maefile}')
    st = next(StructureReader(maefile))
    sorted_atoms = sort_atom_by_atomic(st)
    print(f'Using atom {origin} ({st.atom[origin].element}) as origin.\n')
    if charge:
        try:
            root = Node(None, origin, st.atom[origin].element,
                        st.atom[origin].property['r_j_ESP_Charges'], None,
                        set())
        except:
            sys.exit(
                'Warning: You need to have ESP charge in the maefile in order to run charge option!!!'
            )
    else:
        root = Node(None, origin, st.atom[origin].element, 0, None, set())
    get_stereomatic_desc(st, root, sorted_atoms, charge)

    return root
Ejemplo n.º 12
0
def main():
    args = parse_args()
    print("args", args)

    if args.implementation == TORCHANI:
        from torchani_calculator import torchani_calculator
        calculator = torchani_calculator(args.network_type, args.numb_networks)
    elif args.implementation == AES_ANI:
        from ani_ase import ani_ase_calculator
        calculator = ani_ase_calculator(args.network_type)
    elif args.implementation == KHAN:
        from khan_calculator import khan_calculator
        calculator = khan_calculator(args.network_type, args.khan_network,
                                     args.numb_networks)

    strs = list(StructureReader(args.mae_file))
    cvgd = optimize_structures(strs,
                               calculator.committee,
                               maxit=500,
                               thresh=0.01)

    rd = rawdataset_from_st(strs)
    energy_data = calculator.committee.compute_data(rd)
    for st, data in zip(strs, energy_data):
        st.property["r_j_ANI_ENERGY"] = data.energy
        st.property["r_j_ANI_RHO"] = data.rho

    base, ext = os.path.splitext(args.mae_file)
    outfile = base + "_optimized" + ext
    print("final structure written to file: %s" % outfile)
    with StructureWriter(outfile) as writer:
        writer.extend(strs)
Ejemplo n.º 13
0
def molecule_to_schrodinger_struct(molecule: Molecule):
    """
    Convert a pymatgen Molecule object to a Schrodinger Structure object

    Args:
        molecule (pymatgen.core.structure.Molecule): Molecule to be converted

    Returns:
        struct: schrodinger.structure.Structure object
    """

    # First need to convert molecule to file to use StructureReader

    file_suffix = random.randint(1, 100000000)
    molecule.to('sdf', "temp_conversion{}.sdf".format(file_suffix))

    reader = StructureReader("temp_conversion{}.sdf".format(file_suffix))

    # Assume only one structure (should be the case for a single SDF file)
    struct = [r for r in reader][0]

    for atom in struct.atom:
        atom.formal_charge = 0
    struct.atom[1].formal_charge = molecule.charge

    Path("temp_conversion{}.sdf".format(file_suffix))

    return struct
Ejemplo n.º 14
0
def aggregate_structures(data_path, save_location, scores_version):
    protein = 'MAPK14'
    print(protein)

    #try to load the score file
    scores_file = "{}/{}/scores/{}/pdb.sc".format(data_path, protein,
                                                  scores_version)

    if os.path.isfile(scores_file):

        ligand_folder = '{}/{}/structures/aligned_files'.format(
            data_path, protein)
        ligands = os.listdir(ligand_folder)

        # write one mae files for all poses
        with StructureWriter('{}/all_{}_pv.mae'.format(save_location,
                                                       protein)) as all:

            #iterate over each scored ligand
            for i, ligand in enumerate(ligands):
                pose_file = "{}/{}/structures/aligned_files/{}/{}_out.mae".format(
                    data_path, protein, ligand, ligand)

                #load the structure file containing docking results
                pv = list(StructureReader(pose_file))
                print(pv)

                #add the protein structure but only for the first file
                all.append(pv[0])
Ejemplo n.º 15
0
def compute_protein_mcss(ligands, pair_path):
    init_file = '{}/{}-to-{}_mcss.csv'.format(pair_path, ligands[0],
                                              ligands[1])
    for i in range(len(ligands)):
        for j in range(i + 1, len(ligands)):
            l1, l2 = ligands[i], ligands[j]
            l1_path = '{}/ligand_poses/{}_lig0.mae'.format(pair_path, l1)
            new_l1_path = create_mcss_file(l1_path, l1, pair_path)
            l2_path = '{}/{}_lig.mae'.format(pair_path, l2)
            new_l2_path = create_mcss_file(l2_path, l2, pair_path)
            mcss_types_file = 'mcss_type_file.typ'
            mcss = MCSS(l1, l2)
            with StructureReader(new_l1_path) as ligand1, StructureReader(
                    new_l2_path) as ligand2:
                ligands = {l1: next(ligand1), l2: next(ligand2)}
                mcss.compute_mcss(ligands, init_file, mcss_types_file)
            os.system('rm {} {}'.format(new_l1_path, new_l2_path))
Ejemplo n.º 16
0
def _show_schrodinger_file(path, **kwargs):
    from schrodinger.structure import StructureReader

    view = NGLWidget()
    cts = list(StructureReader(path))
    for ct in cts:
        view.add_component(SchrodingerStructure(ct), **kwargs)
    return view
Ejemplo n.º 17
0
 def load_poses(self, maxposes=10):
     poses = []
     for i, st in enumerate(StructureReader(self.folder+'/'+self.pose_viewer_file_name)):
         if i > maxposes: break
         if i == 0:
             prot_st = st
             continue
         poses.append(st)  
     return prot_st, poses
def get_sequence_from_str(file):
    s = list(StructureReader(file))[0]
    str = ''
    for m in list(s.molecule):
        if len(m.residue) != 1:
            for r in list(m.residue):
                atom = list(r.atom)[0]
                if (atom.chain == "A"):  # to fix for MAPK14: 3GCU
                    str += atom.pdbcode
    return str
def get_sequence_from_str(file, chains, protein):
    s = list(StructureReader(file))[0]
    str = ''
    for m in list(s.molecule):
        if len(m.residue) != 1:
            for r in list(m.residue):
                atom = list(r.atom)[0]
                if atom.chain == chains[protein]:
                    str += atom.pdbcode
    return str
def main():
    coms = {}
    with open(prot_file) as fp:
        for line in tqdm(fp, desc='protein file'):
            if line[0] == '#': continue
            protein, target, start = line.strip().split()
            if protein not in coms:
                coms[protein] = {}
            protein_folder = os.path.join(data_root,
                                          protein + '/structures/aligned')
            if start not in coms[protein]:
                file = os.path.join(protein_folder, start + '_prot.mae')
                s = list(StructureReader(file))[0]
                coms[protein][start] = analyze.center_of_mass(s)
                file = os.path.join(protein_folder, start + '_prot.mae')
                s = list(StructureReader(file))[0]
                coms[protein][start] = analyze.center_of_mass(s)

    with open('com_after_aligned.pkl', 'wb') as f:
        pickle.dump(coms, f)
Ejemplo n.º 21
0
def docking(grid):

    ligands = os.listdir(grid)
    similarities = []
    lgr = logger()
    cfg = CanvasFingerprintGenerator(lgr, 'Radial')
    cfs = CanvasFingerprintSimilarity(lgr)
    cfs.setMetric('Tanimoto')

    for struc_ligand in ligands:
        for ligand in ligands:
            prepped_ligand_file = '/scratch/PI/rondror/combind/bpp_data/MAPK14/ligands/prepared_ligands/{}_lig/{}_lig.mae'.format(
                ligand, ligand)
            prepped_struc_ligand_file = '/scratch/PI/rondror/combind/bpp_data/MAPK14/ligands/prepared_ligands/{}_lig/{}_lig.mae'.format(
                struc_ligand, struc_ligand)
            lig = cfg.generate(next(StructureReader(prepped_ligand_file)))
            struc_lig = cfg.generate(
                next(StructureReader(prepped_struc_ligand_file)))
            similarities.append(cfs.calculateSimilarity(lig, struc_lig))

    outfile = open('/home/users/sidhikab/MAPK14_similarities', 'wb')
    pickle.dump(similarities, outfile)
    outfile.close()
def find_chain(protein, chains, ligand):
    protein_folder = os.path.join(data_root, protein + '/structures/aligned')
    primary_file = os.path.join(protein_folder, ligand + '_prot.mae')
    s = list(StructureReader(primary_file))[0]
    chain_list = []
    for m in list(s.molecule):
        for r in list(m.residue):
            atom = list(r.atom)[0]
            if atom.chain not in chain_list:
                chain_list.append(atom.chain)
    if protein not in chains:
        chains[protein] = chain_list
    else:
        chains[protein] = set.intersection(set(chains[protein]),
                                           set(chain_list))
Ejemplo n.º 23
0
def main():
    coms = {}
    with open(prot_file) as fp:
        for line in tqdm(fp, desc='protein file'):
            if line[0] == '#': continue
            protein, target, start = line.strip().split()

            if protein not in coms:
                coms[protein] = {}

            if start not in coms[protein]:
                start_receptor_file = os.path.join(
                    data_root,
                    '{}/structures/aligned/{}_prot.mae'.format(protein, start))
                start_ligand_file = os.path.join(
                    data_root,
                    '{}/structures/aligned/{}_lig.mae'.format(protein, start))
                start_struct = list(StructureReader(start_receptor_file))[0]
                start_lig = list(StructureReader(start_ligand_file))[0]
                # print(protein, start)
                coms[protein][start] = get_pocket_res(start_struct, start_lig)

            if target not in coms[protein]:
                target_receptor_file = os.path.join(
                    data_root, '{}/structures/aligned/{}_prot.mae'.format(
                        protein, target))
                target_ligand_file = os.path.join(
                    data_root,
                    '{}/structures/aligned/{}_lig.mae'.format(protein, target))
                target_struct = list(StructureReader(target_receptor_file))[0]
                target_lig = list(StructureReader(target_ligand_file))[0]
                # print(protein, target)
                get_pocket_res(target_struct, target_lig)

    with open('pocket_com.pkl', 'wb') as f:
        pickle.dump(coms, f)
Ejemplo n.º 24
0
def main():

    maefile = sys.argv[1]
    origin = int(sys.argv[2])

    print(f'Processing {maefile}')
    st = next(StructureReader(maefile))
    print(f'Using atom {origin} ({st.atom[origin].element}) as origin.\n')

    # Index of atom origin of stereomatic network
    sd = get_stereomatic_desc(st, origin, set([origin]))
    print(sd)

    with open(maefile.replace('.mae', '.json'), 'w') as fh:
        json.dump(sd, fh, indent=4)
Ejemplo n.º 25
0
    def _set_ligand_sizes(self, structure_file):
        try:
            refs = [st for st in StructureReader(structure_file)]
        except:
            print('Unable to read MCSS structure file for', self.l1, self.l2)
            return None
        if len(refs) != 2:
            print('Wrong number of structures', self.l1, self.l2)
            return None
        ref1, ref2 = refs
        n_l1_atoms = len([a for a in ref1.atom if a.element != 'H'])
        n_l2_atoms = len([a for a in ref2.atom if a.element != 'H'])

        self.n_l1_atoms = n_l1_atoms
        self.n_l2_atoms = n_l2_atoms
Ejemplo n.º 26
0
def run_group(grouped_files, raw_root, index, clash_dir):
    """
    checks mean distance of displacement for decoys for each protein, target, start group
    :param grouped_files: (list) list of protein, target, start groups
    :param raw_root: (string) directory where raw data will be placed
    :param index: (int) group number
    :param dist_dir: (string) directiory to place distances
    :param max_poses: (int) maximum number of glide poses considered
    :param max_decoys: (int) maximum number of decoys created per glide pose
    :return:
    """
    clash_dict = {}
    for protein, target, start in grouped_files[index]:
        protein_path = os.path.join(raw_root, protein)
        pair_path = os.path.join(protein_path, '{}-to-{}'.format(target, start))
        pose_path = os.path.join(pair_path, 'ligand_poses')
        struct_path = os.path.join(pair_path, '{}_prot.mae'.format(start))
        lig_path = os.path.join(pose_path, '{}_lig0.mae'.format(target))
        s1 = list(StructureReader(struct_path))[0]
        lig = list(StructureReader(lig_path))[0]
        clash_dict[(protein, target, start)] = steric_clash.clash_volume(s1, struc2=lig)

    outfile = open(os.path.join(clash_dir, '{}.pkl'.format(index)), 'wb')
    pickle.dump(clash_dict, outfile)
Ejemplo n.º 27
0
def file_to_schrodinger_structure(filename: Union[str, Path]):
    """
    Convert a file (sdf, pdb, sd, mol2, maestro, or maestro_text) to a
        Schrodinger Structure object.

    Args:
        filename (str): Name of the file

    Returns:
        structures (list of schrodinger.structure.Structure objects)
    """

    if isinstance(filename, Path):
        fn = filename.as_posix()
    else:
        fn = filename

    reader = StructureReader(fn)

    structures = [s for s in reader]
    return structures
Ejemplo n.º 28
0
def run_group(grouped_files, raw_root, index):
    for protein, target, start in grouped_files[index]:
        pair = '{}-to-{}'.format(target, start)
        protein_path = os.path.join(raw_root, protein)
        pair_path = os.path.join(protein_path, pair)
        pose_path = os.path.join(pair_path, 'ligand_poses')

        # comput mcss
        compute_protein_mcss([target, start], pair_path)

        # combine ligands
        with StructureWriter('{}/{}_merge_pv.mae'.format(pair_path,
                                                         pair)) as all_file:
            for file in os.listdir(pose_path):
                if file[-3:] == 'mae':
                    pv = list(StructureReader(os.path.join(pose_path, file)))
                    all_file.append(pv[0])

        # zip file
        os.system('gzip -f {}/{}_merge_pv.mae'.format(pair_path, pair,
                                                      pair_path, pair))
Ejemplo n.º 29
0
    def split(self):
        #look for the opt_complex, if it doesn't exist, just use the prepped complex

        usefile = ''
        if (os.path.isfile(self.path + self.align_file)):
            usefile = self.path + self.align_file
        else:
            usefile = self.path + self.prepped_complex

        st = next(StructureReader(usefile))
        prot_st = st.extract([a.index for a in st.atom if a.chain != 'L'])
        prot_st.title = '{}_prot'.format(self.name)

        lig_st = st.extract([a.index for a in st.atom if a.chain == 'L'])
        lig_st.title = '{}_lig'.format(self.name)

        prot_wr = StructureWriter(self.path + self.split_protein)
        prot_wr.append(prot_st)
        prot_wr.close()

        lig_wr = StructureWriter(self.path + self.split_ligand)
        lig_wr.append(lig_st)
        lig_wr.close()
def main():
    args = parse_args()
    print("args", args)

    if args.implementation == TORCHANI:
        from torchani_calculator import torchani_calculator
        calculator = torchani_calculator(args.network_type, args.numb_networks)
    elif args.implementation == AES_ANI:
        from ani_ase import ani_ase_calculator
        calculator = ani_ase_calculator(args.network_type)
    elif args.implementation == KHAN:
        from khan_calculator import khan_calculator
        calculator = khan_calculator(args.network_type, args.khan_network,
                                     args.numb_networks)

    #assert args.cif_file.endswith('.cif') or args.cif_file.endswith('.xyz')
    if args.cif_file.endswith('.mae'):
        st = next(StructureReader(args.cif_file))

        if args.truncate_box:
            # reduced size box
            a = 12.0
            deletions = []
            for mol in st.molecule:
                rcom = center_of_mass(st, mol.getAtomIndices())
                inbox = [abs(x) < a / 2 for x in rcom]
                if False in [abs(x) < a / 2 for x in rcom]:
                    deletions.extend(mol.getAtomIndices())
            st.deleteAtoms(deletions)

        rd = rawdataset_from_st([st])
        ase_molecs = khan_molec_to_ase_atoms(rd.all_Xs)
        atoms = ase_molecs[0]

        if args.truncate_box:
            # hard coded box
            #a = 22.6868
            vecs = [[a, 0.0, 0.0], [0.0, a, 0.0], [0.0, 0.0, a]]
            atoms.set_cell(vecs)
            atoms.set_pbc([True, True, True])
            print("after set cell", atoms.get_pbc())

    if args.cif_file.endswith('.cif'):
        atoms = ase_io.read(args.cif_file)

    if args.box_length is not None:
        atoms.set_cell([
            [args.box_length, 0.0, 0.0],
            [0.0, args.box_length, 0.0],
            [0.0, 0.0, args.box_length],
        ])
        atoms.set_pbc([True, True, True])

    if args.supercell is not None:
        atoms = build_supercell(atoms, [args.supercell] * 3)

    periodic = False not in atoms.get_pbc()

    print("cell")
    print(atoms.get_cell())

    if periodic:
        #atoms.wrap()
        space_group = spacegroup.get_spacegroup(atoms)
        print("Space group of crystal: %s" % space_group)
        print("initial unit cell")
        print(atoms.cell)

        # this shows how to get unique atoms and there equivalents
        #scaled_positions = atoms.get_scaled_positions()
        #unique_positions = space_group.unique_sites(scaled_positions)
        #all_positions, symmetry_map = space_group.equivalent_sites(unique_positions)
        #symmetry_groups = defaultdict(list)
        #for igroup, position in zip(symmetry_map, all_positions):
        #    symmetry_groups[igroup].append(position)

        #print("unique positions")
        #for xyz in unique_positions:
        #    print(xyz)

        #for igroup in sorted(symmetry_groups.keys()):
        #    print("positions in symmetry group %d" % igroup)
        #    for xyz in symmetry_groups[igroup]:
        #        print(xyz)

    torsions = ()
    if args.torsion is not None:
        torsions = [(
            float(args.torsion[0]),
            int(args.torsion[1]),
            int(args.torsion[2]),
            int(args.torsion[3]),
        )]

    if args.optimize:
        # cannot optimize cell until we implement a stress tensor
        energy = optimize_molecule(
            atoms,
            calculator,
            torsions=torsions,
            thresh=0.05,
            optimize_cell=args.relax_cell,
        )
    else:
        start_time = time.time()
        energy = single_point_energy(atoms, calculator)
        print("--- %s seconds ---" % (time.time() - start_time))
    if args.dynamics:
        traj = molecular_dynamics(atoms,
                                  calculator,
                                  total_time=args.total_time,
                                  time_step=args.time_step)
        if args.cif_file.endswith('.mae'):
            st = next(StructureReader(args.cif_file))
            with StructureWriter("md_path.mae") as writer:
                for m in traj:
                    st0 = st.copy()
                    st0.setXYZ(m.get_positions())
                    writer.append(st0)
        else:
            with open("md_path.xyz", "w") as fout:
                xyz_lst = []
                for atoms in traj:
                    xyz_lst.append("%d\n" % len(atoms))
                    species = atoms.get_chemical_symbols()
                    carts = atoms.get_positions()
                    for ch, xyz in zip(species, carts):
                        xyz_lst.append("%s %.8f %.8f %.8f" %
                                       (ch, xyz[0], xyz[1], xyz[2]))

                fout.write("\n".join(xyz_lst))

    print("energy of cell (au):", energy)

    if periodic:
        space_group = spacegroup.get_spacegroup(atoms)
        print("Final Space group of crystal: %s" % space_group)
        print("energy of cell/volume (au):", energy / atoms.get_volume())
        print("final unit cell")
        print(atoms.cell)

    print("Uncertainty %.4f (kcal/mol)" %
          (calculator.uncertainty(atoms) * 627.509))

    if periodic:
        outfile = os.path.splitext(args.cif_file)[0] + "_optimized.cif"
    else:
        outfile = os.path.splitext(args.cif_file)[0] + "_optimized.xyz"
    ase_io.write(outfile, atoms)
    print("final structure written to file: %s" % outfile)
Ejemplo n.º 31
0
 def read_pv_file(pvfile):
     if not fileutils.is_poseviewer_file(pvfile):
         raise PoseViewerFileInvalidError(pvfile)
     reader = StructureReader(pvfile)
     return (Receptor(reader.next()),
             tuple(Pose(st, i) for i, st in enumerate(reader)))
Ejemplo n.º 32
0
    for i, group in enumerate(grouped_files):
        print('making grid', i)

        with open('{}/run/grid{}_in.sh'.format(save, i), 'w') as f:

            for s_file in group:
                out_f = s_file[:12]
                os.system('mkdir -p {}/{}'.format(save, out_f))

                with open('{}/{}/{}.in'.format(save, out_f, out_f),
                          'w') as f_in:

                    if len(s_file) != 16:
                        continue

                    s = next(StructureReader(ligands + s_file[:4] +
                                             '_lig.mae'))
                    c = get_centroid(s)
                    x, y, z = c[:3]

                    f_in.write('GRID_CENTER {},{},{}\n'.format(x, y, z))
                    f_in.write('GRIDFILE {}.zip\n'.format(out_f))
                    f_in.write('INNERBOX 15,15,15\n')
                    f_in.write('OUTERBOX 30,30,30\n')
                    f_in.write('RECEP_FILE {}/{}\n'.format(root, s_file))
                    f.write('#!/bin/bash\n')
                    f.write('cd {}/{}\n'.format(save, out_f))
                    f.write('$SCHRODINGER/glide -WAIT {}.in\n'.format(out_f))

        os.chdir('{}/run'.format(save))
        os.system(
            'sbatch -p owners -t 02:00:00 -o grid{}.out grid{}_in.sh'.format(
Ejemplo n.º 33
0
def parse(pdbfile):
    list(StructureReader(pdbfile))
Ejemplo n.º 34
0
    return complete_a_list


if __name__ == '__main__':
    folder = '/scratch/PI/rondror/combind/bpp_data/MAPK14/structures/aligned_files/'
    ligands = os.listdir(folder)
    ligands.remove("4DLI")
    infile = open('MAPK14_pairwise_alignment', 'rb')
    paired_strs = pickle.load(infile)
    infile.close()
    rmsds = []

    for i in range(len(ligands)):
        ending_1 = '{}/{}_out.mae'.format(ligands[i], ligands[i])
        s1 = list(StructureReader(folder + ending_1))[0]
        arr = []

        for j in range(len(ligands)):

            #to monitor progress
            print(i, ligands[i], j, ligands[j])
            ending_2 = '{}/{}_out.mae'.format(ligands[j], ligands[j])
            s2 = list(StructureReader(folder + ending_2))[0]

            (paired_str_s1, paired_str_s2) = paired_strs[i][j]

            r_list_s1 = get_all_res(s1)
            r_list_s2 = get_all_res(s2)

            r_to_i_map_s1 = map_residues_to_align_index(