-
Notifications
You must be signed in to change notification settings - Fork 17
/
polarizer
executable file
·847 lines (733 loc) · 32.3 KB
/
polarizer
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
#!/usr/bin/env python
# polarizer - add Drude oscillators to LAMMPS data file.
# Agilio Padua <[email protected]>
# Alain Dequidt <[email protected]>
# Kateryna Goloviznina <[email protected]>
# version 2023/11/02
import argparse
import random
from copy import deepcopy
usage = """
==============================================================================
Add Drude oscillators to LAMMPS data file.
------------------------------------------------------------------------------
Format of file containing specification of Drude oscillators (alpha.ff):
# type dm/u dq/e k/(kJ/molA2) alpha/A3 thole
C3H 0.4 -1.0 4184.0 1.016 2.6
...
* dm is the mass to place on the Drude particle (subtracted from its core)
* dq is the charge of the Drude particle, its sign determines if Drude particles
are negative or positive; dq may be computed from k and alpha
* k is the harmonic force constant of the bond between core and Drude, and may
be computed from qd and alpha
* alpha is the polarizability
* thole is a parameter of the Thole damping function
------------------------------------------------------------------------------
A Drude particle is created for each atom in the LAMMPS data file
that corresponds to an atom type given in the Drude file.
Since LAMMPS uses numbers for atom types in the data file, a comment
after each line in the Masses section has to be introduced to allow
identification of the atom types within the force field database:
Masses
1 12.011 # C3H
2 12.011 # CTO
...
This script will add new atom types, new bond types, new atoms and
new bonds to the data file.
It will also generate some commands to be included in the LAMMPS input script,
which are related to the topology and force field, namely fix drude,
pair_style and pair_coeff commands. For information on thermostating please
read the documentation of the USER-DRUDE package.
------------------------------------------------------------------------------
This tool can also be used to revert a Drude-polarized data file to a
non-polarizable one.
==============================================================================
"""
# keywords of header and main sections (from data.py in Pizza.py)
hkeywords = ["atoms", "ellipsoids", "lines", "triangles", "bodies",
"bonds", "angles", "dihedrals", "impropers",
"atom types", "bond types", "angle types", "dihedral types",
"improper types", "xlo xhi", "ylo yhi", "zlo zhi", "xy xz yz"]
skeywords = [["Masses", "atom types"],
["Pair Coeffs", "atom types"],
["Bond Coeffs", "bond types"], ["Angle Coeffs", "angle types"],
["Dihedral Coeffs", "dihedral types"],
["Improper Coeffs", "improper types"],
["BondBond Coeffs", "angle types"],
["BondAngle Coeffs", "angle types"],
["MiddleBondTorsion Coeffs", "dihedral types"],
["EndBondTorsion Coeffs", "dihedral types"],
["AngleTorsion Coeffs", "dihedral types"],
["AngleAngleTorsion Coeffs", "dihedral types"],
["BondBond13 Coeffs", "dihedral types"],
["AngleAngle Coeffs", "improper types"],
["Atoms", "atoms"], ["Velocities", "atoms"],
["Ellipsoids", "ellipsoids"],
["Lines", "lines"], ["Triangles", "triangles"],
["Bodies", "bodies"],
["Bonds", "bonds"],
["Angles", "angles"], ["Dihedrals", "dihedrals"],
["Impropers", "impropers"], ["Molecules", "atoms"]]
def massline(att):
return "{0:4d} {1:8.3f} # {2}\n".format(att['id'], att['m'], att['type'])
def bdtline(bdt):
return "{0:4d} {1:12.6f} {2:12.6f} {3}\n".format(bdt['id'], bdt['k'],
bdt['r0'], bdt['note'])
def atomline(at):
return "{0:7d} {1:7d} {2:4d} {3:10.6f} {4:13.6e} {5:13.6e} {6:13.6e} "\
" {7}\n".format(at['n'], at['mol'], at['id'], at['q'],
at['x'], at['y'], at['z'], at['note'])
def bondline(bd):
return "{0:7d} {1:4d} {2:7d} {3:7d} {4}\n".format(bd['n'], bd['id'],
bd['i'], bd['j'], bd['note'])
def velline(at):
return "{0:7d} {1:13.6e} {2:13.6e} {3:13.6e} \n".format(at['n'],
at['vx'], at['vy'], at['vz'])
# --------------------------------------
class Data(object):
def __init__(self, datafile):
'''read LAMMPS data file (from data.py in Pizza.py)'''
# for extract method
self.atomtypes = []
self.bondtypes = []
self.atoms = []
self.bonds = []
self.idmap = {}
self.nselect = 1
f = open(datafile, "r")
self.title = f.readline()
self.names = {}
headers = {}
while 1:
line = f.readline().strip()
if '#' in line:
line = line[:line.index('#')].strip()
if len(line) == 0:
continue
found = 0
for keyword in hkeywords:
if keyword in line:
found = 1
words = line.split()
if keyword == "xlo xhi" or keyword == "ylo yhi" or \
keyword == "zlo zhi":
headers[keyword] = (float(words[0]), float(words[1]))
elif keyword == "xy xz yz":
headers[keyword] = \
(float(words[0]), float(words[1]), float(words[2]))
else:
headers[keyword] = int(words[0])
if not found:
break
sections = {}
while 1:
if len(line) > 0:
found = 0
for pair in skeywords:
keyword, length = pair[0], pair[1]
if keyword == line:
found = 1
if length not in headers:
raise RuntimeError(f'data section {line} has no matching header value')
f.readline()
list_ = []
for _ in range(headers[length]):
list_.append(f.readline())
sections[keyword] = list_
if not found:
raise RuntimeError(f'invalid section {line} in data file')
#f.readline()
line = f.readline()
if not line:
break
if '#' in line:
line = line[:line.index('#')]
line = line.strip()
f.close()
self.headers = headers
self.sections = sections
def write(self, filename):
'''write out a LAMMPS data file (from data.py in Pizza.py)'''
with open(filename, "w") as f:
f.write(self.title + '\n')
for keyword in hkeywords:
if keyword in self.headers:
if keyword == "xlo xhi" or keyword == "ylo yhi" or \
keyword == "zlo zhi":
f.write("{0:f} {1:f} {2}\n".format(
self.headers[keyword][0],
self.headers[keyword][1], keyword))
elif keyword == "xy xz yz":
f.write("{0:f} {1:f} {2:f} {3}\n".format(
self.headers[keyword][0],
self.headers[keyword][1],
self.headers[keyword][2], keyword))
else:
f.write("{0:d} {1}\n".format(self.headers[keyword],
keyword))
for pair in skeywords:
keyword = pair[0]
if keyword in self.sections:
f.write(f'\n{keyword}\n\n')
for line in self.sections[keyword]:
f.write(line)
def extract_nonpol(self):
"""extract atom and bond info from nonpolarizable data"""
if len(self.atomtypes):
return
# extract atom IDs
missinglabels = False
for line in self.sections['Masses']:
tok = line.split()
if len(tok) < 4:
print(f'error: missing type for atom ID {tok[0]} in Masses section')
missinglabels = True
continue
atomtype = {}
atomtype['id'] = int(tok[0])
atomtype['m'] = float(tok[1])
atomtype['type'] = tok[3]
self.atomtypes.append(atomtype)
if missinglabels:
raise RuntimeError('missing atom labels')
# extract atom registers
for line in self.sections['Atoms']:
tok = line.split()
atom = {}
atom['n'] = int(tok[0])
atom['mol'] = int(tok[1])
atom['id'] = int(tok[2])
atom['q'] = float(tok[3])
atom['x'] = float(tok[4])
atom['y'] = float(tok[5])
atom['z'] = float(tok[6])
atom['note'] = ' '.join(tok[7:])
self.atoms.append(atom)
self.idmap[atom['n']] = atom
for line in self.sections['Bonds']:
tok = line.split()
bond = {}
bond['i'] = int(tok[2])
bond['j'] = int(tok[3])
bond['id'] = int(tok[1])
bond['note'] = ' '.join(tok[4:])
# identify atom types in bond
n_i = bond['i'] - 1
n_j = bond['j'] - 1
id_i = self.atoms[n_i]['id'] - 1
id_j = self.atoms[n_j]['id'] - 1
bond['itype'] = self.atomtypes[id_i]['type']
bond['jtype'] = self.atomtypes[id_j]['type']
self.bonds.append(bond)
if 'Velocities' in self.sections:
for line in self.sections['Velocities']:
tok = line.split()
atom = self.idmap[int(tok[0])]
atom['vx'] = float(tok[1])
atom['vy'] = float(tok[2])
atom['vz'] = float(tok[3])
def countH(self, output=False):
'''count H atoms bonded to each atom type'''
if len(self.atomtypes) == 0:
self.extract_nonpol()
# count for all atoms
nH = [0] * self.headers['atoms']
for bd in self.bonds:
if bd['itype'][0] in 'Hh':
j = bd['j'] - 1
nH[j] += 1
elif bd['jtype'][0] in 'Hh':
i = bd['i'] - 1
nH[i] += 1
# transfer counts to atom types
self.nH = [0] * self.headers['atom types']
for att in self.atomtypes:
id = att['id']
for atom in self.atoms:
if atom['id'] == id:
i = atom['n'] - 1
self.nH[id-1] = nH[i]
break
if (output):
for t, n in zip(self.atomtypes, self.nH):
print('{0:8s} {1:1d}'.format(t['type'], n))
def polarize(self, drude):
"""add Drude particles"""
if 'Pair Coeffs' in self.sections:
raise RuntimeError("cannot polarize a data with Pair Coeffs")
if len(self.atomtypes) == 0:
self.extract_nonpol()
natom = self.headers['atoms']
nbond = self.headers['bonds']
nattype = self.headers['atom types']
nbdtype = self.headers['bond types']
# create new atom types (IDs) for Drude particles and modify cores
newattypes = []
for att in self.atomtypes:
att['dflag'] = 'n'
for ddt in drude.types:
if ddt['type'] == att['type']:
nattype += 1
newid = {}
newid['id'] = ddt['id'] = nattype
newid['m'] = ddt['dm']
att['m'] -= ddt['dm']
# label drude particles and cores
att['dflag'] = 'c'
newid['dflag'] = 'd'
newid['type'] = att['type'] + ' DP'
att['type'] += ' DC'
ddt['type'] += ' DC'
newattypes.append(newid)
break
self.headers['atom types'] += len(newattypes)
self.sections['Masses'] = []
for att in self.atomtypes + newattypes:
self.sections['Masses'].append(massline(att))
# create new bond types for core-drude bonds
newbdtypes = []
for att in self.atomtypes:
for ddt in drude.types:
if ddt['type'] == att['type']:
nbdtype += 1
newbdtype = {}
newbdtype['id'] = ddt['bdid'] = nbdtype
newbdtype['k'] = ddt['k']
newbdtype['r0'] = 0.0
newbdtype['note'] = '# ' + ddt['type'] + '-DP'
newbdtypes.append(newbdtype)
break
self.headers['bond types'] += len(newbdtypes)
for bdt in newbdtypes:
self.sections['Bond Coeffs'].append(bdtline(bdt))
# create new atoms for Drude particles and new bonds with their cores
random.seed(123)
newatoms = []
newbonds = []
for atom in self.atoms:
atom['dflag'] = '' # [c]ore, [d]rude, [n]on-polarizable
atom['dd'] = 0 # partner drude or core
for att in self.atomtypes:
if att['id'] == atom['id']:
break
for ddt in drude.types:
if ddt['type'] == att['type']:
natom += 1
newatom = deepcopy(atom)
newatom['n'] = natom
self.idmap[natom] = newatom
newatom['id'] = ddt['id']
newatom['q'] = ddt['dq']
newatom['note'] = atom['note']
if '#' not in newatom['note']:
newatom['note'] += ' #'
newatom['note'] += ' DP'
newatom['dflag'] = 'd'
newatom['dd'] = atom['n']
# avoid superposition of cores and Drudes
newatom['x'] += 0.1 * (random.random() - 0.5)
newatom['y'] += 0.1 * (random.random() - 0.5)
newatom['z'] += 0.1 * (random.random() - 0.5)
if 'Velocities' in self.sections:
newatom['vx'] = atom['vx']
newatom['vy'] = atom['vy']
newatom['vz'] = atom['vz']
newatoms.append(newatom)
atom['q'] -= ddt['dq']
atom['dflag'] = 'c'
atom['dd'] = natom
if '#' not in atom['note']:
atom['note'] += ' #'
atom['note'] += ' DC'
nbond += 1
newbond = {}
newbond['n'] = nbond
newbond['id'] = ddt['bdid']
newbond['i'] = atom['n']
newbond['j'] = newatom['n']
newbond['note'] = '# ' + ddt['type'] + '-DP'
newbonds.append(newbond)
break
self.headers['atoms'] += len(newatoms)
self.headers['bonds'] += len(newbonds)
self.sections['Atoms'] = []
for atom in self.atoms + newatoms:
self.sections['Atoms'].append(atomline(atom))
for bond in newbonds:
self.sections['Bonds'].append(bondline(bond))
if 'Velocities' in self.sections:
self.sections['Velocities'] = []
for atom in self.atoms + newatoms:
self.sections['Velocities'].append(velline(atom))
# update list of atom IDs
for att in newattypes:
self.atomtypes.append(att)
def extract_pol(self):
"""extract atom, drude, bonds info from polarizable data"""
# extract atom IDs
for line in self.sections['Masses']:
tok = line.split()
atomtype = {}
atomtype['id'] = int(tok[0])
atomtype['m'] = float(tok[1])
if len(tok) >= 4:
atomtype['type'] = tok[3]
atomtype['dflag'] = 'n'
if tok[-1] == "DC":
atomtype['dflag'] = 'c'
elif tok[-1] == "DP":
atomtype['dflag'] = 'd'
print(atomtype['dflag'])
else:
raise RuntimeError("comments in Masses section required "\
"to identify cores (DC) and Drudes (DP)")
self.atomtypes.append(atomtype)
# extract bond type data
for line in self.sections['Bond Coeffs']:
tok = line.split()
bondtype = {}
bondtype['id'] = int(tok[0])
bondtype['k'] = float(tok[1])
bondtype['r0'] = float(tok[2])
bondtype['note'] = ''.join([s + ' ' for s in tok[3:]]).strip()
self.bondtypes.append(bondtype)
# extract atom registers
for line in self.sections['Atoms']:
tok = line.split()
atom = {}
atom['n'] = int(tok[0])
atom['mol'] = int(tok[1])
atom['id'] = int(tok[2])
atom['q'] = float(tok[3])
atom['x'] = float(tok[4])
atom['y'] = float(tok[5])
atom['z'] = float(tok[6])
# atom['note'] = ''.join([s + ' ' for s in tok[7:-1]]).strip()
if tok[-1] == 'DC':
atom['note'] = ' '.join(tok[7:-1])
else:
atom['note'] = ' '.join(tok[7:])
self.atoms.append(atom)
self.idmap[atom['n']] = atom
if 'Velocities' in self.sections:
for line in self.sections['Velocities']:
tok = line.split()
atom = self.idmap[int(tok[0])]
atom['vx'] = float(tok[1])
atom['vy'] = float(tok[2])
atom['vz'] = float(tok[3])
# extract bond data
for line in self.sections['Bonds']:
tok = line.split()
bond = {}
bond['n'] = int(tok[0])
bond['id'] = int(tok[1])
bond['i'] = int(tok[2])
bond['j'] = int(tok[3])
bond['note'] = ''.join([s + ' ' for s in tok[4:]]).strip()
self.bonds.append(bond)
if 'Velocities' in self.sections:
for line in self.sections['Velocities']:
tok = line.split()
atom = self.idmap[int(tok[0])]
atom['vx'] = float(tok[1])
atom['vy'] = float(tok[2])
atom['vz'] = float(tok[3])
def depolarize(self):
"""remove Drude particles"""
self.extract_pol()
atom_tp_map = {}
bond_tp_map = {}
atom_map = {}
bond_map = {}
q = {}
atom_tp = {}
m = {}
for att in self.atomtypes:
if att['dflag'] != 'd':
atom_tp_map[att['id']] = len(atom_tp_map) + 1
m[att['id']] = att['m']
print(atom_tp_map)
for atom in self.atoms:
if atom['id'] in atom_tp_map:
atom_map[atom['n']] = len(atom_map) + 1
q[atom['n']] = atom['q']
atom_tp[atom['n']] = atom['id']
for bond in self.bonds:
if bond['i'] in atom_map and bond['j'] in atom_map:
bond_map[bond['n']] = len(bond_map) + 1
if bond['id'] not in bond_tp_map:
bond_tp_map[bond['id']] = len(bond_tp_map) + 1
else:
if bond['i'] in atom_map:
q[bond['i']] += q[bond['j']]
if atom_tp[bond['j']] in m:
m[atom_tp[bond['i']]] += m.pop(atom_tp[bond['j']])
else:
q[bond['j']] += q[bond['i']]
if atom_tp[bond['i']] in m:
m[atom_tp[bond['j']]] += m.pop(atom_tp[bond['i']])
size = len(self.atomtypes)
for iatom_tp in reversed(range(size)):
att = self.atomtypes[iatom_tp]
if att['id'] not in atom_tp_map:
del self.atomtypes[iatom_tp]
else:
att['m'] = m[att['id']]
att['id'] = atom_tp_map[att['id']]
size = len(self.bondtypes)
for ibond_tp in reversed(range(size)):
bdt = self.bondtypes[ibond_tp]
if bdt['id'] not in bond_tp_map:
del self.bondtypes[ibond_tp]
else:
bdt['id'] = bond_tp_map[bdt['id']]
size = len(self.atoms)
for iatom in reversed(range(size)):
atom = self.atoms[iatom]
if atom['n'] not in atom_map:
del self.atoms[iatom]
else:
atom['q'] = q[atom['n']]
atom['n'] = atom_map[atom['n']]
atom['id'] = atom_tp_map[atom['id']]
size = len(self.bonds)
for ibond in reversed(range(size)):
bond = self.bonds[ibond]
if bond['n'] not in bond_map:
del self.bonds[ibond]
else:
bond['n'] = bond_map[bond['n']]
bond['id'] = bond_tp_map[bond['id']]
bond['i'] = atom_map[bond['i']]
bond['j'] = atom_map[bond['j']]
self.sections['Atoms'] = []
for atom in self.atoms:
self.sections['Atoms'].append(atomline(atom))
self.headers['atoms'] = len(self.atoms)
self.sections['Masses'] = []
for att in self.atomtypes:
self.sections['Masses'].append(massline(att))
self.headers['atom types'] = len(self.atomtypes)
self.sections['Bonds'] = []
for bond in self.bonds:
self.sections['Bonds'].append(bondline(bond))
self.headers['bonds'] = len(self.bonds)
self.sections['Bond Coeffs'] = []
for bdt in self.bondtypes:
self.sections['Bond Coeffs'].append(bdtline(bdt))
self.headers['bond types'] = len(self.bondtypes)
if 'Velocities' in self.sections:
self.sections['Velocities'] = []
for atom in self.atoms:
self.sections['Velocities'].append(velline(atom))
def writepairfile (self, pairfile, drude, thole, att_id):
"""print pair_style thole"""
with open(pairfile, "w") as f:
f.write("# interactions involving Drude particles\n")
f.write(f"pair_coeff * {att_id:3d}* coul/long/cs\n")
f.write("# Thole dipole-dipole damping if more than 1 Drude per molecule\n")
# Thole parameters for I,J pairs
ifound = False
for atti in self.atomtypes:
itype = atti['type'].split()[0]
for ddt in drude.types:
dtype = ddt['type'].split()[0]
if dtype == itype:
alphai = ddt['alpha']
tholei = ddt['thole']
ifound = True
break
jfound = False
for attj in self.atomtypes:
if attj['id'] < atti['id']:
continue
jtype = attj['type'].split()[0]
for ddt in drude.types:
dtype = ddt['type'].split()[0]
if dtype == jtype:
alphaj = ddt['alpha']
tholej = ddt['thole']
jfound = True
break
if ifound and jfound:
alphaij = (alphai * alphaj)**0.5
tholeij = (tholei + tholej) / 2.0
if tholeij == thole:
f.write("pair_coeff {0:4} {1:4} thole "\
"{2:7.3f}\n".format(atti['id'], attj['id'],
alphaij))
else:
f.write("pair_coeff {0:4} {1:4} thole {2:7.3f} "\
"{3:7.3f}\n".format(atti['id'],attj['id'],
alphaij, tholeij))
jfound = False
ifound = False
def lmpscript(self, drude, outdfile, thole = 2.6, cutoff = 12.0):
"""print lines for input script, including pair_style thole"""
inpstack = "in-drude.lmp"
pairfile = "pair-drude.lmp"
dfound = False
for att in self.atomtypes:
if att['dflag'] == 'd':
dfound = True
break
if not dfound:
print("No polarizable atoms found.")
return
print("Commands for the LAMMPS input script to handle "\
"polarization written to " + inpstack)
print("Pair coefficients for Thole damping "\
"written to " + pairfile)
print("LAMMPS data file with Drude dipoles "\
"written to " + outdfile)
with open(inpstack, 'w') as f:
f.write("# Commands to include in the LAMMPS input stack\n\n")
f.write("# adapt the pair_style command as needed\n")
f.write(f"pair_style hybrid/overlay [...] coul/long/cs {cutoff:.1f} thole {thole:.3f} {cutoff:.1f}\n\n")
f.write("# new data file with Drude oscillators added\n")
f.write(f"read_data {outdfile}\n\n")
f.write("# read pair interactions involving Drude particles\n")
f.write("# Thole damping recommended if more than 1 Drude "\
"per molecule\n")
f.write(f"include {pairfile}\n\n")
self.writepairfile(pairfile, drude, thole, att['id'])
f.write("# convenient atom groups (for shake, thermostats...)\n")
gatoms = gcores = gdrudes = ""
ndrude = 0
for att in self.atomtypes:
if att['dflag'] != 'd':
gatoms += " {0}".format(att['id'])
if att['dflag'] == 'c':
gcores += " {0}".format(att['id'])
if att['dflag'] == 'd':
gdrudes += " {0}".format(att['id'])
ndrude += 1
f.write("group ATOMS type" + gatoms + "\n")
f.write("group CORES type" + gcores + "\n")
f.write("group DRUDES type" + gdrudes + "\n\n")
f.write("# identify each atom type: "\
"[C]ore, [D]rude, [N]on-polarizable\n")
drudetypes = ""
for att in self.atomtypes:
drudetypes += " {0}".format(att['dflag'].upper())
f.write("fix DRUDE all drude" + drudetypes + "\n\n")
f.write("# store velocity information of ghost atoms\n")
f.write("comm_modify vel yes\n\n")
f.write("variable TK equal 300.0\n")
f.write("variable TDRUDE equal 1.0\n")
f.write("variable PBAR equal 1.0\n\n")
f.write("# temperature-grouped multiple Nose-Hoover thermostats "\
" and barostat\n")
f.write("fix TSTAT all tgnpt/drude temp ${TK} ${TK} 100 "\
"${TDRUDE} 20 iso ${PBAR} ${PBAR} 1000\n\n")
f.write("# zero linear momentum (may not be needed)\n")
f.write("fix ICECUBE all momentum 1000 linear 1 1 1\n\n")
f.write("# output the temperatures of molecular COM, "\
"COM of DC-DP, and DP\n")
f.write("thermo_style custom step [...] "\
"f_TSTAT[1] f_TSTAT[2] f_TSTAT[3]\n\n")
f.write("# write Drude particles to dump file\n")
f.write("dump_modify ... element ... " + ndrude*" Dp" + "\n\n")
f.write("# ATTENTION!\n")
f.write("# * read_data may need 'extra/special/per/atom' keyword, "
"LAMMPS will exit with a message\n")
f.write("# * if using fix shake the group-ID must not include "
"Drude particles; use group ATOMS\n")
f.write("# * give all I<=J pair interactions, no mixing\n")
f.write("# * pair style coul/long/cs from CORESHELL package is "\
"used for interactions of DP;\n")
f.write("# alternatively pair lj/cut/thole/long could be used "\
"avoiding hybrid/overlay and\n")
f.write("# allowing mixing; see doc pages.\n")
# --------------------------------------
kcal = 4.184 # kJ
eV = 96.485 # kJ/mol
fpe0 = 0.0007197587 # (4 Pi eps0) in e^2/(kJ/mol A)
alpha_H = 0.323 # PCCP 20 (2018) 10992
class Drude(object):
"""specification of drude oscillator types"""
def __init__(self, drudefile, data, kcalc=False, metal=False):
self.types = []
self.alpha_H = alpha_H
with open(drudefile, "r") as f:
# search for polarizability of H
for line in f:
line = line.strip()
if line.startswith('#') or len(line) == 0:
continue
if line.startswith('H'):
tok = line.split()
self.alpha_H = float(tok[4])
break
print(f'Polarizability of H merged into heavy atoms: {self.alpha_H:.3f} A3')
f.seek(0)
data.countH()
for line in f:
line = line.strip()
if line.startswith('#') or len(line) == 0:
continue
tok = line.split()
if tok[0].startswith('H'):
if float(tok[4]) != self.alpha_H:
print(f'warning: different polarizabilities for H, using {self.alpha_H:.3f} A3')
continue
drude = {}
drude['type'] = tok[0]
drude['dm'] = float(tok[1])
dq = float(tok[2])
k = float(tok[3])
alpha = float(tok[4])
drude['thole'] = float(tok[5])
positive = True if dq > 0.0 else False
for att in data.atomtypes:
if att['type'] == drude['type']:
id = att['id'] - 1
alpha += data.nH[id] * self.alpha_H
break
drude['alpha'] = alpha
if kcalc:
k = dq*dq / (fpe0 * alpha)
else:
dq = (fpe0 * k * alpha)**0.5
if positive:
drude['dq'] = abs(dq)
else:
drude['dq'] = -abs(dq)
if metal:
drude['k'] = k / (2.0 * eV)
else:
drude['k'] = k / (2.0 * kcal)
self.types.append(drude)
# --------------------------------------
def main():
parser = argparse.ArgumentParser(description = usage,
formatter_class = argparse.RawTextHelpFormatter)
parser.add_argument('-a', '--alpha_file', default = 'alpha.ff',
help = 'Drude parameter file (default: alpha.ff)')
parser.add_argument('-k', '--kcalc', action = 'store_true',
help = 'Drude force constants calculated from '\
'polarizability (default: k from parameter file '\
'and q from polarizability)')
parser.add_argument('-t', '--thole', type = float, default = 2.6,
help = 'global Thole damping parameter (default: 2.6)')
parser.add_argument('-c', '--cutoff', type = float, default = 12.0,
help = 'global distance cutoff/A (default: 12.0)')
parser.add_argument('-m', '--metal', action = 'store_true',
help = 'LAMMPS metal units (default: real units)')
parser.add_argument('-d', '--depolarize', action = 'store_true',
help = 'remove Drude dipole polarization from '\
'LAMMPS data file')
parser.add_argument('infile', help = 'input LAMMPS data file')
parser.add_argument('outfile', help = 'output LAMMPS data file')
args = parser.parse_args()
data = Data(args.infile)
if not args.depolarize:
drude = Drude(args.alpha_file, data, args.kcalc, args.metal)
data.polarize(drude)
data.lmpscript(drude, args.outfile, args.thole, args.cutoff)
else:
data.depolarize()
data.write(args.outfile)
if __name__ == '__main__':
main()