Statistiques
| Branche: | Tag: | Révision :

dockonsurf / modules / screening.py @ 1d22a086

Historique | Voir | Annoter | Télécharger (7,65 ko)

1
import logging
2
import numpy as np
3
import ase
4

    
5
logger = logging.getLogger('DockOnSurf')
6

    
7

    
8
def vect_avg(vects):
9
    """Computes the element-wise mean of a set of vectors.
10

11
    @param vects: np.ndarray with shape (num_vectors, length_vector).
12
    @return: vector average computed doing the element-wise mean.
13
    """
14
    from utilities import try_command
15
    err = "vect_avg parameter vects must be a list-like, able to be converted" \
16
          " np.array"
17
    vects = try_command(np.array, [(ValueError, err)], vects)
18
    if len(vects.shape) == 1:
19
        return vects
20
    else:
21
        num_vects = vects.shape[1]
22
        return np.array([np.average(vects[:, i]) for i in range(num_vects)])
23

    
24

    
25
def get_atom_coords(atoms: ase.Atoms, ctrs_list):
26
    """Gets the coordinates of the specified atoms from a ase.Atoms object.
27

28
    Given an ase.Atoms object and a list of atom indices specified in ctrs_list
29
    it gets the coordinates of the specified atoms. If the element in the
30
    ctrs_list is not an index but yet a list of indices, it computes the
31
    element-wise mean of the coordinates of the atoms specified in the inner
32
    list.
33
    @param atoms: ase.Atoms object for which to obtain the coordinates of.
34
    @param ctrs_list: list of (indices/list of indices) of the atoms for which
35
                      the coordinates should be extracted.
36
    @return: np.ndarray of atomic coordinates.
37
    """
38
    coords = []
39
    for i, elem in enumerate(ctrs_list):
40
        if isinstance(elem, list):
41
            coords.append(vect_avg(np.array([atoms[c].position for c in elem])))
42
        elif isinstance(elem, int):
43
            coords.append(atoms[elem].position)
44
        else:
45
            err = f"'ctrs_list must be a list of ints or lists, {type(elem)} " \
46
                  "found."
47
            logger.error(err)
48
            raise ValueError
49
    return np.array(coords)
50

    
51

    
52
def add_adsorbate(slab, adsorbate, surf_pos, mol_pos, height, offset=None,
53
                  norm_vect=(0, 0, 1)):
54
    """Add an adsorbate to a surface.
55

56
    This function extends the functionality of ase.build.add_adsorbate
57
    (https://wiki.fysik.dtu.dk/ase/ase/build/surface.html#ase.build.add_adsorbate)
58
    by enabling to change the z coordinate and the axis perpendicular to the
59
    surface.
60
    @param slab: ase.Atoms object containing the coordinates of the surface
61
    @param adsorbate: ase.Atoms object containing the coordinates of the
62
        adsorbate.
63
    @param surf_pos: The coordinates of the adsorption site on the surface.
64
    @param mol_pos: The coordinates of the adsorption center in the molecule.
65
    @param height: The height above the surface
66
    @param offset: Offsets the adsorbate by a number of unit cells. Mostly
67
        useful when adding more than one adsorbate.
68
    @param norm_vect: The vector perpendicular to the surface.
69
    """
70
    info = slab.info.get('adsorbate_info', {})
71
    pos = np.array([0.0, 0.0, 0.0])  # (x, y, z) part
72
    spos = np.array([0.0, 0.0, 0.0])  # part relative to unit cell
73
    norm_vect = np.array(norm_vect) / np.linalg.norm(norm_vect)
74
    if offset is not None:
75
        spos += np.asarray(offset, float)
76
    if isinstance(surf_pos, str):
77
        # A site-name:
78
        if 'sites' not in info:
79
            raise TypeError('If the atoms are not made by an ase.build '
80
                            'function, position cannot be a name.')
81
        if surf_pos not in info['sites']:
82
            raise TypeError('Adsorption site %s not supported.' % surf_pos)
83
        spos += info['sites'][surf_pos]
84
    else:
85
        pos += surf_pos
86
    if 'cell' in info:
87
        cell = info['cell']
88
    else:
89
        cell = slab.get_cell()
90
    pos += np.dot(spos, cell)
91
    # Convert the adsorbate to an Atoms object
92
    if isinstance(adsorbate, ase.Atoms):
93
        ads = adsorbate
94
    elif isinstance(adsorbate, ase.Atom):
95
        ads = ase.Atoms([adsorbate])
96
    else:
