forked from Staubjr/little_wiggler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Modeling_Amino_Acids_V5.py
2083 lines (1486 loc) · 74.2 KB
/
Modeling_Amino_Acids_V5.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 python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 14:16:57 2019
@author: jacobstaub
"""
import numpy as np
import math
import matplotlib.pyplot as plt
import sys
import random
import physvis as vis
import random
from scipy.integrate import ode
import os
from scipy.spatial.transform import Rotation as R
""" Note about the units used here:
To match the par and top files from CHARM files
these are the following unit scales we are working in:
Distance: Angstroms
Mass: AMU
Energy: eV
Time: sqrt( AMU * Angstroms^2 / eV ) =~ 1E-14 sec
Angles: Radians
This results in this unit of energy:
E' = (1E-2)/n * Joules
E' = 1.602E-21 * eV """
Time_Unit = ( (1.66054E-27) * (1E-10)**2 / 1.602E-19 ) ** (1/2)
energy_conversion_factor = (2.611E22/6.022E23)
Simulation_config_path = '/home/staubj/Capstone_Files/Txt_CHARM_Files/MD_Simulation_Final_Data/'
Resdiue_config_path = '/home/staubj/Capstone_Files/Txt_CHARM_Files/Residue_Equilibrium_Position_Txt_Files/'
CHARMM_config_path = '/home/staubj/Capstone_Files/Txt_CHARM_Files/CHARRM_FILES/'
def mag(vector):
""" Returns the magnitude of a vector """
mag_vec = math.sqrt(vector[0]**2 + vector[1]**2 + vector[2]**2)
return mag_vec
def unit_vector(vector):
""" Returns the unit vector of a vector """
mag_vec = mag(vector)
uv = vector/mag_vec
return uv
def cross_product(vector1, vector2):
""" Takes the cross product of 2 1X3 matricies """
result_x = (vector1[1]*vector2[2] - vector1[2]*vector2[1])
result_y = (vector1[2]*vector2[0] - vector1[0]*vector2[2])
result_z = (vector1[0]*vector2[1] - vector1[1]*vector2[0])
result = np.array([result_x, result_y, result_z])
return result
def spherical_coordinate_conversion_matrix(vector):
""" Converts a vector from Cartesian to Spherical coordinates """
r = ( (vector[0]**2) + (vector[1]**2) + (vector[2]**2) )**(1/2)
theta = math.atan( ( (vector[0]**2) + (vector[1]**2) )**(1/2)/vector[2] )
phi = math.atan(vector[1]/vector[0])
atom_pos_spherical = np.array([r, phi, theta])
return atom_pos_spherical
def cartesian_coordinate_conversion_matrix(r, theta, phi):
""" Converts a vector from Spherical to Cartesian coordinates """
x = r*math.sin(phi)*math.cos(theta)
y = r*math.sin(phi)*math.sin(theta)
z = r*math.cos(phi)
atom_pos_cartesian = np.array([x, y,z])
return atom_pos_cartesian
def ders(t, y):
""" Ders function used in scipy.integrate.ode to calculate the
accelerations of all of the atoms based on forces due to the
different potential terms """
vals[:] = y
for mol in molecule.all_molecules:
mol.clear_all_counted()
index = len(y)//7
dvals = np.empty((len(y)))
dvals[0:3*index] = y[3*index:6*index]
""" Update all the forces """
for at in atom.all_atoms:
at.force[:] = 0.0
for mol in molecule.all_molecules:
mol.get_all_forces()
for lennard_pair in lennard_jones.all_lennard_jones_pairs:
lennard_pair.atom1_force_counted = False
lennard_pair.atom2_force_counted = False
for lennard_pair in lennard_jones.all_lennard_jones_pairs:
if lennard_pair.atom1_force_counted == False and lennard_pair.atom2_force_counted == False:
lennard_pair.lennard_jones_force()
for sparky_pair in electrostatic.all_electrostatic_pairs:
sparky_pair.atom1_force_counted = False
sparky_pair.atom2_force_counted = False
for sparky_pair in electrostatic.all_electrostatic_pairs:
if sparky_pair.atom1_force_counted == False and sparky_pair.atom2_force_counted == False:
sparky_pair.electrostatic_force()
""" Get the accelerations in dvals for any atom to go outside the specified boundary.
This also accounts of the work that is done by the boundary, which is approimated
as many stiff springs. """
vindex = 3*len(dvals)//7
windex = 6*len(dvals)//7
for mol in molecule.all_molecules:
for at in mol.atoms:
outside = False
distance_vec = at.pos
distance_mag = mag(distance_vec)
distance_unit_vec = distance_vec / distance_mag
if distance_mag - simulation.boundary > 0.0:
outside = True
if outside == False:
dvals[vindex:vindex+3] = at.force/at.mass - y[vindex:vindex+3] * molecule.dampening_coef/at.mass
dvals[windex] = - molecule.dampening_coef * np.square(y[vindex:vindex+3]).sum()
if outside == True:
dvals[vindex:vindex+3] = ( at.force/at.mass - y[vindex:vindex+3] * molecule.dampening_coef/at.mass
- abs(distance_mag - simulation.boundary) * simulation.stiffness_coefficient/at.mass
* distance_unit_vec )
dvals[windex] = ( - molecule.dampening_coef * np.square(y[vindex:vindex+3]).sum()
- abs(distance_mag - simulation.boundary) * simulation.stiffness_coefficient *
( distance_unit_vec[0] * y[vindex] +
distance_unit_vec[1] * y[vindex + 1] +
distance_unit_vec[2] * y[vindex + 2] ) )
vindex += 3
windex += 1
return dvals
#############################################################################################################################
class simulation():
""" Simulation class to contain parameters and run variables about the things for the simulation
This class does the following things:
1.) initialize_CHARMM_Values: Initializes program by reading values from the modified CHARRM
file produced using Read_Residue_Data_File.py. This assigns
all necessary constants for each specific bond, bond angle,
dihedral, and lennard-jones pair. All electrostatic terms are
constant and fixed in the electrostatic class.
2.) update_energies: Calculates the instananeous potential energy and kinetic energy
of the system as well as the work done by the viscous fluid and
'squishy sphere' boundary if True. Values for instantaneous
potential, kinetic energy, and total energy are appended to lists
of values over time. Resets instantaneous class attributes for
potential energy, kinetic energy, and work at the end.
3.) visualize: If called, creates an instance of the visual classes for all bonds and
atoms in the molecules in the class list molecules.
4.) graph_energy_conservation: Uses matplotlib to create a plot with three subplots:
total energy and work, total energy plus work, and potential
and kinetic energy with repsect to time. If save image == True,
creates SVG file with hardcoded title in current directory.
5.) get_potential: After reseting class attribute potential_energy to 0, calculates the potential
in the molecules in class list molecules due to lennard-jones pairs, electrostatic
pairs, bonds, bond angles, and dihedrals.
6.) get_kinetic_energy: After reseting class attriute kinetic_energy to 0, calculates the kinetic
energy of all of the molecules in the class list molecules.
7.) get_work: For all atoms in molecules in class list molecule, add all the works done by the atoms
in the time step to the class attribute work. Also, add the value to the class
attribute total_work.
8.) hydrate: Randomly adds water to the simulation. The function only if by adding the water to the
simulation, the potential does not increase by a large hardcoded value. This function
randomly makes water molecules inside the sphere and randomly rotates them usnig Scipy.
9.) print_final_positions: Print final positions of all atoms in all molecules in class list molecule.
Also, print the atoms bonded to each other by atom index as well as element
type.
"""
boundary = 0
radius = 0
stiffness_coefficient = 0
def __init__(self, squishy_sphere = False, radius = 100.0, stiffness = 1E5):
if squishy_sphere == True:
if radius == 100.0:
raise Exception('If you want a boundary, you need to enter a radius!')
if stiffness == 0.0:
raise Exception('If you want a boundary, you need to determine a stiffness!')
simulation.boundary = radius
simulation.radius = radius
simulation.stiffness_coefficient = stiffness
if squishy_sphere == False:
simulation.boundary = 1E6
simulation.radius = 1E6
simulation.stiffness_coefficient = 0.0
self.initialize_CHARMM_values()
self.molecules = []
self.potential_energy = 0.0
self.kinetic_energy = 0.0
self.work = 0.0
self.total_work = 0.0
self.times = []
self.kinetic_energies = []
self.potential_energies = []
self.total_energies = []
self.works = []
self.total_works = []
self.energy_plus_total_work = []
def initialize_CHARMM_values(self):
os.chdir(CHARMM_config_path)
file = open('Formatted_CHARMM_File.txt', 'r')
lines = file.readlines()
for line in lines:
if line[1:6] == 'BONDS':
bond_start_line = lines.index(line) + 2
if line [1:12] == 'BOND_ANGLES':
bond_end_line = lines.index(line) - 2
bond_angle_start_line = lines.index(line) + 2
if line[1:10] == 'Dihedrals':
bond_angle_end_line = lines.index(line) - 2
dihedral_start_line = lines.index(line) + 2
if line[1:8] == 'Lennard':
dihedral_end_line = lines.index(line) - 2
lennard_jones_start_line = lines.index(line) + 2
lennard_jones_end_line = len(lines)
for line in lines[bond_start_line: bond_end_line]:
values = line.split('\t')
index = str(values[0] + '-' + values[1])
bond.k_bond[index] = float(values[2]) * energy_conversion_factor
bond.E0_bond[index] = float(values[3])
for line in lines[bond_angle_start_line: bond_angle_end_line]:
values = line.split('\t')
index = str(values[0] + '-' + values[1] + '-' + values[2])
bond_angle.k_bond_angle[index] = float(values[3]) * energy_conversion_factor
bond_angle.bond_angle[index] = float(values[4]) * math.pi/180
for line in lines[dihedral_start_line: dihedral_end_line]:
values = line.split('\t')
index = str(values[0] + '-' + values[1] + '-' + values[2] + '-' + values[3])
dihedral.k_chi[index] = float(values[4]) * energy_conversion_factor
dihedral.n[index] = int(values[5])
dihedral.delta[index] = float(values[6])
for line in lines[lennard_jones_start_line: lennard_jones_end_line]:
values = line.split('\t')
index = str(values[0])
lennard_jones.epsilon_i[index] = float(values[1]) * energy_conversion_factor
lennard_jones.r_min_i[index] = float(values[2])
def update_energies(self):
self.get_potential()
self.get_kinetic_energy()
self.get_work()
self.total_energy = self.kinetic_energy + self.potential_energy
self.potential_energies.append(self.potential_energy)
self.kinetic_energies.append(self.kinetic_energy)
self.total_energies.append(self.total_energy)
self.works.append(-self.work)
self.total_works.append(-self.total_work)
self.energy_plus_total_work.append(self.total_energy - self.work)
self.potential_energy = 0.0
self.kinetic_energy = 0.0
self.work = 0.0
def visualize(self):
for molecule in self.molecules:
for atom in molecule.atoms:
visual(atom)
for bond in molecule.bonds:
visual(bond)
def graph_energy_conservation(self, save_image = False):
fig, ax = plt.subplots( 1, 3, sharex = True, sharey = True, figsize = (16, 9))
ax[0].plot(self.times, self.total_energies, label = 'Total Energy', color = 'r')
ax[0].plot(self.times, self.works, label = 'Total_Work', color = 'b')
ax[2].plot(self.times, self.potential_energies, label = 'Potential Energy', color = 'm')
ax[2].plot(self.times, self.kinetic_energies, label = 'Kinetic Energy', color = 'c')
ax[1].plot(self.times, self.energy_plus_total_work, label = 'Total Energy + Work', color = '#4F0066')
ax[2].legend()
ax[0].legend()
ax[2].set_ylabel('Energy (eV)')
ax[0].set_ylabel('Energy (eV)')
ax[2].set_xlabel('Time (Jake Seconds)')
ax[1].set_ylabel('Energy (eV)')
ax[0].set_title('Work and Energy')
ax[1].set_title('Total Energy Plus Work')
ax[2].set_title('Potential and Kinetic Energy')
fig.show()
plt.show()
if save_image == True:
fig.savefig('Alanine_Stabilization_Energy_Diagram.svg', type = '.svg' )
def get_potential(self):
self.potential_energy = 0.0
for lennard_pair in lennard_jones.all_lennard_jones_pairs:
lennard_pair.atom1_potential_counted = False
lennard_pair.atom2_potential_counted = False
for sparky_pair in electrostatic.all_electrostatic_pairs:
sparky_pair.atom1_potnetial_counted = False
sparky_pair.atom2_potential_counted = False
for molecule in self.molecules:
for bond in molecule.bonds:
self.potential_energy += bond.bond_potential()
for bond_angle in molecule.bond_angles:
self.potential_energy += bond_angle.bond_angle_potential()
for dihedral in molecule.dihedrals:
self.potential_energy += dihedral.dihedral_potential()
for lennard_pair in lennard_jones.all_lennard_jones_pairs:
if lennard_pair.atom1_potential_counted == False and lennard_pair.atom2_potential_counted == False:
self.potential_energy += lennard_pair.lennard_jones_potential()
for sparky_pair in electrostatic.all_electrostatic_pairs:
if sparky_pair.atom1_potential_counted == False and sparky_pair.atom2_potential_counted == False:
self.potential_energy += sparky_pair.electrostatic_potential()
def get_kinetic_energy(self):
self.kinetic_energy = 0.0
for molecule in self.molecules:
for atom in molecule.atoms:
self.kinetic_energy += 0.5 * atom.mass * mag(atom.vel)**2
def get_work(self):
for molecule in self.molecules:
for atom in molecule.atoms:
self.work += atom.work[0]
self.total_work += atom.work[0]
def hydrate(self, number_of_water):
water_theta = 104.5/(2 * math.pi)
l0 = 0.96
waters_added = 0
attempt_to_add_water = 0
while waters_added < number_of_water:
x = random.uniform(-1,1)
y = random.uniform(-1,1)
z = random.uniform(-1,1)
random_pos = np.array([x,y,z])
mag_r = mag(random_pos)
unit_pos = random_pos / mag_r
random_position = unit_pos * random.uniform(0.1, 0.80 * simulation.boundary)
water_one = molecule()
O1 = atom( atom_number = 3, element = 'oxygen' , element_type = 'OT', x0 = random_position[0], y0 = random_position[1], z0 = random_position[2], test = True )
H1 = atom( atom_number = 1, element = 'hydrogen', element_type = 'HT', test = True )
H2 = atom( atom_number = 1, element = 'hydrogen', element_type = 'HT', test = True )
H2.pos = np.array([math.sin(water_theta/2)*l0, math.cos(water_theta/2)*l0, 0])
H1.pos = np.array([-math.sin(water_theta/2)*l0, math.cos(water_theta/2)*l0, 0])
rotation_theta = random.uniform(0, 2 * math.pi)
random_vec = np.random.random(3)
mag_v = mag(random_vec)
rotation_vector = random_vec / mag_v
r = R.from_rotvec( rotation_theta * rotation_vector )
r.as_matrix()
H1.pos = r.apply(H1.pos)
H2.pos = r.apply(H2.pos)
H1.pos += O1.pos
H2.pos += O1.pos
self.get_potential()
initial_potential = self.potential_energy
self.potential_energy = 0.0
for pair in testing_potentials.all_test_lennard_jones_pairs:
self.potential_energy += lennard_jones.lennard_jones_potential(pair)
for pair in testing_potentials.all_test_electrostatic_pairs:
self.potential_energy += electrostatic.electrostatic_potential(pair)
# print(initial_potential, abs(self.potential_energy - initial_potential))
# sys.exit(20)
if abs(self.potential_energy - initial_potential) < 1.25 * initial_potential: #should I actually hard code this?
water_one.add_atom(H1)
water_one.add_atom(H2)
water_one.add_atom(O1)
for water_atom in water_one.atoms:
for specific_atom in atom.all_atoms:
lennard_jones(water_atom, specific_atom)
for water_atom in water_one.atoms:
visual(water_atom)
atom.all_atoms.append(water_atom)
water_one.bond_atoms(H1, O1, 1)
water_one.bond_atoms(H2, O1, 1)
self.molecules.append(water_one)
waters_added += 1
attempt_to_add_water += 1
else:
atoms_to_remove = [O1, H1, H2]
testing_potentials.remove_atoms(atoms_to_remove)
attempt_to_add_water += 1
print(" Hydration Status : {:.1f}% | Attempt # : {}".format(waters_added/number_of_water * 100, attempt_to_add_water))
initial_potential = 0.0
self.potential_energy = 0.0
def print_final_positions(self, name):
os.chdir(Simulation_config_path)
file = open('{}.txt'.format(str(name)), 'w')
file.write('#### Final MD Simulation Positions ####')
file.write('#\n#\n')
file.write('#Atom_Number:\tAtom_type:\tAtom_Element:\tPosition[x,y,z]:\n')
for molecule in self.molecules:
for atom in molecule.atoms:
file.write(str(atom.atom_number))
file.write('\t')
file.write(str(atom.element_type))
file.write('\t')
file.write(str(atom.element))
file.write('\t')
file.write(str(atom.pos[0]))
file.write('\t')
file.write(str(atom.pos[1]))
file.write('\t')
file.write(str(atom.pos[2]))
file.write('\n')
file.write('\n#Bonds Formed:\n\n')
file.write('# Atom #1 - Atom #2: Bond Order:\n\n')
for molecule in self.molecules:
for bond in molecule.bonds:
file.write(str(bond.atom1.atom_number))
file.write('-')
file.write(str(bond.atom2.atom_number))
file.write('\t')
file.write(str(bond.number_of_bonds))
file.write('\n')
file.close()
class testing_potentials:
"""
"""
Time_Unit = ( (1.66054E-27) * (1E-10)**2 / 1.602E-18 ) ** (1/2)
Special_Epsilon = (6.2415E18)**2 * (1/Time_Unit)**2 / ( (1E-10)**3 * (1.66054E-27) )
K = 1 / ( 4 * math.pi * Special_Epsilon)
all_test_atoms = []
all_test_lennard_jones_pairs = []
all_test_electrostatic_pairs = []
epsilon_i = { 'CC33A' : -0.0780 * (2.611E22/6.022E23) ,
'HCA3A' : -0.0240 * (2.611E22/6.022E23) ,
'HT' : -0.046 * (2.611E22/6.022E23) ,
'HCA2A' : -0.0350 * (2.611E22/6.022E23) ,
'CC32A' : -0.0560 * (2.611E22/6.022E23) ,
'OT' : -0.1521 * (2.611E22/6.022E23) ,
'CT1' : -0.2000 * (2.611E22/6.022E23) ,
'CT3' : -0.0800 * (2.611E22/6.022E23) ,
'NH1' : -0.2000 * (2.611E22/6.022E23) ,
'C' : -0.1100 * (2.611E22/6.022E23) ,
'H' : -0.0460 * (2.611E22/6.022E23) ,
'HB' : -0.0220 * (2.611E22/6.022E23) ,
'O' : -0.1200 * (2.611E22/6.022E23) ,
'HA' : -0.0220 * (2.611E22/6.022E23) }
r_min_i = { 'CC33A' : 2.0400 ,
'HCA3A' : 1.3400 ,
'HT' : 0.2245 ,
'HCA2A' : 1.3400 ,
'CC32A' : 2.0100 ,
'OT' : 1.7682 ,
'CT1' : 2.2750 ,
'CT3' : 2.0600 ,
'NH1' : 1.8500 ,
'C' : 2.0000 ,
'H' : 0.2245 ,
'HB' : 1.3200 ,
'O' : 1.7000 ,
'HA' : 1.3200 }
charge = { 'CT3' : -0.27,
'HA' : 0.09,
'C' : 0.51,
'O' : -0.51,
'NH1' : -0.47,
'H' : 0.31,
'CT1' : 0.07,
'HB' : 0.09,
'OT' : -0.834,
'HT' : 0.417 }
def __init__(self, atom_1, atom_2, interaction_type = 'lennard-jones'):
self.interaction_type = interaction_type
self.atom1 = atom_1
self.atom2 = atom_2
if self.interaction_type == 'lennard-jones':
self.atom1_potential_counted = False
self.atom1_force_counted = False
self.atom2_potential_counted = False
self.atom2_force_counted = False
self.Epsilon = (2.6114E22/6.022E23) * math.sqrt( lennard_jones.epsilon_i[atom_1.element_type] *
lennard_jones.epsilon_i[atom_2.element_type] )
self.R_min = ( lennard_jones.r_min_i[atom_1.element_type]/2 +
lennard_jones.r_min_i[atom_2.element_type]/2 )
testing_potentials.all_test_lennard_jones_pairs.append(self)
if self.interaction_type == 'electrostatic':
self.charge1 = electrostatic.charge[self.atom1.element_type]
self.charge2 = electrostatic.charge[self.atom2.element_type]
self.atom1_force_counted = False
self.atom1_potential_counted = False
self.atom2_force_counted = False
self.atom2_potenial_counted = False
testing_potentials.all_test_electrostatic_pairs.append(self)
def remove_atoms(list_of_atoms):
for atom_to_delete in list_of_atoms:
for pair in testing_potentials.all_test_lennard_jones_pairs:
if pair.atom1 or pair.atom2 == atom_to_delete:
testing_potentials.all_test_lennard_jones_pairs.remove(pair)
for pair in testing_potentials.all_test_electrostatic_pairs:
if pair.atom1 or pair.atom2 == atom_to_delete:
testing_potentials.all_test_electrostatic_pairs.remove(pair)
testing_potentials.all_test_atoms.remove(atom_to_delete)
class atom:
all_atoms = []
masses = { 'hydrogen' : 1,
'oxygen' : 16,
'carbon' : 12,
'nitrogen' : 10 }
potential_bonds = { 'hydrogen' : 1,
'oxygen' : 2,
'carbon' : 4,
'nitrogen' : 3 }
def __init__(self, element, element_type = 'None Assigned', charge = None, molecule = None, atom_number = 0,
x0 = 0., y0 = 0., z0 = 0., vx0 = 0., vy0 = 0., vz0 = 0., test = False):
self._pos = np.array([x0, y0, z0])
self._vel = np.array([vx0, vy0, vz0])
self._work = np.zeros(1)
self.element = element
self.mass = atom.masses[self.element]
self.atom_number = atom_number
self.molecule = molecule
self.element_type = element_type
self.charge = charge
self.force = np.zeros(3)
self.potential_bonds = atom.potential_bonds[self.element]
self.bonds = []
self.test = test
if len(atom.all_atoms) > 1:
for specific_atom in atom.all_atoms:
if self.test == False:
lennard_jones(self, specific_atom)
electrostatic(self, specific_atom)
testing_potentials(atom_1 = self, atom_2 = specific_atom, interaction_type = 'lennard-jones')
testing_potentials(atom_1 = self, atom_2 = specific_atom, interaction_type = 'electrostatic')
if self.test == True:
testing_potentials(atom_1 = self, atom_2 = specific_atom, interaction_type = 'lennard-jones')
testing_potentials(atom_1 = self, atom_2 = specific_atom, interaction_type = 'electrostatic')
# if self.test == False and self.visualize == True:
# visual(self)
if self.test == False:
atom.all_atoms.append(self)
testing_potentials.all_test_atoms.append(self)
def move_data_to_buffers(self, posbuffer, velbuffer, workbuffer):
pos = self._pos.copy()
vel = self._vel.copy()
work = self._work.copy()
self._pos = np.frombuffer(posbuffer)
self._vel = np.frombuffer(velbuffer)
self._work = np.frombuffer(workbuffer)
self._pos[:] = pos
self._vel[:] = vel
self._work[:] = work
@property
def pos(self):
return self._pos
@pos.setter
def pos(self, value):
self._pos[:] = value
@property
def vel(self):
return self._vel
@vel.setter
def vel(self, value):
self._vel[:] = value
@property
def work(self):
return self._work
@work.setter
def work(self, value):
self._work[:] = value
class molecule():
dampening_coef = 0.7 # I typically use 1.0 for 'good' results
all_molecules = []
atom_number = 0
def __init__(self):
self.atoms = []
self.bonds = []
self.bond_angles = []
self.dihedrals = []
self.array_packing_offset = 0
molecule.all_molecules.append(self)
def add_atom(self, atom):
self.atoms.append(atom)
atom.molecule = self
def bond_atoms(self, atom1, atom2, multiplicity):
if not atom1 in self.atoms:
raise Exception("I ain't got {}, atom number {}. Try molecule {}".format(atom2.element, atom2.atom_number, atom2.molecule))
if not atom2 in self.atoms:
raise Exception("I ain't got {}, atom number {}. Try molecule {}".format(atom2.element, atom2.atom_number, atom2.molecule))
new_bond = bond(atom1, atom2, number_of_bonds = multiplicity)
new_dihedrals_maybe = False
for other_bond in self.bonds:
if atom1 == other_bond.atom1 or atom1 == other_bond.atom2:
new_bond_angle = bond_angle(other_bond, new_bond)
new_dihedrals_maybe = True
self.bond_angles.append(new_bond_angle)
if atom2 == other_bond.atom1 or atom2 == other_bond.atom2:
new_bond_angle = bond_angle(other_bond, new_bond)
new_dihedrals_maybe = True
self.bond_angles.append(new_bond_angle)
if new_dihedrals_maybe == True:
for other_bond_angle in self.bond_angles:
bond_angle_1 = new_bond_angle.ordered_list_of_atoms()
bond_angle_2 = other_bond_angle.ordered_list_of_atoms()
center_atom_1 = bond_angle_1[1]
center_atom_2 = bond_angle_2[1]
if center_atom_1 != center_atom_2:
if new_bond_angle.bond1 == other_bond_angle.bond1 or new_bond_angle.bond1 == other_bond_angle.bond2:
new_dihedral = dihedral(other_bond_angle, new_bond_angle)
self.dihedrals.append(new_dihedral)
elif new_bond_angle.bond2 == other_bond_angle.bond1 or new_bond_angle.bond2 == other_bond_angle.bond2:
new_dihedral = dihedral(other_bond_angle, new_bond_angle)
self.dihedrals.append(new_dihedral)
new_dihedrals_maybe = False
self.bonds.append(new_bond)
def clear_all_counted(self):
for bon in self.bonds:
bon.counted = False
for bangle in self.bond_angles:
bangle.counted = False
for dangle in self.dihedrals:
dangle.counted = False
def get_all_forces(self):
""" Takes a molecule and calculates all bond and bond angle
forces for all of the atoms in the molecule. """
""" Set all the forces on all of the atoms to 0 """
for at in self.atoms:
at.force[:] = 0.
""" Bond Forces """
for specific_bond in self.bonds:
if specific_bond.counted == False:
specific_bond.bond_force()
""" Bond Angle Forces """
for specific_bond_angle in self.bond_angles:
if specific_bond_angle.counted == False:
specific_bond_angle.bond_angle_force()
""" Dihedral Forces """
for specific_dihedral in self.dihedrals:
if specific_dihedral.counted == False:
specific_dihedral.dihedral_force()
""" Lennard Jones Forces :
Not calculated here. Calculated in ders function. """
# for specific_atom in self.atoms:
# for specific_lennard_jones_pair in lennard_jones.all_lennard_jones_pairs:
# if specific_atom == specific_lennard_jones_pair.atom1 and specific_lennard_jones_pair.atom1_force_counted == False:
# forces = specific_lennard_jones_pair.lennard_jones_force()
# specific_lennard_jones_pair.atom1.force += forces[0]
# specific_lennard_jones_pair.atom1_force_counted = True
# if specific_atom == specific_lennard_jones_pair.atom2 and specific_lennard_jones_pair.atom2_force_counted == False:
# forces = specific_lennard_jones_pair.lennard_jones_force()
# specific_lennard_jones_pair.atom2.force += forces[1]
# specific_lennard_jones_pair.atom2_force_counted = True
""" Electrostatic Potential Forces :
Not calculated here. Calculated in ders function. """
# for specific_atom in self.atoms:
# for specific_electrostatic_pair in electrostatic.all_electrostatic_pairs:
# if specific_atom == specific_electrostatic_pair.atom1:
# forces = electrostatic.electrostatic_force(specific_electrostatic_pair)
# specific_electrostatic_pair.atom1.force += forces[0]
# if specific_atom == specific_electrostatic_pair.atom2:
# forces = electrostatic.electrostatic_force(specific_electrostatic_pair)
# specific_electrostatic_pair.atom2.force += forces[1]
class bond:
k_bond = {} #(eV/A^2)
E0_bond = {} #angstroms
def __init__(self, atom1, atom2, counted = False, number_of_bonds = 1):
self.atom1 = atom1
self.atom2 = atom2
if self.atom1.potential_bonds < len(self.atom1.bonds):
print('A {} is going to be bonded to {} other atoms.'.format(self.atom1.element, len(self.atom1.bonds + 1)))
if self.atom2.potential_bonds < len(self.atom2.bonds):
print('A {} is going to be bonded to {} other atoms.'.format(self.atom2.element, len(self.atom2.bonds + 1)))
self.counted = counted
self.number_of_bonds = number_of_bonds
atom1.bonds.append(self)
atom2.bonds.append(self)
try:
self.k_bond = bond.k_bond["{}-{}".format(self.atom1.element_type, self.atom2.element_type)]
except:
self.k_bond = bond.k_bond["{}-{}".format(self.atom2.element_type, self.atom1.element_type)]
finally:
if self.k_bond == None:
sys.stderr.write('Unable to find a bond spring coefficient for atoms : {}-{}, atom numbers : {}-{}, and element types : {}-{}'.format(self.atom1.element, self.atom2.element,
self.atom1.atom_number, self.atom2.atom_number,
self. atom1.element_type, self.atom2.element_type))
try:
self.E0_bond = bond.E0_bond["{}-{}".format(self.atom1.element_type, self.atom2.element_type)]
except:
self.E0_bond = bond.E0_bond["{}-{}".format(self.atom2.element_type, self.atom1.element_type)]
finally:
if self.k_bond == None:
sys.stderr.write('Unable to find a equilibrium bond lengths for atoms : {}-{}, atom numbers : {}-{}, and element types : {}-{}'.format(self.atom1.element, self.atom2.element,
self.atom1.atom_number, self.atom2.atom_number,
self.atom1.element_type, self.atom2.element_type))
# if self.atom1.visualize == True and self.atom2.visualize == True:
# visual(self)
def bond_potential(self):
""" Calculates and returns bond potential """
distance = mag(self.atom2.pos - self.atom1.pos)
potential = 0.5 * self.k_bond * (distance - self.E0_bond)**2
return potential
def bond_force(self):
""" Calculates the spring bond potential and returns dU """
r_vec = (self.atom2.pos - self.atom1.pos)
r_hat = r_vec/mag(r_vec)
dU = self.k_bond * (mag(r_vec) - self.E0_bond)
Force_1 = dU * r_hat
Force_2 = -1 * Force_1
self.atom1.force += Force_1
self.atom2.force += Force_2
self.atom1.counted = True
self.atom2.counted = True
class bond_angle:
k_bond_angle = {} #(eV/rad^2)
bond_angle = {} #radians
def __init__(self, bond1, bond2, counted = False):
self.bond1 = bond1
self.bond2 = bond2
self.counted = counted
if bond1.atom1 != bond2.atom1 and bond1.atom1 != bond2.atom2 and bond1.atom2 != bond2.atom1 and bond1.atom2 != bond2.atom2:
raise Exception('You fuckin\' dooftard. These bonds do not have a common atom!')
typedex_list = bond_angle.ordered_list_of_atoms(self)
self.start_atom = typedex_list[0]
self.middle_atom = typedex_list[1]
self.end_atom = typedex_list[2]
self.typedex = "{}-{}-{}".format(self.start_atom.element_type,
self.middle_atom.element_type,
self.end_atom.element_type)
self.reverse_typedex = "{}-{}-{}".format(self.end_atom.element_type,
self.middle_atom.element_type,
self.start_atom.element_type)
if self.typedex in bond_angle.k_bond_angle:
self.k_bond_angle = bond_angle.k_bond_angle[self.typedex]
elif self.reverse_typedex in bond_angle.k_bond_angle:
if self.typedex != self.reverse_typedex:
self.k_bond_angle = bond_angle.k_bond_angle[self.reverse_typedex]
else:
sys.stderr.write('Unable to find a bond angle spring coefficient for atoms : {}-{}-{}, atom numbers : {}-{}-{}, and element types : {}-{}-{}\n\n'.format(self.start_atom.element, self.middle_atom.element, self.end_atom.element,
self.start_atom.atom_number, self.middle_atom.atom_number, self.end_atom.atom_number,
self.start_atom.element_type, self.middle_atom.element_type, self.end_atom.element_type))
if self.typedex in bond_angle.bond_angle:
self.bond_angle0 = bond_angle.bond_angle[self.typedex]
elif self.reverse_typedex in bond_angle.bond_angle:
if self.typedex != self.reverse_typedex:
self.bond_angle0 = bond_angle.bond_angle[self.reverse_typedex]
else:
sys.stderr.write('Unable to find a bond angle equilibrium angle for atoms : {}-{}-{}, atom numbers : {}-{}-{}, and element types : {}-{}-{}\n\n'.format(self.start_atom.element, self.middle_atom.element, self.end_atom.element,
self.start_atom.atom_number, self.middle_atom.atom_number, self.end_atom.atom_number,
self.start_atom.element_type, self.middle_atom.element_type, self.end_atom.element_type))
sys.exit(20)
def ordered_list_of_atoms(self):
""" Determines which atom in a pair of bonds
( so a bond angle) is the central atom. This is used
to eliminate the possibility of redundnacy and overcounting
forces """
if self.bond1.atom1 == self.bond2.atom1:
center_atom = self.bond1.atom1
atom1 = self.bond1.atom2
atom3 = self.bond2.atom2