-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPd_cluster.py
1900 lines (1569 loc) · 77.1 KB
/
Pd_cluster.py
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import numpy as np
import matplotlib
from scipy.spatial import Delaunay
matplotlib.use("agg")
import torch
import matplotlib.pyplot as plt
import ase
from ase import Atom
from ase.io.lasp_PdO import write_arc, read_arc
import os
from copy import deepcopy
import json
import itertools
from ase.units import Hartree
from ase.build import fcc100, add_adsorbate
from ase.visualize import view
from ase.visualize.plot import plot_atoms
from ase.optimize.bfgslinesearch import BFGSLineSearch
from ase.calculators.lasp_PdO import LASP
from ase.constraints import FixAtoms
from ase.calculators.emt import EMT
from ase import Atoms
from ase.io import read, write
from ase.optimize import QuasiNewton
import gym
import math
import copy
from gym import spaces
from ase.md.langevin import Langevin
from ase import units
from math import cos, sin
import random
from random import sample
from ase.geometry.analysis import Analysis
from ase.cluster.wulff import wulff_construction
# from slab import images
'''
Actions:
Type: Discrete(8)
Num Action
0 ADS
1 Translation
2 R_Rotation
3 L_Rotation
4 Min
5 Diffusion
6 Drill
7 Dissociation
'''
surfaces = [(1, 0, 0),(1, 1, 0), (1, 1, 1)]
esurf = [1.0, 1.0, 1.0] # Surface energies.
lc = 3.89
size = 38 # Number of atoms
atoms = wulff_construction('Pd', surfaces, esurf,
size, 'fcc',
rounding='closest', latticeconstant=lc)
# slab = images[0]
DIRECTION = [
np.array([1, 0, 0]),
np.array([-1, 0, 0]),
np.array([0, 1, 0]),
np.array([0, -1, 0]),
np.array([0, 0, 1]),
np.array([0, 0, -1]),
]
# 设定动作空间
ACTION_SPACES = ['ADS', 'Translation', 'R_Rotation', 'L_Rotation', 'MD', 'Diffusion', 'Drill', 'Dissociation', 'Desportion']
# TODO:
'''
3.add "LAT_TRANS" part into step(considered in the cluster situation)
'''
# 创建MCT环境
class MCTEnv(gym.Env):
metadata = {"render.modes": ["rgb_array"]}
def __init__(self,
save_dir=None,
timesteps=None,
temperature=473,
k=8.6173324e-05,
max_episodes=None,
step_size=0.1,
max_energy_profile = 0.5,
convergence = 0.005,
save_every=None,
save_every_min=None,
plot_every=None,
reaction_H = None, #/(KJ/mol)
reaction_n = None,
delta_s = None, #/eV
use_DESW = None):
self.initial_state = atoms.copy() # 设定初始结构
self.to_constraint(self.initial_state)
self.initial_state, self.energy, self.force = self.lasp_calc(self.initial_state) # 由于使用lasp计算,设定初始能量
self.episode = 0 # 初始化episode为0
self.max_episodes = max_episodes
self.save_every = save_every
self.save_every_min = save_every_min
self.plot_every = plot_every
self.use_DESW = use_DESW
self.step_size = step_size # 设定单个原子一次能移动的距离
self.timesteps = timesteps # 定义episode的时间步上限
# self.episode_reward = 0 # 初始化一轮epsiode所获得的奖励
self.timestep = 0 # 初始化时间步数为0
# self.H = 112690 * 32/ 96485 # 没有加入熵校正, 单位eV
self.reaction_H = reaction_H
self.reaction_n = reaction_n
self.delta_s = delta_s
self.H = self.reaction_H * self.reaction_n
self.max_energy_profile = max_energy_profile
self.range = [0.9, 1.1]
self.reward_threshold = 0
# 保存history,plots,trajs,opt
if not os.path.exists(save_dir):
os.makedirs(save_dir)
self.history_dir = os.path.join(save_dir, 'history')
self.plot_dir = os.path.join(save_dir, 'plots')
if not os.path.exists(self.history_dir):
os.makedirs(self.history_dir)
if not os.path.exists(self.plot_dir):
os.makedirs(self.plot_dir)
# 初始化history字典
self.history = {}
# 记录不同吸附态(Pd64O,Pd64O2......Pd64O16)时的能量以及结构
self.adsorb_history = {}
# 标记可以自由移动的原子
# self.free_atoms = list(set(range(len(self.initial_state))) - set(bottomList))
# self.len_atom = len(self.free_atoms)
self.convergence = convergence
# 设定环境温度为473 K,定义热力学能
# T = 473.15
self.temperature_K = temperature
self.k = k # eV/K
self.thermal_energy = k * temperature * self.len_atom
self.action_space = spaces.Dict({'action_type': spaces.Discrete(len(ACTION_SPACES)),
'facet_selection': spaces.Discrete(len(atoms.get_surfaces()))})
# 设定动作空间,‘action_type’为action_space中的独立动作,atom_selection为三层Pd layer和环境中的16个氧
# movement设定为单个原子在空间中的运动(x,y,z)
# 定义动作空间
self.observation_space = self.get_observation_space()
# 一轮过后重新回到初始状态
self.reset()
return
def step(self, action):
pro = 1 # 定义该step完成该动作的概率,初始化为1
barrier = 0
self.steps = 50 # 定义优化的最大步长
reward = 0 # 定义初始奖励为0
diffusable = 1
self.action_idx = action['action_type']
RMSD_similar = False
kickout = False
RMSE = 10
self.done = False # 开关,决定episode是否结束
done_similar = False
episode_over = False # 与done作用类似
self.atoms, previous_structure, previous_energy = self.state
# 定义表层、次表层、深层以及环境层的平动范围
self.lamada_d = 0.2
self.lamada_s = 0.4
self.lamada_layer = 0.6
self.lamada_env = 0
surfList = []
for facet in atoms.get_surfaces():
atoms= self.cluster_rotation(atoms, facet)
list = self.get_surf_atoms(atoms)
for i in list:
surfList.append(i)
atoms = self.recover_rotation(atoms, facet)
surfList = [i for n, i in enumerate(surfList) if i not in surfList[:n]]
constraint = FixAtoms(mask=[a.symbol != 'O' and a.index not in surfList for a in atoms])
assert self.action_space.contains(self.action_idx), "%r (%s) invalid" % (
self.action_idx,
type(self.action_idx),
)
if action in [0, 2, 3, 5, 6]:
self.facet_selection = action['facet_selection']
self.cluster_rotation(self.atoms, self.facet_selection)
self.muti_movement = np.array([np.random.normal(0.25,0.25), np.random.normal(0.25,0.25), np.random.normal(0.25,0.25)])
# 定义层之间的平动弛豫
# 定义保存ts,min和md动作时的文件路径
save_path_ts = None
save_path_ads = None
save_path_md = None
# env_list = self.label_atoms(self.atoms, [2.0- fluct_d_layer, 2.0 + fluct_d_layer]) # 判断整个slab中是否还存在氧气分子,若不存在且动作依旧执行吸附,则强制停止
_, ads_exist = self.to_ads_adsorbate(self.atoms)
if not ads_exist and action == 0:
# self.done = True
self.action_idx = 1
layerList = self.get_layer_atoms(self.atoms)
layer_O = []
for i in layerList:
if self.atoms[i].symbol == 'O':
layer_O.append(i)
surfList = []
for facet in atoms.get_surfaces():
atoms= self.cluster_rotation(atoms, facet)
list = self.get_surf_atoms(atoms)
for i in list:
surfList.append(i)
atoms = self.recover_rotation(atoms, facet)
surfList = [i for n, i in enumerate(surfList) if i not in surfList[:n]]
constraint = FixAtoms(mask=[a.symbol != 'O' and a.index not in surfList for a in atoms])
subList = self.get_sub_atoms(self.atoms)
sub_O = []
for i in subList:
if self.atoms[i].symbol == 'O':
sub_O.append(i)
if not bool(layer_O) and self.action_idx == 6:
self.action_idx = 1
'''——————————————————————————————————————————以下是动作选择————————————————————————————————————————————————————————'''
if self.action_idx == 0:
self.atoms = self.choose_ads_site(self.atoms, self.total_s)
# return new_state,new_state_energy
elif self.action_idx == 1:
initial_positions = self.atoms.positions
for atom in initial_positions:
if atom in self.deep_atom:
atom += self.lamada_d * self.muti_movement
if atom in self.sub_atom:
atom += self.lamada_s * self.muti_movement
if atom in self.surf_atom:
atom += self.lamada_layer * self.muti_movement
if atom in self.layer_atom:
atom += self.lamada_layer * self.muti_movement
self.atoms.positions = initial_positions
elif self.action_idx == 2:
self._to_rotation(self.atoms, 9)
elif self.action_idx == 3:
self._to_rotation(self.atoms, -9)
elif self.action_idx == 4:
self.atoms.set_constraint(constraint)
self.atoms.calc = EMT()
dyn = Langevin(self.atoms, 5 * units.fs, self.temperature_K * units.kB, 0.002, trajectory=save_path_md,
logfile='MD.log')
dyn.run(self.steps)
'''------------The above actions are muti-actions and the following actions contain single-atom actions--------------------------------'''
elif self.action_idx == 5: # 表面上氧原子的扩散,单原子行为
self.atoms, diffusable = self.to_diffuse_oxygen(self.atoms, self.total_s)
elif self.action_idx == 6: # 表面晶胞的扩大以及氧原子的钻洞,多原子行为+单原子行为
selected_drill_O_list = []
layer_O_atom_list = self.layer_O_atom_list(self.atoms)
sub_O_atom_list = self.sub_O_atom_list(self.atoms)
if layer_O_atom_list:
for i in layer_O_atom_list:
selected_drill_O_list.append(i)
if sub_O_atom_list:
for j in sub_O_atom_list:
selected_drill_O_list.append(j)
if selected_drill_O_list:
selected_O = selected_drill_O_list[np.random.randint(len(selected_drill_O_list))]
self.atoms = self.to_expand_lattice(self.atoms, 1.25, 1.25, 1.1)
if selected_O in layer_O:
self.atoms = self.to_drill_surf(self.atoms)
elif selected_O in sub_O:
self.atoms = self.to_drill_deep(self.atoms)
self.to_constraint(self.atoms)
self.atoms, _, _ = self.lasp_calc(self.atoms)
self.atoms = self.to_expand_lattice(self.atoms, 0.8, 0.8, 10/11)
else:
reward -= 1
elif self.action_idx == 7: # 氧气解离
self.atoms = self.O_dissociation(self.atoms)
elif self.action_idx == 8:
_, desorblist = self.to_desorb_adsorbate(self.atoms)
if desorblist:
self.atoms = self.choose_ads_to_desorb(self.atoms)
else:
reward -= 1
else:
print('No such action')
self.timestep += 1
if action in [0, 2, 3, 5, 6]:
self.recover_rotation(self.atoms, self.facet_selection)
self.to_constraint(self.atoms)
# 优化该state的末态结构以及next_state的初态结构
self.atoms, current_energy, current_force = self.lasp_calc(self.atoms)
previous_atom = self.trajectories[-1]
# kickout the structure if too similar
if self.RMSD(self.atoms, previous_atom)[0] and (current_energy - previous_energy) > 0:
self.atoms = previous_atom
current_energy = previous_energy
RMSD_similar = True
if self.timestep > 3:
if self.RMSD(self.atoms, self.trajectories[-2])[0] and (current_energy - self.history['energies'][-2]) > 0:
self.atoms = previous_atom
current_energy = previous_energy
RMSD_similar = True
reward -= 1
if self.timestep > 21:
if self.RMSD(self.atoms, self.trajectories[-20])[0] and (current_energy - self.history['energies'][-20]) > 0:
self.atoms = previous_atom
current_energy = previous_energy
RMSD_similar = True
reward -= 1
if RMSD_similar:
kickout = True
if self.to_get_bond_info(self.atoms): # 如果结构过差,将结构kickout
self.atoms = previous_atom
current_energy = previous_energy
kickout = True
# current_force = self.history['forces'][-1]
reward += -5
if self.action_idx == 0:
current_energy = current_energy - self.delta_s
self.adsorb_history['traj'] = self.adsorb_history['traj'] + [self.atoms.copy()]
self.adsorb_history['structure'] = self.adsorb_history['structure'] + [self.atoms.get_positions()]
self.adsorb_history['energy'] = self.adsorb_history['energy'] + [current_energy - previous_energy]
self.adsorb_history['timesteps'].append(self.history['timesteps'][-1] + 1)
if self.action_idx == 8:
current_energy = current_energy + self.delta_s
relative_energy = current_energy - previous_energy
if relative_energy > 5:
reward += -1
else:
# reward += math.tanh(-relative_energy/(self.H * 8.314 * self.temperature_K)) * (math.pow(10.0, 5))
reward += self.get_reward_sigmoid(relative_energy)
if relative_energy >= 0:
reward -= 0.5
self.RMSD_list.append(self.RMSD(self.atoms, previous_atom)[1])
if self.timestep > 6:
current_action_list = self.history['actions'][-5:]
result = all(x == current_action_list[0] for x in current_action_list)
if result and self.action_idx == current_action_list[0] and (RMSD_similar and relative_energy >= 0):
self.repeat_action += 1
reward -= self.repeat_action * 1
elif result and self.action_idx != current_action_list[0]:
self.repeat_action = 0
if self.action_idx in [1,2,3,5,6,7]:
barrier = self.check_TS(previous_atom, self.atoms, previous_energy, current_energy, self.action_idx) # according to Boltzmann probablity distribution
if barrier > 5:
reward += -5.0 / (self.reaction_n * self.k * self.temperature_K)
barrier = 5.0
else:
# reward += math.tanh(-relative_energy /(self.H * 8.314 * self.temperature_K)) * (math.pow(10.0, 5))
reward += -relative_energy / (self.reaction_n * self.k * self.temperature_K)
current_structure = self.atoms.get_positions()
self.energy = current_energy
self.force = current_force
observation = self.get_obs() # 能观察到该state的结构与能量信息
self.state = self.atoms, current_structure, current_energy
# Update the history for the rendering
self.history, self.trajectories = self.update_history(self.action_idx, kickout)
'''sub_Pd_list = []
sub_list = self.label_atoms(self.atoms, [sub_z - fluct_d_Pd, sub_z + fluct_d_Pd])
for i in self.atoms:
if i.index in sub_list and i.symbol == 'Pd':
sub_Pd_list.append(i.index)
if len(sub_Pd_list) > 25:
reward -= (len(sub_Pd_list) - 25) * 5
else:
reward += 5'''
env_Pd_list = []
env_list = self.label_atoms(self.atoms, [23.33, 25.83])
for i in self.atoms: #查找是否Pd原子游离在环境中
if i.index in env_list and i.symbol == 'Pd':
env_Pd_list.append(i.index)
exist_too_short_bonds = self.exist_too_short_bonds(self.atoms)
if exist_too_short_bonds or env_Pd_list or self.energy - self.initial_energy > 4 or relative_energy > self.max_RE:
# reward += self.get_reward_sigmoid(1) * (self.timesteps - self.history['timesteps'][-1])
reward -= 0.5 * self.timesteps
self.done = True
elif self.timestep > 11:
if self.atoms == self.trajectories[-10]:
self.done = True
reward -= 0.5 * self.timesteps
if -1.5 * relative_energy > self.max_RE:
self.max_RE = -1.5 * relative_energy
if len(self.history['actions']) - 1 >= self.total_steps: # 当步数大于时间步,停止,且防止agent一直选取扩散或者平动动作
self.done = True
'''Pd_z = []
O_z = []
for i in range(len(self.atoms)):
if self.atoms[i].symbol == 'Pd':
Pd_z.append(self.atoms.positions[i][2])
if self.atoms[i].symbol == 'O':
O_z.append(self.atoms.positions[i][2])
highest_Pd_z = max(Pd_z)
highest_O_z = max(O_z)
lowest_O_z = min(O_z)
ana = Analysis(self.atoms)
OObonds = ana.get_bonds('O', 'O', unique = True)
if not OObonds[0]: # 若表层以及次表层的氧都以氧原子的形式存在,加分
if highest_O_z < highest_Pd_z and lowest_O_z > 12.0:
reward += 50'''
# reward -= 0.5 # 每经历一步timesteps,扣一分
# _, exist = self.to_ads_adsorbate(self.atoms)
if len(self.history['real_energies']) > 31:
RMSE = self.RMSE(self.history['real_energies'][-30:])
if RMSE < 1.0:
done_similar = True
if (((current_energy - self.initial_energy) <= -0.95 * self.H and (current_energy - self.initial_energy) >= -1.1 * self.H) and (abs(current_energy - previous_energy) < self.min_RE_d and abs(current_energy - previous_energy) > 0.0001)) or (((current_energy - self.initial_energy) <= -0.9 * self.H and (current_energy - self.initial_energy) >= -1.2 * self.H) and done_similar): # 当氧气全部被吸附到Pd表面,且两次相隔的能量差小于一定阈值,达到终止条件
# if abs(current_energy - previous_energy) < self.min_RE_d and abs(current_energy - previous_energy) > 0.001:
self.done = True
reward -= (self.energy - self.initial_energy)/(self.H * self.k * self.temperature_K)
# self.min_RE_d = abs(current_energy - previous_energy)
self.history['reward'] = self.history['reward'] + [reward]
self.episode_reward += reward
if self.episode_reward <= self.reward_threshold: # 设置惩罚下限
self.done = True
if self.done:
episode_over = True
self.episode += 1
if self.episode % self.save_every == 0:
self.save_episode()
self.plot_episode()
return observation, reward, episode_over, [done_similar]
def save_episode(self):
save_path = os.path.join(self.history_dir, '%d.npz' % self.episode)
np.savez_compressed(
save_path,
traj = self.trajectories,
initial_energy=self.initial_energy,
energies=self.history['energies'],
actions=self.history['actions'],
structures=self.history['structures'],
timesteps=self.history['timesteps'],
forces = self.history['forces'],
reward = self.history['reward'],
adsorb_traj=self.adsorb_history['traj'],
adsorb_structure=self.adsorb_history['structure'],
adsorb_energy=self.adsorb_history['energy'],
adsorb_timesteps = self.adsorb_history['timesteps'],
ts_energy = self.TS['energies'],
ts_timesteps = self.TS['timesteps'],
episode_reward = self.episode_reward,
)
return
def plot_episode(self):
save_path = os.path.join(self.plot_dir, '%d.png' % self.episode)
energies = np.array(self.history['energies'])
actions = np.array(self.history['actions'])
plt.figure(figsize=(30, 30))
plt.xticks(fontsize=12, fontfamily='Arial', fontweight='bold')
plt.yticks(fontsize=12, fontfamily='Arial', fontweight='bold')
# plt.title('Epi_{}'.format(620 + episode), fontsize=28, fontweight='bold', fontfamily='Arial')
plt.xlabel('steps(fs)', fontsize=18, fontweight='bold', fontstyle='italic', fontfamily='Arial')
plt.ylabel('Energies(eV)', fontsize=18, fontweight='bold', fontstyle='italic', fontfamily='Arial')
plt.plot(energies, color='blue')
for action_index in range(len(ACTION_SPACES)):
action_time = np.where(actions == action_index)[0]
plt.plot(action_time, energies[action_time], 'o',
label=ACTION_SPACES[action_index])
plt.scatter(self.TS['timesteps'], self.TS['energies'], label='TS', marker='x', color='g', s=180)
plt.scatter(self.adsorb_history['timesteps'], self.adsorb_history['energy'], label='ADS', marker='p', color='black', s=180)
plt.legend(loc='upper left')
plt.savefig(save_path, bbox_inches='tight')
return plt.close('all')
def reset(self):
if os.path.exists('input.arc'):
os.remove('input.arc')
if os.path.exists('all.arc'):
os.remove('all.arc')
if os.path.exists('sella.log'):
os.remove('sella.log')
self.atoms = atoms.copy()
self.to_constraint(self.atoms)
self.atoms, self.initial_energy, self.initial_force= self.lasp_calc(self.atoms)
self.action_idx = 0
self.episode_reward = 0.5 * self.timesteps
self.timestep = 0
self.total_steps = self.timesteps
self.max_RE = 3
self.min_RE_d = self.convergence * self.len_atom
self.repeat_action = 0
self.n_O2 = 2000
self.n_O3 = 0
self.ads_list = []
for _ in range(self.n_O2):
self.ads_list.append(2)
self.atoms = self.choose_ads_site(self.atoms)
self.trajectories = []
self.RMSD_list = []
self.trajectories.append(self.atoms.copy())
self.TS = {}
# self.TS['structures'] = [slab.get_scaled_positions()[self.free_atoms, :]]
self.TS['energies'] = [0.0]
self.TS['timesteps'] = [0]
self.adsorb_history = {}
self.adsorb_history['traj'] = [atoms]
self.adsorb_history['structure'] = [atoms.get_scaled_positions()[self.free_atoms, :].flatten()]
self.adsorb_history['energy'] = [0.0]
self.adsorb_history['timesteps'] = [0]
results = ['energies', 'actions', 'structures', 'timesteps', 'forces', 'scaled_structures', 'real_energies', 'reward']
for item in results:
self.history[item] = []
self.history['energies'] = [0.0]
self.history['real_energies'] = [0.0]
self.history['actions'] = [0]
self.history['forces'] = [self.initial_force]
self.history['structures'] = [atoms.get_positions().flatten()]
self.history['scaled_structures'] = [atoms.get_scaled_positions()[self.free_atoms, :].flatten()]
self.history['timesteps'] = [0]
self.history['reward'] = []
self.state = self.atoms, self.atoms.positions, self.initial_energy
observation = self.get_obs()
return observation
def render(self, mode='rgb_array'):
if mode == 'rgb_array':
# return an rgb array representing the picture of the atoms
# Plot the atoms
fig, ax1 = plt.subplots()
plot_atoms(self.atoms.get_scaled_positions(),
ax1,
rotation='48x,-51y,-144z',
show_unit_cell=0)
ax1.set_ylim([-1, 2])
ax1.set_xlim([-1, 2])
ax1.axis('off')
ax2 = fig.add_axes([0.35, 0.85, 0.3, 0.1])
# Add a subplot for the energy history overlay
ax2.plot(self.history['timesteps'],
self.history['energies'])
if len(self.TS['timesteps']) > 0:
ax2.plot(self.TS['timesteps'],
self.TS['energies'], 'o', color='g')
ax2.set_ylabel('Energy [eV]')
# Render the canvas to rgb values for the gym render
plt.draw()
renderer = fig.canvas.get_renderer()
x = renderer.buffer_rgba()
img_array = np.frombuffer(x, np.uint8).reshape(x.shape)
plt.close()
# return the rendered array (but not the alpha channel)
return img_array[:, :, :3]
else:
return
def close(self):
return
def get_observation_space(self):
observation_space = spaces.Dict({'structures':
spaces.Box(
low=-1,
high=2,
shape=(self.len_atom * 3, ),
dtype=float
),
'energy': spaces.Box(
low=-50.0,
high=5.0,
shape=(1,),
dtype=float
),
'force':spaces.Box(
low=-2,
high=2,
shape=(self.len_atom * 3, ),
dtype=float
),
'TS': spaces.Box(low = -0.5,
high = 1.5,
shape = (1,),
dtype=float),
})
return observation_space
def get_obs(self):
observation = {}
observation['structure'] = self.atoms.get_scaled_positions()[self.free_atoms, :].flatten()
observation['energy'] = np.array([self.energy - self.initial_energy]).reshape(1, )
observation['force'] = self.force[self.free_atoms, :].flatten()
return observation['structure']
def update_history(self, action_idx, kickout):
self.trajectories.append(self.atoms.copy())
self.history['timesteps'] = self.history['timesteps'] + [self.history['timesteps'][-1] + 1]
self.history['energies'] = self.history['energies'] + [self.energy - self.initial_energy]
self.history['forces'] = self.history['forces'] + [self.force]
self.history['actions'] = self.history['actions'] + [action_idx]
self.history['structures'] = self.history['structures'] + [self.atoms.get_positions().flatten()]
self.history['scaled_structures'] = self.history['scaled_structures'] + [self.atoms.get_scaled_positions()[self.free_atoms, :].flatten()]
if not kickout:
self.history['real_energies'] = self.history['real_energies'] + [self.energy - self.initial_energy]
return self.history, self.trajectories
def transition_state_search(self, previous_atom, current_atom, previous_energy, current_energy, action):
layerlist = self.label_atoms(previous_atom, [16.0, 21.0])
layer_O = []
for i in layerlist:
if previous_atom[i].symbol == 'O':
layer_O.append(i)
if self.use_DESW:
self.to_constraint(previous_atom)
write_arc([previous_atom])
write_arc([previous_atom, current_atom])
previous_atom.calc = LASP(task='TS', pot='PdO', potential='NN D3')
if previous_atom.get_potential_energy() == 0: #没有搜索到过渡态
ts_energy = previous_energy
else:
# ts_atom = read_arc('TSstr.arc',index = -1)
barrier, ts_energy = previous_atom.get_potential_energy()
# barrier = ts_energy - previous_energy
else:
if action == 1:
if current_energy - previous_energy < -1.0:
barrier = 0
elif current_energy - previous_energy >= -1.0 and current_energy - previous_energy <= 1.0:
barrier = np.random.normal(2, 2/3)
else:
barrier = 4.0
if action == 2 or action == 3:
barrier = math.log(1 + pow(math.e, current_energy-previous_energy), 10)
if action == 5:
barrier = math.log(0.5 + 1.5 * pow(math.e, 2 *(current_energy - previous_energy)), 10)
elif action == 6:
barrier = 0.93 * pow(math.e, 0.615 * (current_energy - previous_energy)) - 0.16
elif action == 7:
barrier = 0.65 + 0.84 * (current_energy - previous_energy)
else:
barrier = 1.5
ts_energy = previous_energy + barrier
return barrier, ts_energy
def check_TS(self, previous_atom, current_atom, previous_energy, current_energy, action):
barrier, ts_energy = self.transition_state_search(previous_atom, current_atom, previous_energy, current_energy, action)
self.record_TS(ts_energy)
# pro = math.exp(-barrier / self.k * self.temperature_K)
return barrier
def record_TS(self, ts_energy):
self.TS['energies'].append(ts_energy - self.initial_energy)
self.TS['timesteps'].append(self.history['timesteps'][-1] + 1)
return
def choose_ads_site(self, state):
new_state = state.copy()
surf_sites = self.get_surf_sites(state)
layerList = self.get_layer_atoms(new_state)
add_total_sites = []
layer_O = []
for ads_sites in surf_sites:
for i in layerList:
if state[i].symbol == 'O':
layer_O.append(i)
to_other_O_distance = []
if layer_O:
for i in layer_O:
distance = self.distance(ads_sites[0], ads_sites[1], ads_sites[2] + 1.3, state.get_positions()[i][0],
state.get_positions()[i][1], state.get_positions()[i][2])
to_other_O_distance.append(distance)
if min(to_other_O_distance) > 2 * d_O_O:
ads_sites[4] = 1
else:
ads_sites[4] = 1
if ads_sites[4]:
add_total_sites.append(ads_sites)
if add_total_sites:
ads_site = add_total_sites[np.random.randint(len(add_total_sites))]
new_state = state.copy()
# ads, _ = self.to_ads_adsorbate(new_state)
choosed_adsorbate = np.random.randint(len(self.ads_list))
ads = self.ads_list[choosed_adsorbate]
del self.ads_list[choosed_adsorbate]
# delenvlist = [0, 1]
# del env_s[[i for i in range(len(env_s)) if i in delenvlist]]
if len(ads):
if len(ads) == 2:
self.n_O2 -= 1
O1 = Atom('O', (ads_site[0], ads_site[1], ads_site[2] + 1.3))
O2 = Atom('O', (ads_site[0], ads_site[1], ads_site[2] + 2.51))
new_state = new_state + O1
new_state = new_state + O2
# ads = O1 + O2
elif len(ads) == 3:
self.n_O3 -= 1
O1 = Atom('O', (ads_site[0], ads_site[1], ads_site[2] + 1.3))
O2 = Atom('O', (ads_site[0], ads_site[1] + 1.09, ads_site[2] + 1.97))
O3 = Atom('O', (ads_site[0], ads_site[1] - 1.09, ads_site[2] + 1.97))
new_state = new_state + O1
new_state = new_state + O2
new_state = new_state + O3
return new_state
def choose_ads_to_desorb(self, state):
new_state = state.copy()
# add_total_sites = []
layer_O = []
O_position = []
desorblist = []
layerList = self.label_atoms(state, [16.0, 18.0])
for i in layerList:
if state[i].symbol == 'O':
layer_O.append(i)
if layer_O:
desorb, _ = self.to_desorb_adsorbate(new_state)
if len(desorb):
if len(desorb) == 2:
self.ads_list.append(2)
desorblist.append(desorb[0])
desorblist.append(desorb[1])
elif len(desorb) == 3:
self.ads_list.append(3)
desorblist.append(desorb[0])
desorblist.append(desorb[1])
desorblist.append(desorb[2])
for i in desorblist:
O_position.append(state.get_positions()[i][0])
O_position.append(state.get_positions()[i][1])
O_position.append(state.get_positions()[i][2])
del new_state[[i for i in range(len(new_state)) if i in desorblist]]
if len(desorb):
if len(desorb) == 2:
self.n_O2 += 1
O1 = Atom('O', (O_position[0], O_position[1], O_position[2] + 4.0))
O2 = Atom('O', (O_position[3], O_position[4], O_position[5] + 4.0))
new_state = new_state + O1
new_state = new_state + O2
# ads = O1 + O2
elif len(desorb) == 3:
self.n_O3 += 1
O1 = Atom('O', (O_position[0], O_position[1], O_position[2] + 4.0))
O2 = Atom('O', (O_position[3], O_position[4], O_position[5] + 4.0))
O3 = Atom('O', (O_position[6], O_position[7], O_position[8] + 4.0))
new_state = new_state + O1
new_state = new_state + O2
new_state = new_state + O3
return new_state
def _to_rotation(self, atoms, zeta):
initial_state = atoms.copy()
zeta = math.pi * zeta / 180
matrix = [[cos(zeta), -sin(zeta), 0],
[sin(zeta), cos(zeta), 0],
[0, 0, 1]]
matrix = np.array(matrix)
rotation_list = []
surf_list = self.get_surf_atoms(atoms)
layer_list = self.get_layer_atoms(atoms)
for i in surf_list:
rotation_list.append(i)
for j in layer_list:
rotation_list.append(j)
rotation_list = [i for n, i in enumerate(rotation_list) if i not in rotation_list[:n]]
central_point = self.mid_point(atoms, surf_list)
for atom in initial_state.positions:
if atom.index in rotation_list:
atom += np.array(
(np.dot(matrix, (np.array(atom.tolist()) - central_point).T).T + central_point).tolist()) - atom
atoms.positions = initial_state.get_positions()
def to_diffuse_oxygen(self, slab, facet):
layer_O = []
to_diffuse_O_list = []
diffuse_sites = []
layer_List = self.get_layer_atoms(slab)
neigh_facet = self.neighbour_facet(slab, facet)
for i in neigh_facet:
new_state = self.cluster_rotation(new_state, i)
list = self.get_surf_atoms(new_state)
sites = self.get_surf_sites(atoms,list)
for site in sites:
diffuse_sites.append(site.tolist())
new_state = self.recover_rotation(new_state, i)
diffuse_sites = np.array(diffuse_sites)
diffusable_sites = []
interference_O_distance = []
diffusable = True
for i in slab:
if i.index in layer_List and i.symbol == 'O':
layer_O.append(i.index)
for ads_sites in diffuse_sites: # 寻找可以diffuse的位点
to_other_O_distance = []
if layer_O:
for i in layer_O:
distance = self.distance(ads_sites[0], ads_sites[1], ads_sites[2] + 1.5, slab.get_positions()[i][0],
slab.get_positions()[i][1], slab.get_positions()[i][2])
to_other_O_distance.append(distance)
if min(to_other_O_distance) > 1.5 * d_O_O:
ads_sites[4] = 1
else:
ads_sites[4] = 0
else:
ads_sites[4] = 1
if ads_sites[4]:
diffusable_sites.append(ads_sites)
if layer_O: # 防止氧原子被trap住无法diffuse
for i in layer_O:
to_other_O_distance = []
for j in layer_O:
if j != i:
distance = self.distance(slab.get_positions()[i][0],
slab.get_positions()[i][1], slab.get_positions()[i][2],slab.get_positions()[j][0],
slab.get_positions()[j][1], slab.get_positions()[j][2])
to_other_O_distance.append(distance)
if self.to_get_min_distances(to_other_O_distance,4):
d_min_4 = self.to_get_min_distances(to_other_O_distance, 4)
if d_min_4 > 2.0:
to_diffuse_O_list.append(i)
else:
to_diffuse_O_list.append(i)
if to_diffuse_O_list:
selected_O_index = layer_O[np.random.randint(len(to_diffuse_O_list))]
diffuse_site = diffusable_sites[np.random.randint(len(diffusable_sites))]
interference_O_list = [i for i in layer_O if i != selected_O_index]
for j in interference_O_list:
d = self.atom_to_traj_distance(slab.positions[selected_O_index], diffuse_site, slab.positions[j])
interference_O_distance.append(d)
if interference_O_distance:
if min(interference_O_distance) < 0.3 * d_O_O:
diffusable = False
if diffusable:
for atom in slab:
if atom.index == selected_O_index:
atom.position = np.array([diffuse_site[0], diffuse_site[1], diffuse_site[2] + 1.5])
# del slab[[j for j in range(len(slab)) if j == selected_O_index]]
# O = Atom('O', (diffuse_site[0], diffuse_site[1], diffuse_site[2] + 1.5))
# slab = slab + O
return slab, diffusable
def to_expand_lattice(self, slab, expand_layer, expand_surf, expand_lattice):
layerList = self.get_layer_atoms(slab)
surfList = self.get_surf_atoms(slab)
subList = self.get_sub_atoms(slab)
if layerList:
mid_point_layer = self.mid_point(slab, layerList)
else:
mid_point_layer = self.mid_point(slab,surfList)
mid_point_surf = self.mid_point(slab, surfList)
mid_point_sub = self.mid_point(slab, subList)
for i in slab:
slab.positions[i.index][0] = (slab.get_positions()[i.index][0] - mid_point_layer[0]) * expand_lattice + \
mid_point_layer[0]
slab.positions[i.index][1] = (slab.get_positions()[i.index][1] - mid_point_layer[1]) * expand_lattice + \
mid_point_layer[1]