basic_mutations.py 9.09 KB
Newer Older
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import numpy as np
from abc import ABC, abstractmethod
from ase.data import covalent_radii
from ase.geometry import get_distances

from ase.visualize import view

from candidate_operations.candidate_generation import OffspringOperation


def pos_add_sphere(rattle_strength):
    # Rattle within a sphere
    r = rattle_strength * np.random.rand()**(1/3)
    theta = np.random.uniform(low=0, high=2*np.pi)
    phi = np.random.uniform(low=0, high=np.pi)
    pos_add = r * np.array([np.cos(theta)*np.sin(phi),
                            np.sin(theta)*np.sin(phi),
                            np.cos(phi)])
    return pos_add

def pos_add_sphere_shell(rmin, rmax):
    # Rattle within a sphere
    r = np.random.uniform(rmin**3, rmax**3)**(1/3)
    theta = np.random.uniform(low=0, high=2*np.pi)
    phi = np.random.uniform(low=0, high=np.pi)
    pos_add = r * np.array([np.cos(theta)*np.sin(phi),
                            np.sin(theta)*np.sin(phi),
                            np.cos(phi)])
    return pos_add

class RattleMutation(OffspringOperation):
    """Class to perform rattle mutations on structures.
    
    Parameters:

    n_top: The number of atoms to optimize. Specifically the
    atoms with indices [-n_top:] are optimized.
    
    Nrattle: The average number of atoms to rattle.

    rattle_range: The maximum distance within witch to rattle the
    atoms. Atoms are rattled uniformly within a sphere of this
    radius.

    blmin: The minimum allowed distance between atoms in units of
    the covalent distance between atoms, where d_cov=r_cov_i+r_cov_j.
    
    blmax: The maximum allowed distance, in units of the covalent 
    distance, from a single isolated atom to the closest atom. If
    blmax=None, no constraint is enforced on isolated atoms.

    description: Name of the operation, which will be saved in
    info-dict of structures, on which the operation is applied.    
    """
    def __init__(self, n_top, Nrattle=3, rattle_range=3, blmin=0.7, blmax=1.3,
                 description='RattleMutation'):
        OffspringOperation.__init__(self, blmin=blmin, blmax=blmax)
        self.description = description
        self.n_top = n_top
        self.probability = Nrattle/n_top
        self.rattle_range = rattle_range

    def get_new_candidate(self, parents):
        a = parents[0]
        a = self.rattle(a)
        a = self.finalize(a)
        return a

    def rattle(self, atoms):
        """Standardized candidate generation method for all mutation
        and crossover operations.
        """
        a = atoms.copy()
        Natoms = len(a)
        Nslab = Natoms - self.n_top

        # Randomly select indices of atoms to permute - in random order.
        indices_to_rattle = np.arange(Nslab,Natoms)[np.random.rand(self.n_top)
                                                     < self.probability]
        indices_to_rattle = np.random.permutation(indices_to_rattle)
        if len(indices_to_rattle) == 0:
            indices_to_rattle = [np.random.randint(Nslab,Natoms)]

        # Perform rattle operations in sequence.
        for i in indices_to_rattle:
            for _ in range(100):
                posi_0 = np.copy(a.positions[i])
                
                # Perform rattle
                pos_add = pos_add_sphere(self.rattle_range)
                a.positions[i] += pos_add
                
                # Check if rattle was valid
                valid_bondlengths = self.check_valid_bondlengths(a)
                
                if not valid_bondlengths:
                    a.positions[i] = posi_0
                else:
                    break
        return a

