forked from peteboyd/lammps_interface
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_cluster_v2.py
3572 lines (3016 loc) · 167 KB
/
create_cluster_v2.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
#!/usr/bin/env python
"""
main.py
the program starts here.
"""
import sys
import math
import re
import numpy as np
import networkx as nx
import ForceFields
import itertools
import operator
from structure_data import from_CIF, write_CIF, clean
from structure_data import write_RASPA_CIF, write_RASPA_sim_files, MDMC_config
from CIFIO import CIF
from ccdc import CCDC_BOND_ORDERS
from datetime import datetime
from InputHandler import Options
from copy import deepcopy
import Molecules
if sys.version_info < (3,0):
input = raw_input
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
from structure_data import MolecularGraph
from atomic import ATOMIC_NUMBER
class LammpsSimulation(object):
def __init__(self, options):
self.name = clean(options.cif_file)
self.special_commands = []
self.options = options
self.molecules = []
self.subgraphs = []
self.molecule_types = {}
self.unique_atom_types = {}
self.unique_bond_types = {}
self.unique_angle_types = {}
self.unique_dihedral_types = {}
self.unique_improper_types = {}
self.unique_pair_types = {}
self.pair_in_data = True
self.separate_molecule_types = True
self.framework = False # Flag if a framework exists in the simulation.
self.type_molecules = {}
self.no_molecule_pair = True # ensure that h-bonding will not occur between molecules of the same type
self.fix_shake = {}
self.fix_rigid = {}
def set_MDMC_config(self, MDMC_config):
self.MDMC_config = MDMC_config
def unique_atoms(self):
"""Computes the number of unique atoms in the structure"""
count = 0
ff_type = {}
fwk_nodes = sorted(self.graph.nodes())
molecule_nodes = []
for k in sorted(self.molecule_types.keys()):
nds = []
for m in self.molecule_types[k]:
jnodes = sorted(self.subgraphs[m].nodes())
nds += jnodes
for n in jnodes:
del fwk_nodes[fwk_nodes.index(n)]
molecule_nodes.append(nds)
molecule_nodes.append(fwk_nodes)
for node, data in self.graph.nodes_iter(data=True):
# add factor for h_bond donors
if self.separate_molecule_types:
molid = [j for j,mol in enumerate(molecule_nodes) if node in mol]
if(len(molid) != 1):
print("ERROR!")
molid = molid[0]
else:
molid = 0
if data['force_field_type'] is None:
if data['h_bond_donor']:
# add neighbors to signify type of hbond donor
label = (data['element'], data['h_bond_donor'], molid, tuple(sorted([self.graph.node[j]['element'] for j in self.graph.neighbors(node)])))
else:
label = (data['element'], data['h_bond_donor'], molid)
else:
if data['h_bond_donor']:
# add neighbors to signify type of hbond donor
label = (data['force_field_type'], data['h_bond_donor'], molid, tuple(sorted([self.graph.node[j]['element'] for j in self.graph.neighbors(node)])))
else:
label = (data['force_field_type'], data['h_bond_donor'], molid)
try:
type = ff_type[label]
except KeyError:
count += 1
type = count
ff_type[label] = type
self.unique_atom_types[type] = node
self.type_molecules[type] = molid
data['ff_type_index'] = type
def unique_bonds(self):
"""Computes the number of unique bonds in the structure"""
count = 0
bb_type = {}
for n1, n2, data in self.graph.edges_iter2(data=True):
btype = "%s"%data['potential']
try:
type = bb_type[btype]
except KeyError:
try:
if data['potential'].special_flag == 'shake':
self.fix_shake.setdefault('bonds', []).append(count+1)
except AttributeError:
pass
count += 1
type = count
bb_type[btype] = type
self.unique_bond_types[type] = (n1, n2, data)
data['ff_type_index'] = type
def unique_angles(self):
ang_type = {}
count = 0
for b, data in self.graph.nodes_iter(data=True):
# compute and store angle terms
try:
ang_data = data['angles']
for (a, c), val in ang_data.items():
atype = "%s"%val['potential']
try:
type = ang_type[atype]
except KeyError:
count += 1
try:
if val['potential'].special_flag == 'shake':
self.fix_shake.setdefault('angles', []).append(count)
except AttributeError:
pass
type = count
ang_type[atype] = type
self.unique_angle_types[type] = (a, b, c, val)
val['ff_type_index'] = type
# update original dictionary
data['angles'][(a, c)] = val
except KeyError:
# no angle associated with this node.
pass
def unique_dihedrals(self):
count = 0
dihedral_type = {}
for b, c, data in self.graph.edges_iter2(data=True):
try:
dihed_data = data['dihedrals']
for (a, d), val in dihed_data.items():
dtype = "%s"%val['potential']
try:
type = dihedral_type[dtype]
except KeyError:
count += 1
type = count
dihedral_type[dtype] = type
self.unique_dihedral_types[type] = (a, b, c, d, val)
val['ff_type_index'] = type
# update original dictionary
data['dihedrals'][(a,d)] = val
except KeyError:
# no dihedrals associated with this edge
pass
def unique_impropers(self):
count = 0
improper_type = {}
for b, data in self.graph.nodes_iter(data=True):
try:
rem = []
imp_data = data['impropers']
for (a, c, d), val in imp_data.items():
if val['potential'] is not None:
itype = "%s"%val['potential']
try:
type = improper_type[itype]
except KeyError:
count += 1
type = count
improper_type[itype] = type
self.unique_improper_types[type] = (a, b, c, d, val)
val['ff_type_index'] = type
else:
rem.append((a,c,d))
for m in rem:
data['impropers'].pop(m)
except KeyError:
# no improper terms associated with this atom
pass
def unique_pair_terms(self):
pot_names = []
nodes_list = sorted(self.unique_atom_types.keys())
electro_neg_atoms = ["N", "O", "F"]
for n, data in self.graph.nodes_iter(data=True):
if data['h_bond_donor']:
pot_names.append('h_bonding')
if data['tabulated_potential']:
pot_names.append('table')
pot_names.append(data['pair_potential'].name)
# mix yourself
table_str = ""
if len(list(set(pot_names))) > 1 or (any(['buck' in i for i in list(set(pot_names))])):
self.pair_in_data = False
for (i, j) in itertools.combinations_with_replacement(nodes_list, 2):
n1, n2 = self.unique_atom_types[i], self.unique_atom_types[j]
i_data = self.graph.node[n1]
j_data = self.graph.node[n2]
mol1 = self.type_molecules[i]
mol2 = self.type_molecules[j]
# test to see if h-bonding to occur between molecules
pairwise_test = ((mol1 != mol2 and self.no_molecule_pair) or (not self.no_molecule_pair))
if i_data['tabulated_potential'] and j_data['tabulated_potential']:
table_pot = deepcopy(i_data)
table_str += table_pot['table_function'](i_data,j_data, table_pot)
table_pot['table_potential'].filename = "table." + self.name
self.unique_pair_types[(i, j, 'table')] = table_pot
if (i_data['h_bond_donor'] and j_data['element'] in electro_neg_atoms and pairwise_test and not j_data['h_bond_donor']):
hdata = deepcopy(i_data)
hdata['h_bond_potential'] = hdata['h_bond_function'](n2, self.graph, flipped=False)
hdata['tabulated_potential'] = False
self.unique_pair_types[(i,j,'hb')] = hdata
if (j_data['h_bond_donor'] and i_data['element'] in electro_neg_atoms and pairwise_test and not i_data['h_bond_donor']):
hdata = deepcopy(j_data)
hdata['tabulated_potential'] = False
hdata['h_bond_potential'] = hdata['h_bond_function'](n1, self.graph, flipped=True)
self.unique_pair_types[(i,j,'hb')] = hdata
# mix Lorentz-Berthelot rules
pair_data = deepcopy(i_data)
if 'buck' in i_data['pair_potential'].name and 'buck' in j_data['pair_potential'].name:
eps1 = i_data['pair_potential'].eps
eps2 = j_data['pair_potential'].eps
sig1 = i_data['pair_potential'].sig
sig2 = j_data['pair_potential'].sig
eps = np.sqrt(eps1*eps2)
Rv = (sig1 + sig2)
Rho = Rv/12.0
A = 1.84e5 * eps
C=2.25*(Rv)**6*eps
pair_data['pair_potential'].A = A
pair_data['pair_potential'].rho = Rho
pair_data['pair_potential'].C = C
pair_data['tabulated_potential'] = False
# assuming i_data has the same pair_potential name as j_data
self.unique_pair_types[(i,j, i_data['pair_potential'].name)] = pair_data
elif 'lj' in i_data['pair_potential'].name and 'lj' in j_data['pair_potential'].name:
pair_data['pair_potential'].eps = np.sqrt(i_data['pair_potential'].eps*j_data['pair_potential'].eps)
pair_data['pair_potential'].sig = (i_data['pair_potential'].sig + j_data['pair_potential'].sig)/2.
pair_data['tabulated_potential'] = False
self.unique_pair_types[(i,j, i_data['pair_potential'].name)] = pair_data
# can be mixed by lammps
else:
for b in sorted(list(self.unique_atom_types.keys())):
data = self.graph.node[self.unique_atom_types[b]]
# compute and store angle terms
pot = data['pair_potential']
self.unique_pair_types[b] = data
if (table_str):
f = open('table.'+self.name, 'w')
f.writelines(table_str)
f.close()
return
def define_styles(self):
# should be more robust, some of the styles require multiple parameters specified on these lines
self.kspace_style = "ewald %f"%(0.000001)
bonds = set([j['potential'].name for n1, n2, j in list(self.unique_bond_types.values())])
if len(list(bonds)) > 1:
self.bond_style = "hybrid %s"%" ".join(list(bonds))
else:
self.bond_style = "%s"%list(bonds)[0]
for n1, n2, b in list(self.unique_bond_types.values()):
b['potential'].reduced = True
angles = set([j['potential'].name for a,b,c,j in list(self.unique_angle_types.values())])
if len(list(angles)) > 1:
self.angle_style = "hybrid %s"%" ".join(list(angles))
else:
self.angle_style = "%s"%list(angles)[0]
for a,b,c,ang in list(self.unique_angle_types.values()):
ang['potential'].reduced = True
if (ang['potential'].name == "class2"):
ang['potential'].bb.reduced=True
ang['potential'].ba.reduced=True
dihedrals = set([j['potential'].name for a,b,c,d,j in list(self.unique_dihedral_types.values())])
if len(list(dihedrals)) > 1:
self.dihedral_style = "hybrid %s"%" ".join(list(dihedrals))
else:
self.dihedral_style = "%s"%list(dihedrals)[0]
for a,b,c,d, di in list(self.unique_dihedral_types.values()):
di['potential'].reduced = True
if (di['potential'].name == "class2"):
di['potential'].mbt.reduced=True
di['potential'].ebt.reduced=True
di['potential'].at.reduced=True
di['potential'].aat.reduced=True
di['potential'].bb13.reduced=True
impropers = set([j['potential'].name for a,b,c,d,j in list(self.unique_improper_types.values())])
if len(list(impropers)) > 1:
self.improper_style = "hybrid %s"%" ".join(list(impropers))
elif len(list(impropers)) == 1:
self.improper_style = "%s"%list(impropers)[0]
for a,b,c,d,i in list(self.unique_improper_types.values()):
i['potential'].reduced = True
if (i['potential'].name == "class2"):
i['potential'].aa.reduced=True
else:
self.improper_style = ""
pairs = set(["%r"%(j['pair_potential']) for j in list(self.unique_pair_types.values())]) | \
set(["%r"%(j['h_bond_potential']) for j in list(self.unique_pair_types.values()) if j['h_bond_potential'] is not None]) | \
set(["%r"%(j['table_potential']) for j in list(self.unique_pair_types.values()) if j['tabulated_potential']])
if len(list(pairs)) > 1:
self.pair_style = "hybrid/overlay %s"%(" ".join(list(pairs)))
else:
self.pair_style = "%s"%list(pairs)[0]
for p in list(self.unique_pair_types.values()):
p['pair_potential'].reduced = True
def set_graph(self, graph):
self.graph = graph
try:
if(not self.options.force_field == "UFF") and (not self.options.force_field == "Dreiding"):
self.graph.find_metal_sbus = True # true for UFF4MOF, BTW_FF and Dubbeldam
if (self.options.force_field == "Dubbeldam"):
self.graph.find_organic_sbus = True
self.graph.compute_topology_information(self.cell, self.options.tol, self.options.neighbour_size)
except AttributeError:
# no cell set yet
pass
def set_cell(self, cell):
self.cell = cell
try:
self.graph.compute_topology_information(self.cell, self.options.tol, self.options.neighbour_size)
except AttributeError:
# no graph set yet
pass
def split_graph(self):
self.compute_molecules()
if (self.molecules):
print("Molecules found in the framework, separating.")
molid=0
for molecule in self.molecules:
molid += 1
sg = self.cut_molecule(molecule)
sg.molecule_id = molid
# unwrap coordinates
sg.unwrap_node_coordinates(self.cell)
self.subgraphs.append(sg)
type = 0
temp_types = {}
for i, j in itertools.combinations(range(len(self.subgraphs)), 2):
if self.subgraphs[i].number_of_nodes() != self.subgraphs[j].number_of_nodes():
continue
matched = self.subgraphs[i] | self.subgraphs[j]
if (len(matched) == self.subgraphs[i].number_of_nodes()):
if i not in list(temp_types.keys()) and j not in list(temp_types.keys()):
type += 1
temp_types[i] = type
temp_types[j] = type
self.molecule_types.setdefault(type, []).append(i)
self.molecule_types[type].append(j)
else:
try:
type = temp_types[i]
temp_types[j] = type
except KeyError:
type = temp_types[j]
temp_types[i] = type
if i not in self.molecule_types[type]:
self.molecule_types[type].append(i)
if j not in self.molecule_types[type]:
self.molecule_types[type].append(j)
unassigned = set(range(len(self.subgraphs))) - set(list(temp_types.keys()))
for j in list(unassigned):
type += 1
self.molecule_types[type] = [j]
def assign_force_fields(self):
attr = {'graph':self.graph, 'cutoff':self.options.cutoff, 'h_bonding':self.options.h_bonding,
'keep_metal_geometry':self.options.fix_metal, 'bondtype':self.options.dreid_bond_type}
param = getattr(ForceFields, self.options.force_field)(**attr)
self.special_commands += param.special_commands()
# apply different force fields.
for mtype in list(self.molecule_types.keys()):
# prompt for ForceField?
rep = self.subgraphs[self.molecule_types[mtype][0]]
#response = input("Would you like to apply a new force field to molecule type %i with atoms (%s)? [y/n]: "%
# (mtype, ", ".join([rep.node[j]['element'] for j in rep.nodes()])))
#ff = self.options.force_field
#if response.lower() in ['y','yes']:
# ff = input("Please enter the name of the force field: ")
#elif response.lower() in ['n', 'no']:
# pass
#else:
# print("Unrecognized command: %s"%response)
ff = self.options.mol_ff
if ff is None:
ff = self.options.force_field
atoms = ", ".join([rep.node[j]['element'] for j in rep.nodes()])
print("Warning: Molecule %s with atoms (%s) will be using the %s force field as no "%(mtype,atoms,ff)+
" value was set for molecules. To prevent this warning "+
"set --molecule-ff=[some force field] on the command line.")
h_bonding = False
if (ff == "Dreiding"):
hbonding = input("Would you like this molecule type to have hydrogen donor potentials? [y/n]: ")
if hbonding.lower() in ['y', 'yes']:
h_bonding = True
elif hbonding.lower() in ['n', 'no']:
h_bonding = False
else:
print("Unrecognized command: %s"%hbonding)
sys.exit()
for m in self.molecule_types[mtype]:
# Water check
# currently only works on bare water without dummy atoms.
ngraph = self.subgraphs[m]
self.assign_molecule_ids(ngraph)
if ff[-5:] == "Water":
self.add_water_model(ngraph, ff)
ff = ff[:-6] # remove _Water from end of name
p = getattr(ForceFields, ff)(graph=self.subgraphs[m],
cutoff=self.options.cutoff,
h_bonding=h_bonding)
self.special_commands += p.special_commands()
def assign_molecule_ids(self, graph):
for node in graph.nodes():
graph.node[node]['molid'] = graph.molecule_id
def molecule_template(self, mol):
""" Construct a molecule template for
reading and insertions in a LAMMPS simulation.
Not sure how the bonding, angle, dihedral, improper,
and pair terms will be dealt with yet..
"""
#I think the Molecule class should be generalized so that
#this kind of input can be generated easily
molecule = getattr(Molecule, mol)()
def add_water_model(self, ngraph, ff):
size = ngraph.number_of_nodes()
if size < 3 or size > 3:
print("Error: cannot assign %s "%(ff) +
"to molecule of size %i, with "%(size)+
"atoms (%s)"%(", ".join([ngraph.node[kk]['element'] for
kk in ngraph.nodes()])))
print("If this is a water molecule with pre-existing "+
"dummy atoms for a particular force field, "+
"please remove them and re-run this code.")
sys.exit()
for node in ngraph.nodes():
if ngraph.node[node]['element'] == "O":
oid = node
oatom = ngraph.node[node]
elif ngraph.node[node]['element'] == "H":
try:
hatom1
h2id = node
hatom2 = ngraph.node[node]
except NameError:
h1id = node
hatom1 = ngraph.node[node]
h2o = getattr(Molecules, ff)()
h2o.approximate_positions(O_pos = oatom['cartesian_coordinates'],
H_pos1 = hatom1['cartesian_coordinates'],
H_pos2 = hatom2['cartesian_coordinates'])
# replace the current H positions with the force-field assigned
# ones
oatom['mass'] = h2o.O_mass
oatom['force_field_type'] = "OW"
hatom1['cartesian_coordinates'] = h2o.H_coord[0]
hatom1['mass'] = h2o.H_mass
hatom1['force_field_type'] = "HW"
hatom2['cartesian_coordinates'] = h2o.H_coord[1]
hatom2['mass'] = h2o.H_mass
hatom2['force_field_type'] = "HW"
for j in h2o.dummy:
# increment graph size
self.increment_graph_sizes()
os = ngraph.original_size
args = {'element': 'X',
'force_field_type': 'X',
'cartesian_coordinates': j,
'potential': None,
'rings': [],
'molid': ngraph.molecule_id,
'atomic_number': 0,
'h_bond_donor': False,
'h_bond_potential': None,
'tabulated_potential': False,
'table_potential': None,
'pair_potential': None
}
ngraph.add_node(os, **args)
ngraph.add_edge(oid, os, order=1.,
weight=1.,
length=h2o.Rdum,
symflag='1_555',
)
ngraph.sorted_edge_dict.update({(oid, os): (oid, os)})
ngraph.sorted_edge_dict.update({(os, oid): (oid, os)})
# compute new angles between dummy atoms
ngraph.compute_angles()
def increment_graph_sizes(self, inc=1):
self.graph.original_size += inc
for mtype in list(self.molecule_types.keys()):
for m in self.molecule_types[mtype]:
graph = self.subgraphs[m]
graph.original_size += 1
def compute_simulation_size(self):
supercell = self.cell.minimum_supercell(self.options.cutoff)
if np.any(np.array(supercell) > 1):
print("Warning: unit cell is not large enough to"
+" support a non-bonded cutoff of %.2f Angstroms."%self.options.cutoff)
if(self.options.replication is not None):
supercell = tuple(map(int, re.split('x| |, |,',self.options.replication)))
if(len(supercell) != 3):
if(supercell[0] < 1 or supercell[1] < 1 or supercell[2] < 1):
print("Incorrect supercell requested: %s\n"%(supercell))
print("Use <ixjxk> format")
print("Exiting...")
sys.exit()
if np.any(np.array(supercell) > 1):
print("Re-sizing to a %i x %i x %i supercell. "%(supercell))
#TODO(pboyd): apply to subgraphs as well, if requested.
self.graph.build_supercell(supercell, self.cell)
molcount = 0
if self.subgraphs:
molcount = max([g.molecule_id for g in self.subgraphs])
for mtype in list(self.molecule_types.keys()):
# prompt for replication of this molecule in the supercell.
rep = self.subgraphs[self.molecule_types[mtype][0]]
response = input("Would you like to replicate molceule %i with atoms (%s) in the supercell? [y/n]: "%
(mtype, ", ".join([rep.node[j]['element'] for j in rep.nodes()])))
if response in ['y', 'Y', 'yes']:
for m in self.molecule_types[mtype]:
self.subgraphs[m].build_supercell(supercell, self.cell, track_molecule=True, molecule_len=molcount)
self.cell.update_supercell(supercell)
def compute_cluster_box_size(self):
"""
Added by MW b/c simbox size can need to be even bigger than a normal
simbox when we are making a cluster from one unit cell
"""
supercell = self.cell.minimum_supercell(self.options.cutoff)
# we really need a 3x3x3 grid of supercells to 100% ensure we get all components of cluster accurately
supercell = (supercell[0]+2, supercell[1]+2, supercell[2]+2)
self.supercell_tuple = (supercell[0], supercell[1], supercell[2])
if np.any(np.array(supercell) > 1):
print("Warning: unit cell is not large enough to"
+" support a non-bonded cutoff of %.2f Angstroms\n"%self.options.cutoff +
"Re-sizing to a %i x %i x %i supercell. "%(supercell))
#TODO(pboyd): apply to subgraphs as well, if requested.
self.graph.build_supercell(supercell, self.cell)
for mtype in list(self.molecule_types.keys()):
# prompt for replication of this molecule in the supercell.
rep = self.subgraphs[self.molecule_types[mtype][0]]
response = input("Would you like to replicate moleule %i with atoms (%s) in the supercell? [y/n]: "%
(mtype, ", ".join([rep.node[j]['element'] for j in rep.nodes()])))
if response in ['y', 'Y', 'yes']:
for m in self.molecule_types[mtype]:
self.subgraphs[m].build_supercell(supercell, self.cell, track_molecule=True)
self.cell.update_supercell(supercell)
def count_dihedrals(self):
count = 0
for n1, n2, data in self.graph.edges_iter(data=True):
try:
for dihed in data['dihedrals'].keys():
count += 1
except KeyError:
pass
return count
def count_angles(self):
count = 0
for node, data in self.graph.nodes_iter(data=True):
try:
for angle in data['angles'].keys():
count += 1
except KeyError:
pass
return count
def count_impropers(self):
count = 0
for node, data in self.graph.nodes_iter(data=True):
try:
for angle in data['impropers'].keys():
count += 1
except KeyError:
pass
return count
def merge_graphs(self):
for mgraph in self.subgraphs:
self.graph += mgraph
if sorted(self.graph.nodes()) != [i+1 for i in range(len(self.graph.nodes()))]:
print("Re-labelling atom indices.")
reorder_dic = {i:j+1 for i, j in zip(sorted(self.graph.nodes()), range(len(self.graph.nodes())))}
self.graph.reorder_labels(reorder_dic)
for mgraph in self.subgraphs:
mgraph.reorder_labels(reorder_dic)
def write_lammps_files(self):
self.unique_atoms()
self.unique_bonds()
self.unique_angles()
self.unique_dihedrals()
self.unique_impropers()
self.unique_pair_terms()
self.define_styles()
data_str = self.construct_data_file()
datafile = open("data.%s"%self.name, 'w')
datafile.writelines(data_str)
datafile.close()
inp_str = self.construct_input_file()
inpfile = open("in.%s"%self.name, 'w')
inpfile.writelines(inp_str)
inpfile.close()
print("files created!")
def construct_data_file(self):
t = datetime.today()
string = "Created on %s\n\n"%t.strftime("%a %b %d %H:%M:%S %Y %Z")
if(len(self.unique_atom_types.keys()) > 0):
string += "%12i atoms\n"%(nx.number_of_nodes(self.graph))
if(len(self.unique_bond_types.keys()) > 0):
string += "%12i bonds\n"%(nx.number_of_edges(self.graph))
if(len(self.unique_angle_types.keys()) > 0):
string += "%12i angles\n"%(self.count_angles())
if(len(self.unique_dihedral_types.keys()) > 0):
string += "%12i dihedrals\n"%(self.count_dihedrals())
if (len(self.unique_improper_types.keys()) > 0):
string += "%12i impropers\n"%(self.count_impropers())
if(len(self.unique_atom_types.keys()) > 0):
string += "\n%12i atom types\n"%(len(self.unique_atom_types.keys()))
if(len(self.unique_bond_types.keys()) > 0):
string += "%12i bond types\n"%(len(self.unique_bond_types.keys()))
if(len(self.unique_angle_types.keys()) > 0):
string += "%12i angle types\n"%(len(self.unique_angle_types.keys()))
if(len(self.unique_dihedral_types.keys()) > 0):
string += "%12i dihedral types\n"%(len(self.unique_dihedral_types.keys()))
if (len(self.unique_improper_types.keys()) > 0):
string += "%12i improper types\n"%(len(self.unique_improper_types.keys()))
string += "%19.6f %10.6f %s %s\n"%(0., self.cell.lx, "xlo", "xhi")
string += "%19.6f %10.6f %s %s\n"%(0., self.cell.ly, "ylo", "yhi")
string += "%19.6f %10.6f %s %s\n"%(0., self.cell.lz, "zlo", "zhi")
if (np.any(np.array([self.cell.xy, self.cell.xz, self.cell.yz]) > 0.0)):
string += "%19.6f %10.6f %10.6f %s %s %s\n"%(self.cell.xy, self.cell.xz, self.cell.yz, "xy", "xz", "yz")
# Let's track the forcefield potentials that haven't been calc'd or user specified
no_bond = []
no_angle = []
no_dihedral = []
no_improper = []
# this should be non-zero, but just in case..
if(len(self.unique_atom_types.keys()) > 0):
string += "\nMasses\n\n"
for key in sorted(self.unique_atom_types.keys()):
unq_atom = self.graph.node[self.unique_atom_types[key]]
mass, type = unq_atom['mass'], unq_atom['force_field_type']
string += "%5i %15.9f # %s\n"%(key, mass, type)
if(len(self.unique_bond_types.keys()) > 0):
string += "\nBond Coeffs\n\n"
for key in sorted(self.unique_bond_types.keys()):
n1, n2, bond = self.unique_bond_types[key]
atom1, atom2 = self.graph.node[n1], self.graph.node[n2]
if bond['potential'] is None:
no_bond.append("%5i : %s %s"%(key,
atom1['force_field_type'],
atom2['force_field_type']))
else:
ff1, ff2 = (atom1['force_field_type'],
atom2['force_field_type'])
string += "%5i %s "%(key, bond['potential'])
string += "# %s %s\n"%(ff1, ff2)
class2angle = False
if(len(self.unique_angle_types.keys()) > 0):
string += "\nAngle Coeffs\n\n"
for key in sorted(self.unique_angle_types.keys()):
a, b, c, angle = self.unique_angle_types[key]
atom_a, atom_b, atom_c = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c]
if angle['potential'] is None:
no_angle.append("%5i : %s %s %s"%(key,
atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type']))
else:
if (angle['potential'].name == "class2"):
class2angle = True
string += "%5i %s "%(key, angle['potential'])
string += "# %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'])
if(class2angle):
string += "\nBondBond Coeffs\n\n"
for key in sorted(self.unique_angle_types.keys()):
a, b, c, angle = self.unique_angle_types[key]
atom_a, atom_b, atom_c = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c]
if (angle['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'])
else:
try:
string += "%5i %s "%(key, angle['potential'].bb)
string += "# %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'])
except AttributeError:
pass
string += "\nBondAngle Coeffs\n\n"
for key in sorted(self.unique_angle_types.keys()):
a, b, c, angle = self.unique_angle_types[key]
atom_a, atom_b, atom_c = self.graph.node[a],\
self.graph.node[b],\
self.graph.node[c]
if (angle['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'])
else:
try:
string += "%5i %s "%(key, angle['potential'].ba)
string += "# %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'])
except AttributeError:
pass
class2dihed = False
if(len(self.unique_dihedral_types.keys()) > 0):
string += "\nDihedral Coeffs\n\n"
for key in sorted(self.unique_dihedral_types.keys()):
a, b, c, d, dihedral = self.unique_dihedral_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if dihedral['potential'] is None:
no_dihedral.append("%5i : %s %s %s %s"%(key,
atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type']))
else:
if(dihedral['potential'].name == "class2"):
class2dihed = True
string += "%5i %s "%(key, dihedral['potential'])
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
if (class2dihed):
string += "\nMiddleBondTorsion Coeffs\n\n"
for key in sorted(self.unique_dihedral_types.keys()):
a, b, c, d, dihedral = self.unique_dihedral_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if (dihedral['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
else:
try:
string += "%5i %s "%(key, dihedral['potential'].mbt)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
except AttributeError:
pass
string += "\nEndBondTorsion Coeffs\n\n"
for key in sorted(self.unique_dihedral_types.keys()):
a, b, c, d, dihedral = self.unique_dihedral_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if (dihedral['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
else:
try:
string += "%5i %s "%(key, dihedral['potential'].ebt)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
except AttributeError:
pass
string += "\nAngleTorsion Coeffs\n\n"
for key in sorted(self.unique_dihedral_types.keys()):
a, b, c, d, dihedral = self.unique_dihedral_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if (dihedral['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
else:
try:
string += "%5i %s "%(key, dihedral['potential'].at)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
except AttributeError:
pass
string += "\nAngleAngleTorsion Coeffs\n\n"
for key in sorted(self.unique_dihedral_types.keys()):
a, b, c, d, dihedral = self.unique_dihedral_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if (dihedral['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
else:
try:
string += "%5i %s "%(key, dihedral['potential'].aat)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
except AttributeError:
pass
string += "\nBondBond13 Coeffs\n\n"
for key in sorted(self.unique_dihedral_types.keys()):
a, b, c, d, dihedral = self.unique_dihedral_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if (dihedral['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
else:
try:
string += "%5i %s "%(key, dihedral['potential'].bb13)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
except AttributeError:
pass
class2improper = False
if (len(self.unique_improper_types.keys()) > 0):
string += "\nImproper Coeffs\n\n"
for key in sorted(self.unique_improper_types.keys()):
a, b, c, d, improper = self.unique_improper_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if improper['potential'] is None:
no_improper.append("%5i : %s %s %s %s"%(key,
atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type']))
else:
if(improper['potential'].name == "class2"):
class2improper = True
string += "%5i %s "%(key, improper['potential'])
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
if (class2improper):
string += "\nAngleAngle Coeffs\n\n"
for key in sorted(self.unique_improper_types.keys()):
a, b, c, d, improper = self.unique_improper_types[key]
atom_a, atom_b, atom_c, atom_d = self.graph.node[a], \
self.graph.node[b], \
self.graph.node[c], \
self.graph.node[d]
if (improper['potential'].name!="class2"):
string += "%5i skip "%(key)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
else:
try:
string += "%5i %s "%(key, improper['potential'].aa)
string += "# %s %s %s %s\n"%(atom_a['force_field_type'],
atom_b['force_field_type'],
atom_c['force_field_type'],
atom_d['force_field_type'])
except AttributeError:
pass
if((len(self.unique_pair_types.keys()) > 0) and (self.pair_in_data)):