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

dockonsurf / modules / screening.py @ b4aef3d7

Historique | Voir | Annoter | Télécharger (8,18 ko)

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

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

    
7

    
8
def get_vect_angle(v1, v2, degrees=False):
9
    """Computes the angle between two vectors.
10

11
    @param v1: The first vector.
12
    @param v2: The second vector.
13
    @param degrees: Whether the result should be in radians (True) or in
14
        degrees (False).
15
    @return: The angle in radians if degrees = False, or in degrees if
16
        degrees =True
17
    """
18
    v1_u = v1 / np.linalg.norm(v1)
19
    v2_u = v2 / np.linalg.norm(v2)
20
    angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
21
    return angle if not degrees else angle * 180 / np.pi
22

    
23

    
24
def vect_avg(vects):
25
    """Computes the element-wise mean of a set of vectors.
26

27
    @param vects: np.ndarray with shape (num_vectors, length_vector).
28
    @return: vector average computed doing the element-wise mean.
29
    """
30
    from utilities import try_command
31
    err = "vect_avg parameter vects must be a list-like, able to be converted" \
32
          " np.array"
33
    vects = try_command(np.array, [(ValueError, err)], vects)
34
    if len(vects.shape) == 1:
35
        return vects
36
    else:
37
        num_vects = vects.shape[1]
38
        return np.array([np.average(vects[:, i]) for i in range(num_vects)])
39

    
40

    
41
def get_atom_coords(atoms: ase.Atoms, ctrs_list):
42
    """Gets the coordinates of the specified atoms from a ase.Atoms object.
43

44
    Given an ase.Atoms object and a list of atom indices specified in ctrs_list
45
    it gets the coordinates of the specified atoms. If the element in the
46
    ctrs_list is not an index but yet a list of indices, it computes the
47
    element-wise mean of the coordinates of the atoms specified in the inner
48
    list.
49
    @param atoms: ase.Atoms object for which to obtain the coordinates of.
50
    @param ctrs_list: list of (indices/list of indices) of the atoms for which
51
                      the coordinates should be extracted.
52
    @return: np.ndarray of atomic coordinates.
53
    """
54
    coords = []
55
    for i, elem in enumerate(ctrs_list):
56
        if isinstance(elem, list):
57
            coords.append(vect_avg(np.array([atoms[c].position for c in elem])))
58
        elif isinstance(elem, int):
59
            coords.append(atoms[elem].position)
60
        else:
61
            err = f"'ctrs_list must be a list of ints or lists, {type(elem)} " \
62
                  "found."
63
            logger.error(err)
64
            raise ValueError
65
    return np.array(coords)
66

    
67

    
68
def add_adsorbate(slab, adsorbate, surf_pos, mol_pos, height, offset=None,
69
                  norm_vect=(0, 0, 1)):
70
    """Add an adsorbate to a surface.
71

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

    
121

    
122
def ads_euler(molec, surf, site, ctr, pts_angle, neigh_ctr, norm_vect):
123
    from random import random
124
    plane_vect = np.cross(norm_vect, [random() for i in range(3)])
125
    add_adsorbate()
126

    
127
    return
128

    
129

    
130
def ads_chemcat(site, ctr, pts_angle):
131
    return "TO IMPLEMENT"
132

    
133

    
134
def adsorb_confs(conf_list, surf, ads_ctrs, sites, algo, num_pts, neigh_ctrs,
135
                 norm_vect):
136
    """Generates a number of adsorbate-surface structure coordinates.
137

138
    Given a list of conformers, a surface, a list of atom indices (or list of
139
    list of indices) of both the surface and the adsorbate, it generates a
140
    number of adsorbate-surface structures for every possible combination of
141
    them at different orientations.
142
    @param conf_list: list of ase.Atoms of the different conformers
143
    @param surf: the ase.Atoms object of the surface
144
    @param ads_ctrs: the list atom indices of the adsorbate.
145
    @param sites: the list of atom indices of the surface.
146
    @param algo: the algorithm to use for the generation of adsorbates.
147
    @param num_pts: the number of points per angle orientation to sample
148
    @param neigh_ctrs: the indices of the neighboring atoms to the adsorption
149
    atoms.
150
    @param norm_vect: The vector perpendicular to the surface.
151
    @return: list of ase.Atoms for the adsorbate-surface structures
152
    """
153
    surf_ads_list = []
154
    sites_coords = get_atom_coords(surf, sites)
155
    for conf in conf_list:
156
        molec_ctr_coords = get_atom_coords(conf, ads_ctrs)
157
        molec_neigh_coords = get_atom_coords(conf, neigh_ctrs)
158
        for site in sites_coords:
159
            for i, molec_ctr in enumerate(molec_ctr_coords):
160
                if algo == 'euler':
161
                    surf_ads_list.append(ads_euler(conf, surf, site, molec_ctr,
162
                                                   num_pts, norm_vect,
163
                                                   molec_neigh_coords[i]))
164
                elif algo == 'chemcat':
165
                    surf_ads_list.append(ads_chemcat(site, molec_ctr, num_pts))
166
    return surf_ads_list
167

    
168

    
169
def run_screening(inp_vars):
170
    """Carry out the screening of adsorbate coordinates on a surface
171

172
    @param inp_vars: Calculation parameters from input file.
173
    """
174
    import os
175
    from modules.formats import read_coords, read_energies, \
176
        rdkit_mol_to_ase_atoms, adapt_format
177
    from modules.clustering import get_rmsd, clustering
178
    from modules.isolated import get_moments_of_inertia
179
    from modules.calculation import run_calc
180

    
181
    if not os.path.isdir("isolated"):
182
        err = "'isolated' directory not found. It is needed in order to carry "
183
        "out the screening of structures to be adsorbed"
184
        logger.error(err)
185
        raise ValueError(err)
186

    
187
    conf_list = read_coords(inp_vars['code'], 'isolated', 'rdkit')
188
    # TODO Implement neighbors algorithm
189
    # neigh_list = get_neighbors(conf_list[0], inp_vars['molec_ads_ctrs'])
190
    conf_enrgs = read_energies(inp_vars['code'], 'isolated')
191
    mois = np.array([get_moments_of_inertia(conf)[0] for conf in conf_list])
192
    rmsd_mtx = get_rmsd(conf_list)
193
    exemplars = clustering(rmsd_mtx)
194
    conf_list = [conf_list[idx] for idx in exemplars]
195
    conf_list = [rdkit_mol_to_ase_atoms(conf) for conf in conf_list]
196
    surf = adapt_format('ase', inp_vars['surf_file'])
197
    surf_ads_list = adsorb_confs(conf_list, surf, inp_vars['molec_ads_ctrs'],
198
                                 inp_vars['sites'], inp_vars['ads_algo'],
199
                                 inp_vars['sample_points_per_angle'],
200
                                 inp_vars['molec_neigh_ctrs'],
201
                                 inp_vars['surf_norm_vect'])
202
    run_calc('screening', inp_vars, surf_ads_list)