97
        # Assume it is a string representing a single Atom
98
        ads = ase.Atoms([ase.Atom(adsorbate)])
99
    pos += height * norm_vect
100
    # Move adsorbate into position
101
    ads.translate(pos - mol_pos)
102
    # Attach the adsorbate
103
    slab.extend(ads)
104

    
105

    
106
def ads_euler(molec, surf, site, ctr, pts_angle, neigh_ctr, norm_vect):
107
    from random import random
108
    plane_vect = np.cross(norm_vect, [random() for i in range(3)])
109
    add_adsorbate()
110

    
111
    return
112

    
113

    
114
def ads_chemcat(site, ctr, pts_angle):
115
    return "TO IMPLEMENT"
116

    
117

    
118
def adsorb_confs(conf_list, surf, ads_ctrs, sites, algo, num_pts, neigh_ctrs,
119
                 norm_vect):
120
    """Generates a number of adsorbate-surface structure coordinates.
121

122
    Given a list of conformers, a surface, a list of atom indices (or list of
123
    list of indices) of both the surface and the adsorbate, it generates a
124
    number of adsorbate-surface structures for every possible combination of
125
    them at different orientations.
126
    @param conf_list: list of ase.Atoms of the different conformers
127
    @param surf: the ase.Atoms object of the surface
128
    @param ads_ctrs: the list atom indices of the adsorbate.
129
    @param sites: the list of atom indices of the surface.
130
    @param algo: the algorithm to use for the generation of adsorbates.
131
    @param num_pts: the number of points per angle orientation to sample
132
    @param neigh_ctrs: the indices of the neighboring atoms to the adsorption
133
    atoms.
134
    @param norm_vect: The vector perpendicular to the surface.
135
    @return: list of ase.Atoms for the adsorbate-surface structures
136
    """
137
    surf_ads_list = []
138
    sites_coords = get_atom_coords(surf, sites)
139
    for conf in conf_list:
140
        molec_ctr_coords = get_atom_coords(conf, ads_ctrs)
141
        molec_neigh_coords = get_atom_coords(conf, neigh_ctrs)
142
        for site in sites_coords:
143
            for i, molec_ctr in enumerate(molec_ctr_coords):
144
                if algo == 'euler':
145
                    surf_ads_list.append(ads_euler(conf, surf, site, molec_ctr,
146
                                                   num_pts, norm_vect,
147
                                                   molec_neigh_coords[i]))
148
                elif algo == 'chemcat':
149
                    surf_ads_list.append(ads_chemcat(site, molec_ctr, num_pts))
150
    return surf_ads_list
151

    
152

    
153
def run_screening(inp_vars):
154
    """Carry out the screening of adsorbate coordinates on a surface
155

156
    @param inp_vars: Calculation parameters from input file.
157
    """
158
    import os
159
    from modules.formats import read_coords, read_energies, \
160
        rdkit_mol_to_ase_atoms, adapt_format
161
    from modules.clustering import get_rmsd, clustering
162
    from modules.isolated import get_moments_of_inertia
163
    from modules.calculation import run_calc
164

    
165
    if not os.path.isdir("isolated"):
166
        err = "'isolated' directory not found. It is needed in order to carry "
167
        "out the screening of structures to be adsorbed"
168
        logger.error(err)
169
        raise ValueError(err)
170

    
171
    conf_list = read_coords(inp_vars['code'], 'isolated', 'rdkit')
172
    # TODO Implement neighbors algorithm
173
    # neigh_list = get_neighbors(conf_list[0], inp_vars['molec_ads_ctrs'])
174
    conf_enrgs = read_energies(inp_vars['code'], 'isolated')
175
    mois = np.array([get_moments_of_inertia(conf)[0] for conf in conf_list])
176
    rmsd_mtx = get_rmsd(conf_list)
177
    exemplars = clustering(rmsd_mtx)
178
    conf_list = [conf_list[idx] for idx in exemplars]
179
    conf_list = [rdkit_mol_to_ase_atoms(conf) for conf in conf_list]
180
    surf = adapt_format('ase', inp_vars['surf_file'])
181
    surf_ads_list = adsorb_confs(conf_list, surf, inp_vars['molec_ads_ctrs'],
182
                                 inp_vars['sites'], inp_vars['ads_algo'],
183
                                 inp_vars['sample_points_per_angle'],
184
                                 inp_vars['molec_neigh_ctrs'],
185
                                 inp_vars['surf_norm_vect'])
186
    run_calc('screening', inp_vars, surf_ads_list)