class RattleMutation2(OffspringOperation):
    """Class to perform rattle mutations on structures.
    
    Parameters:

    n_top: The number of atoms to optimize. Specifically the
    atoms with indices [-n_top:] are optimized.
    
    Nrattle: The average number of atoms to rattle.

    blmin: The minimum allowed distance between atoms in units of
    the covalent distance between atoms, where d_cov=r_cov_i+r_cov_j.
    
    blmax: The maximum allowed distance, in units of the covalent 
    distance, from a single isolated atom to the closest atom. If
    blmax=None, no constraint is enforced on isolated atoms.

    description: Name of the operation, which will be saved in
    info-dict of structures, on which the operation is applied.    
    """
    def __init__(self, n_top, Nrattle=3, blmin=0.7, blmax=1.3,
                 description='RattleMutation'):
        OffspringOperation.__init__(self, blmin=blmin, blmax=blmax)
        self.description = description
        self.n_top = n_top
        self.probability = Nrattle/n_top

    def get_new_candidate(self, parents):
        """Standardized candidate generation method for all mutation
        and crossover operations.
        """
        a = parents[0]
        a = self.rattle(a)
        a = self.finalize(a)
        return a

    def rattle(self, atoms):
        a = atoms.copy()
        Natoms = len(a)
        Nslab = Natoms - self.n_top
        num = a.numbers

        # Randomly select indices of atoms to permute - in random order.
        indices_to_rattle = np.arange(Nslab,Natoms)[np.random.rand(self.n_top)
                                                     < self.probability]
        indices_to_rattle = np.random.permutation(indices_to_rattle)
        if len(indices_to_rattle) == 0:
            indices_to_rattle = [np.random.randint(Nslab,Natoms)]

        # Perform rattle operations in sequence.
        for i in indices_to_rattle:
            for _ in range(100):
                posi_0 = np.copy(a.positions[i])
                j = np.random.randint(Nslab,Natoms)

                # Perform rattle
                covalent_dist_ij = covalent_radii[num[i]] + covalent_radii[num[j]]
                rmin = self.blmin * covalent_dist_ij
                rmax = self.blmax * covalent_dist_ij
                pos_add = pos_add_sphere_shell(rmin, rmax)
                a.positions[i] = np.copy(a.positions[j]) + pos_add

                # Check if rattle was valid
                valid_bondlengths = self.check_valid_bondlengths(a)
                
                if not valid_bondlengths:
                    a.positions[i] = posi_0
                else:
                    break
        return a


class PermutationMutation(OffspringOperation):
    """Class to perform permutation mutations on structures.
    
    Parameters:

    n_top: The number of atoms to optimize. Specifically the
    atoms with indices [-n_top:] are optimized.
    
    Npermute: The average number of permutations to perform.
    
    blmin: The minimum allowed distance between atoms in units of
    the covalent distance between atoms, where d_cov=r_cov_i+r_cov_j.
    
    blmax: The maximum allowed distance, in units of the covalent 
    distance, from a single isolated atom to the closest atom. If
    blmax=None, no constraint is enforced on isolated atoms.
    
    description: Name of the operation, which will be saved in
    info-dict of structures, on which the operation is applied.
    """

    def __init__(self, n_top, Npermute=3, blmin=0.7, blmax=1.3,
                 description='PermutationMutation'):
        OffspringOperation.__init__(self, blmin=blmin, blmax=blmax)
        self.description = description
        self.n_top = n_top
        self.probability = Npermute/n_top

    def get_new_candidate(self, parents):
        """Standardized candidate generation method for all mutation
        and crossover operations.
        """
        a = parents[0]
        a = self.mutate(a)
        a = self.finalize(a)
        return a

    def mutate(self, atoms):
        a = atoms.copy()
        Natoms = len(a)
        Nslab = Natoms - self.n_top
        num = a.numbers

        # Check if permutation mutation is applicable to structure.
        num_unique_top = list(set(num[-self.n_top:]))
        assert len(num_unique_top) > 1, 'Permutations with one atomic type is not valid'

        # Randomly select indices of atoms to permute - in random order.
        indices_to_permute = np.arange(Nslab,Natoms)[np.random.rand(self.n_top)
                                                   < self.probability]
        indices_to_permute = np.random.permutation(indices_to_permute)
        if len(indices_to_permute) == 0:
            indices_to_permute = [np.random.randint(Nslab,Natoms)]

        # Perform permutations in sequence.
        for i_permute in indices_to_permute:
            for _ in range(100):
                j_permute = np.random.randint(Nslab,Natoms)
                while num[i_permute] == num[j_permute]:
                    j_permute = np.random.randint(Nslab,Natoms)

                # Permute
                pos_i = np.copy(a.positions[i_permute])
                pos_j = np.copy(a.positions[j_permute])
                a.positions[i_permute] = pos_j
                a.positions[j_permute] = pos_i

                # Check if rattle was valid
                valid_bondlengths = self.check_valid_bondlengths(a)
                
                if not valid_bondlengths:
                    a.positions[i_permute] = pos_i
                    a.positions[j_permute] = pos_j
                else:
                    break
        return a