-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPolymer_brush_umbrella_sampling.py
2570 lines (1974 loc) · 101 KB
/
Polymer_brush_umbrella_sampling.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
#obtain an estimate for the z dependence of the charge distribution.
from __future__ import print_function
import espressomd
from espressomd import code_info
from espressomd import analyze
from espressomd.interactions import *
from espressomd import electrostatics
from espressomd.io.writer import h5md # pylint: disable=import-error
from espressomd import shapes
#from espressomd import reaction_ensemble
import espressomd.reaction_methods
import espressomd.accumulators
import espressomd.observables
import espressomd.polymer
import espressomd.visualization
import math
import matplotlib.pyplot as plt
import random
import numpy as np
from scipy.optimize import newton
import h5py
from scipy import interpolate
#from statistic import *
#from espressomd import visualization
#import matplotlib.pyplot as plt
import sys
import gzip
import pickle
import os
import time
"""
from __future__ import print_function
import espressomd
import espressomd.analyze
import espressomd.electrostatics
import espressomd.observables
import espressomd.accumulators
import espressomd.math
import espressomd.polymer
import espressomd.reaction_methods
from scipy import interpolate
espressomd.assert_features(['ELECTROSTATICS', 'P3M', 'WCA'])
import tqdm
import numpy as np
import scipy.optimize
import matplotlib.pyplot as plt
"""
#conversion_factor_from_1_per_sigma_3_to_mol_per_l=37.11711304995093
sigma = 3.55e-10 # Sigma in SI units
avo = 6.022e+23 # Avogadro's number in SI units
conversion_factor_from_1_per_sigma_3_to_mol_per_l = 1/(10**3 * avo * sigma**3) # Prefactor to mol/L
print("conversion_factor_from_1_per_sigma_3_to_mol_per_l", conversion_factor_from_1_per_sigma_3_to_mol_per_l )
temperature = 1.0
beta=1.0/temperature
pH_desired=7
pH=pH_desired
#>>>>>>>>>>>>>>>>>>>>>.Problems in this code that msut clarify with David<<<<<<<<<<<<
#1. Why for pH=7 I am not getting cH/cOH order of 10^-14
#2. Imposed cHA infinetesimally low , so one of H2A and A is infinetesimally low too
#3. ONes again confirm if all concentrations and other units taken properly in bulk units not mol_per_l
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#cs_bulk=0.000016
c_poly_mol_per_L=0.01#0.15 # Why some reaction runs are depending on this check
c_poly=c_poly_mol_per_L/conversion_factor_from_1_per_sigma_3_to_mol_per_l
cs_mol_per_L=0.001
cs_bulk=cs_mol_per_L/conversion_factor_from_1_per_sigma_3_to_mol_per_l
Kw=10**-14 #dimensionless dissociation constant Kw=relative_activity(H)*relative_activity(OH)
cref_in_mol_per_l=1.0 #in mol/l
cH_bulk_in_mol_per_l=10**(-pH)*cref_in_mol_per_l #this is a guess, which is used as starting point of the self consistent optimization, will be modified for a desired pH at a certain salt concentration anyway.
#cs_bulk=input_from_file
pKA =4.0 #8.3-13.3
KA = np.exp((np.log(10))*-pKA)#pKA = log10(KA)
Kcideal_in_mol_per_l=KA*cref_in_mol_per_l
#cA_bulk = 0.00016# in units of 1/sigma3
pka=8.0
#8.3-13.3
ka = np.exp((np.log(10))*-pka)#pKA = log10(KA)
pkb=-7.0
#8.3-13.3
kb = np.exp((np.log(10))*-pkb)#pKA = log10(KA)
c0_in_mol_per_l =0#0.001#(10*cs_mol_per_L)#0.01
#box_length = disputed
"""
|__________________________________________________Determine Bulk concentrations self consistently____________________________|
|_____________________________________________________________________________________________________________________________|
Form a bulk ionic composition constituting {Na+, Cl-,H+, OH-} imposing electroneutrality of the reservoir. Take [H+] and an
initial salt concentration as inputs then from this Kw=[H+][OH-] get [OH-]; electroneutrality gives [Na+] and [Cl-] . Since inputs
are in mol/L. We want all in 1/sigma3.
"""
#conversion_factor_from_1_per_sigma_3_to_mol_per_l=37.1
def determine_bulk_concentrations_selfconsistently(arg_cH_bulk , arg_gamma_res):
#Globally read
global Kw, cref_in_mol_per_l, conversion_factor_from_1_per_sigma_3_to_mol_per_l, pH, pka, pkb
global cref_sim, c0_sim
# Globally edited
global cHA_bulk, cH2A_bulk, cA_bulk, cNa_bulk, cCl_bulk, cOH_bulk, cH_bulk
global cH_bulk_in_mol_per_l, gamma_res
gamma_res = arg_gamma_res
cH_bulk = arg_cH_bulk
cH_bulk_in_mol_per_l = cH_bulk*conversion_factor_from_1_per_sigma_3_to_mol_per_l
cOH_bulk=(Kw/(cH_bulk_in_mol_per_l/cref_in_mol_per_l))*cref_in_mol_per_l/conversion_factor_from_1_per_sigma_3_to_mol_per_l
FAC1 = ((10**(-pkb))*(cH_bulk/cref_sim)) + 1
cA_bulk = c0_sim / ((gamma_res*FAC1*(cH_bulk/cref_sim)*(10**pka)) + 1)
cH2A_bulk = c0_sim - (cA_bulk * ((1.0/((10**(-pka)) * (cref_sim/cH_bulk) * (gamma_res**(-1))))+1))
cHA_bulk = c0_sim - cH2A_bulk - cA_bulk
# print("\n After >> \n FAC - ", FAC1, "\n cH_bulk - ",cH_bulk, "\n gamma_res -", gamma_res, "\n c0_sim - ", c0_sim, "\n cA_bulk = (ka*cHA_bulk)/(gamma_res*cH_bulk) - ", cA_bulk, "\n cH2A_bulk = kb*cHA_bulk*cH_bulk - ", cH2A_bulk, cA_bulk * ((1.0/((10**(-pka)) * (cref_sim/cH_bulk) * (gamma_res**(-1))))+1), ((gamma_res*FAC1*(cH_bulk/cref_sim)*(10**pka)) + 1))
if((cOH_bulk+cA_bulk)>=(cH_bulk+cH2A_bulk)):
cNa_bulk=cs_bulk+(cOH_bulk+cA_bulk-cH_bulk-cH2A_bulk)
cCl_bulk=cs_bulk
else:
cCl_bulk=cs_bulk+(cH_bulk+cH2A_bulk-cOH_bulk-cA_bulk)
cNa_bulk=cs_bulk
return np.array([cH_bulk, cOH_bulk, cNa_bulk, cCl_bulk, cH2A_bulk, cHA_bulk, cA_bulk])
"""____________________________________________________________________________________________________________________________|
_______________________________________________________________________________________________________________________________|
"""
"""
|_______________________________________Recursion to converge pH of reservoir to the desired value_____________________________|
|______________________________________________________________________________________________________________________________|
pH = -(1/ln10). ln(C_H+/C_ref) - (1/ln10).(\bta\mu_{H+}/2)
pH = -log_10{(C_H+/C_ref)*exp(\bta\mu_{H+}/2)}
here;
\mu_{H+} is a function of ionic strength I_res(current_concentrations) of the reservoir
"""
#/tikhome/keerthirk/keerthi_ICP/worksheets_david/scripts/widom_insertion
print('entered')
# Here, ionic strength is in bulk units (1/sigma^3) and so is other values
ionic_strength, excess_chemical_potential_monovalent_pairs_in_bulk_data ,value_of_lB ,excess_chemical_potential_monovalent_pairs_in_bulk_data_error =np.loadtxt("/tikhome/keerthirk/espresso/build_new/test-for-PE_brush/new/excess_chemical_potential_david_lB2_uncommented.dat", unpack=True)
excess_chemical_potential_monovalent_pairs_in_bulk=interpolate.interp1d(ionic_strength, excess_chemical_potential_monovalent_pairs_in_bulk_data)
# ((((((( IDEAL CASE CHANGE )))))))))))
#def excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk):
# return 0
max_self_consistent_runs=200
self_consistent_run=0
def calculate_alphas_self_consistently(arg_pH, arg_cs_mol_per_L, arg_c0_in_mol_per_l, arg_pka, arg_pkb):
global cs_mol_per_L, cs_bulk, c0_in_mol_per_L, c0_sim, pH, pka, pkb
global cH_bulk_in_mol_per_l
global cNa_bulk, cCl_bulk, cOH_bulk, cH_bulk, cH2A_bulk, cHA_bulk, cA_bulk, ionic_strength_bulk
global Kw, cref_in_mol_per_l, cref_sim,conversion_factor_from_1_per_sigma_3_to_mol_per_l
global determined_pH
cs_mol_per_L = arg_cs_mol_per_L
c0_in_mol_per_l = arg_c0_in_mol_per_l
pH = arg_pH
pka = arg_pka
pkb = arg_pkb
cs_bulk=cs_mol_per_L/conversion_factor_from_1_per_sigma_3_to_mol_per_l
cref_sim = cref_in_mol_per_l/conversion_factor_from_1_per_sigma_3_to_mol_per_l
c0_sim = c0_in_mol_per_l/conversion_factor_from_1_per_sigma_3_to_mol_per_l
cH_bulk_in_mol_per_l=10**(-pH)*cref_in_mol_per_l #this is a guess, which is used as starting point of the self consistent optimization
cH_bulk=cH_bulk_in_mol_per_l/conversion_factor_from_1_per_sigma_3_to_mol_per_l
gamma_res = 1.0 #initially considering the ideal case
cH_bulk, cOH_bulk, cNa_bulk, cCl_bulk, cH2A_bulk, cHA_bulk, cA_bulk =determine_bulk_concentrations_selfconsistently(cH_bulk, gamma_res )
ionic_strength_bulk=0.5*(cNa_bulk+cCl_bulk+cOH_bulk+cH_bulk+cH2A_bulk+cA_bulk) #in units of 1/sigma^3
determined_pH=-np.log10(cH_bulk*conversion_factor_from_1_per_sigma_3_to_mol_per_l/cref_in_mol_per_l*np.exp((excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk) )/(2.0*temperature)))
while abs(determined_pH-pH)>1e-6:
if(determined_pH)>pH:
cH_bulk=cH_bulk*1.005
else:
cH_bulk=cH_bulk/1.003
gamma_res = np.exp((excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk) )/(1.0*temperature))
cH_bulk, cOH_bulk, cNa_bulk, cCl_bulk, cH2A_bulk, cHA_bulk, cA_bulk =determine_bulk_concentrations_selfconsistently(cH_bulk, gamma_res)
ionic_strength_bulk=0.5*(cNa_bulk+cCl_bulk+cOH_bulk+cH_bulk+cH2A_bulk+cA_bulk) #in units of 1/sigma^3
determined_pH=-np.log10(cH_bulk*conversion_factor_from_1_per_sigma_3_to_mol_per_l*np.exp((excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk) )/(2.0*temperature)))
# print(pH, determined_pH, gamma_res, ionic_strength_bulk )
# print("\n Before exiting Loop >> \n cH_bulk - ", cH_bulk, "\n cHA_bulk - ",cHA_bulk, "\n cH2A_bulk -", cH2A_bulk, "\n cOH_bulk - ", cOH_bulk, "\n cA_bulk - ", cA_bulk, "\n cNa_bulk - ", cNa_bulk, "\n cCl_bulk - ", cCl_bulk)
# print('Determined pH in NonIdeal case ', determined_pH)
return 0,0,0
# return cH2A_bulk/c0_sim, cA_bulk/c0_sim, (cA_bulk-cH2A_bulk)/(cA_bulk+cHA_bulk+cH2A_bulk)
def ideal_alpha_acid(pH, pKA):
return 1. / (1 + 10**(pKA - pH))
"""
pH_range = np.linspace(0.0, 14.0, 500)
alphas_positive = []
alphas_negative = []
alphas_net = []
for pH in pH_range:
alphas_temp = calculate_alphas_self_consistently(pH, cs_mol_per_L, c0_in_mol_per_l, pka, pkb)
alphas_positive.append(alphas_temp[0])
alphas_negative.append(alphas_temp[1])
alphas_net.append(alphas_temp[2])
#plt('font', **{'family':'serif','serif':['Helvetica']})
#plt('text', usetex=True)
plt.plot(pH_range, alphas_positive, label="base")
plt.plot(pH_range, alphas_negative, label="acid")
plt.plot(pH_range, alphas_net, label="effective")
plt.plot(pH_range, ideal_alpha_acid(pH_range, 10.0), label="acid (HH)", linestyle="dotted")
plt.xlabel('pH')
plt.ylabel('Degree of ionization ')
plt.legend()
#plt.show()
plt.savefig('alpha_ampholyte_ion_calc_self_consistent.png')
#f = open("sunil.mpc", "a")
"""
pH= pH_desired
alphas_temp = calculate_alphas_self_consistently(pH, cs_mol_per_L, c0_in_mol_per_l, pka, pkb)
print('Determined pH in NonIdeal case ', determined_pH)
print( "pH - ",pH, "\n cs_mol_per_L - ",cs_mol_per_L,"\n c0_in_mol_per_l -", c0_in_mol_per_l,"\n pka -",pka,"\n pkb - ",pkb, "\n cs_bulk - ",cs_bulk ,"\n c0_sim -",c0_sim, "\n cH_bulk - ", cH_bulk, "\n cHA_bulk - ",cHA_bulk, "\n cH2A_bulk -", cH2A_bulk, "\n cOH_bulk - ", cOH_bulk, "\n cA_bulk - ", cA_bulk, "\n cNa_bulk - ", cNa_bulk, "\n cCl_bulk - ", cCl_bulk)
#f.write("pH - ",pH, "\n cs_mol_per_L - ",cs_mol_per_L,"\n c0_in_mol_per_l -", c0_in_mol_per_l,"\n pka -",pka,"\n pkb - ",pkb, "\n cs_bulk - ",cs_bulk ,"\n c0_sim -",c0_sim, "\n cH_bulk - ", cH_bulk, "\n cHA_bulk - ",cHA_bulk, "\n cH2A_bulk -", cH2A_bulk, "\n cOH_bulk - ", cOH_bulk, "\n cA_bulk - ", cA_bulk, "\n cNa_bulk - ", cNa_bulk, "\n cCl_bulk - ", cCl_bulk)
#f.close()
#print("\n After exiting Loop >> \n cH_bulk - ", cH_bulk, "\n cHA_bulk - ",cHA_bulk, "\n cH2A_bulk -", cH2A_bulk, "\n cOH_bulk - ", cOH_bulk, "\n cA_bulk - ", cA_bulk, "\n cNa_bulk - ", cNa_bulk, "\n cCl_bulk - ", cCl_bulk)
#print(np.exp((excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk) )))
"""____________________________________________________________________________________________________________________________|
_______________________________________________________________________________________________________________________________|
"""
"""
|_______________________________________Basic concentration checks_____________________________________________________________|
|______________________________________________________________________________________________________________________________|
Checks for kw-((c_H+/c_ref).(c_OH-/c_ref).exp(2\bta\mu/2))=0 ;
sum{z_i c_i}=0 ;
pH_desired-pH_determined=0 ;
cs_salt_fixed = min(c_Na, c_cl) ;
At pH 7 conce. of H+ and OH- same ;
"""
print('Ionic strength', ionic_strength_bulk, 'value ', excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk))
#def check_concentrations():
"""
# if(abs(Kw-cOH_bulk*cH_bulk*np.exp((excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk) )/temperature)*conversion_factor_from_1_per_sigma_3_to_mol_per_l**2/cref_in_mol_per_l**2)>1e-15):
# raise RuntimeError("Kw incorrect")
# UNCOMMENT THIS AND CONFIRM WHY 10^-15
"""
def check_concentrations():
if(abs(cNa_bulk+cH_bulk+cH2A_bulk-cOH_bulk-cCl_bulk-cA_bulk)>1e-14):
raise RuntimeError("bulk is not electroneutral")
if(abs(pH-determined_pH)>1e-6):
raise RuntimeError("pH is not compatible with ionic strength and bulk H+ concentration")
if(abs(cs_bulk-min(cNa_bulk, cCl_bulk))>1e-14):
raise RuntimeError("bulk salt concentration is not correct")
if(abs(pH-7)<1e-14):
if((cH_bulk/cOH_bulk-1)>1e-14):
print(cH_bulk, cOH_bulk)
# raise RuntimeError("cH and cOH need to be symmetric at pH 7")
# print(cH_bulk*50*50*50, cOH_bulk*50*50*50)
#IMPORTANT COMMENTED raise RuntimeError("cH and cOH need to be symmetric at pH 7")
#print("after self consistent concentration calculation: cH_bulk, cOH_bulk, cNa_bulk, cCl_bulk, cH2A_bulk, cA_bulk, cHA_bulk", cH_bulk, cOH_bulk, cNa_bulk, cCl_bulk, cH2A_bulk, cA_bulk, cHA_bulk)
print ("after self consistent concentration calculation: ionic strength - ", ionic_strength_bulk,"cNa_bulk, cCl_bulk, cOH_bulk, cH_bulk, cH2A_bulk, cHA_bulk, cA_bulk: ", cNa_bulk, cCl_bulk, cOH_bulk, cH_bulk, cH2A_bulk, cHA_bulk, cA_bulk)
print("check KW: ",Kw, cOH_bulk*cH_bulk*np.exp((excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk) )/temperature)*conversion_factor_from_1_per_sigma_3_to_mol_per_l**2/cref_in_mol_per_l**2)
print((excess_chemical_potential_monovalent_pairs_in_bulk(ionic_strength_bulk)))
print("check electro neutrality bulk after", cNa_bulk+cH_bulk+cH2A_bulk-cOH_bulk-cCl_bulk-cA_bulk) #note that charges are neutral up to numerical precision. femto molar charge inequalities are not important in the bulk.
print("check pH: input", pH, "determined pH", determined_pH)
print("check cs bulk: input", cs_bulk, "determinde cs_bulk", min(cNa_bulk, cCl_bulk))
#print("check cH_bulk/cOH_bulk:", cH_bulk/cOH_bulk)
print("ka, kb, cHA_in_mol_per_l :", ka, kb, (cHA_bulk*conversion_factor_from_1_per_sigma_3_to_mol_per_l))
check_concentrations()
print ("Uptill here !!!!!!!!!!!!!")
def MC_swap_A_HA_particles(type_HA, type_A):
As=system.part.select(type=type_A)
HAs=system.part.select(type=type_HA)
ids_A=As.id
ids_HA=HAs.id
if(len(ids_A)>0 and len(ids_HA)>0):
#choose random_id_A, choose_random_id_HA
random_id_A=ids_A[np.random.randint(0,len(ids_A))]
random_id_HA=ids_HA[np.random.randint(0,len(ids_HA))]
old_energy=system.analysis.energy()["total"]
#adapt type and charge
system.part[random_id_A].type=type_HA
system.part[random_id_A].q=0
system.part[random_id_HA].type=type_A
system.part[random_id_HA].q=-1
new_energy=system.analysis.energy()["total"]
#apply metropolis criterion, accept or reject based on energetic change
if(np.random.random()<min(1,np.exp(-(new_energy-old_energy)/temperature))):
#accept
pass
else:
#reject
system.part[random_id_A].type=type_A
system.part[random_id_A].q=-1
system.part[random_id_HA].type=type_HA
system.part[random_id_HA].q=0
"""
def rescale_system_with_changing_grafting_density(graf_dens_sim, Num_polymers_in_brush):
global box_l_x, box_l_y, Volume
sqrt_Num_polymers_in_brush = (np.sqrt(Num_polymers_in_brush))
if isinstance(sqrt_Num_polymers_in_brush, float):
raise RuntimeError("Num of polymers in brush has to be a a proper root")
unit_step = np.sqrt((1.0/graf_dens_sim))
new_length = unit_step*sqrt_Num_polymers_in_brush
box_l_x=new_length
box_l_y=new_length
Volume = box_l_x*box_l_y*box_l_z_tube # in units of 1/sigma3
# rescale box
system.change_volume_and_rescale_particles(d_new=box_length)
print("Rescaled the simulation box.", flush=True)
p3m = espressomd.electrostatics.P3M(**P3M_PARAMS, **CI_PARAMS)
system.actors.add(p3m)
def system_setup(c_salt_SI):
print(f"Salt concentration: {c_salt_SI:.12g} mol/l", flush=True)
c_salt_sim = c_salt_SI /conversion_factor_from_1_per_sigma_3_to_mol_per_l
box_length = np.cbrt(N_ion_pairs / c_salt_sim)
# rescale box
system.change_volume_and_rescale_particles(d_new=box_length)
print("Rescaled the simulation box.", flush=True)
p3m = espressomd.electrostatics.P3M(**P3M_PARAMS, **CI_PARAMS)
system.actors.add(p3m)
"""
"""________________________________________________DEFINING REACTIONS__________________________________________________________|
_______________________________________________________________________________________________________________________________|
"""
type_H=0
type_A=1
type_HA=2
type_OH=3
#type_constraint=4
type_Na=4
type_Cl=5
type_constraint_A=6
type_constraint_B=7
type_HA_zwit=8
type_A_zwit=9
type_H2A_zwit=10
type_Usampling_wall=11
type_probe=[type_HA_zwit, type_A_zwit, type_H2A_zwit]
z_H=+1
z_A=-1
z_HA=0
z_OH=-1
#z_constraint=
z_Na=+1
z_Cl=-1
z_constraint=0
z_HA_zwit=0
z_H2A_zwit=+1
z_A_zwit=-1
#z_probe=+1
z_Usampling_wall=0
types_neutral_polymer=[type_HA, type_constraint_A, type_constraint_B]
type_ions=[type_H ,type_OH, type_Na, type_Cl , type_HA_zwit, type_A_zwit, type_H2A_zwit]
types=[type_H, type_A, type_HA,type_OH, type_Na, type_Cl, type_constraint_A, type_constraint_B , type_HA_zwit, type_A_zwit, type_H2A_zwit]
types_without_zwitterion=[type_H, type_A, type_HA,type_OH, type_Na, type_Cl, type_constraint_A, type_constraint_B ]
types_without_polymer=[type_H,type_OH, type_Na, type_Cl, type_constraint_A, type_constraint_B , type_HA_zwit, type_A_zwit, type_H2A_zwit]
types_polymer=[type_A, type_HA]
#types_without_wall=[type_H, type_A, type_HA,type_OH, type_Na, type_Cl, type_HA_zwit, type_A_zwit, type_H2A_zwit]
#types=[type_H, type_A, type_HA,type_OH, type_Na, type_Cl, type_HA_zwit, type_A_zwit, type_H2A_zwit]
charges=[z_H, z_A, z_HA, z_OH, z_Na, z_Cl, z_HA_zwit, z_H2A_zwit, z_A_zwit]
#Nions=[N_H, N_A, N_HA, N_OH, N_Na, N_Cl]
"""
bead_start_pos_arr_1D = np.array([1,2,3])#([123]) A list
bead_start_pos_arr_2D = np.array([ [1,2,3],[4,5,6],[7,8,9] ])#([ [123],[123],[123],...] )A list of lists
bead_start_pos_arr_3D = np.array( [ [[1,2,3],[4,5,6],[7,8,9]] , [['a','s','d'],['f','g','h'],['a','s','d']] , [['b','h','m'],['q','r','r'],['o','l','p']] ] )#([ [[],[],[]] , [[],[],[]] , [[],[],[]] ] )A list of lists of lists
print ('bead_start_pos_arr_1D.shape', bead_start_pos_arr_1D.shape)
print ('bead_start_pos_arr_2D.shape', bead_start_pos_arr_2D.shape)
print ('bead_start_pos_arr_3D.shape', bead_start_pos_arr_3D.shape)
"""
#______________________Grafting density and setting up box dimensions________
graf_dens_sim=0.1
Num_polymers_in_brush=100
#Num_beads_each_polymer=
Num_monomers_maximum=100
Num_beads_each_polymer=Num_monomers_maximum
sqrt_Num_polymers_in_brush = (int)(np.sqrt(Num_polymers_in_brush))
#sqrt_check_Num_polymers_in_brush = (np.sqrt(Num_polymers_in_brush))
#if isinstance(sqrt_check_Num_polymers_in_brush, float):
# raise RuntimeError("Num of polymers in brush has to be a a proper root")
unit_step = np.sqrt((1.0/graf_dens_sim))
new_length = unit_step*sqrt_Num_polymers_in_brush
box_l_x=new_length
box_l_y=new_length
box_l_z_tube=150
elc_gap=30
box_l_z=box_l_z_tube+elc_gap
Volume = box_l_x*box_l_y*box_l_z_tube # in units of 1/sigma3
print("Box DImensions ")
print(box_l_x, box_l_y, box_l_z, unit_step, sqrt_Num_polymers_in_brush, Num_polymers_in_brush)
slab_width=box_l_z_tube#(wall_offset_from_box_boundary - (box_l_z-wall_offset_from_box_boundary) )
wall_offset=0#box_l_z - ((box_l_z/2.0)+(slab_width/2.0))
system = espressomd.System(box_l=[box_l_x, box_l_y, box_l_z])
TIME_STEPS = 0.01
system.time_step = TIME_STEPS
system.cell_system.skin = 0.4
LJ_EPSILON = 1.0
LJ_SIGMA = 1.0
print("-------------- Box DImensions---------------------")
print(box_l_x, box_l_y, box_l_z)
#===============================Setting up the polymer brush===================================
# Setup an array of initial adhered beads
#=======================================
bead_start_pos_arr = np.empty((Num_polymers_in_brush, 3), dtype=float)
z_offset=wall_offset+LJ_SIGMA
particle_count =0;
if(particle_count < Num_polymers_in_brush):
for i in range (sqrt_Num_polymers_in_brush ):
for j in range (sqrt_Num_polymers_in_brush):
bead_start_pos_arr[particle_count][0] = (i+1)*unit_step
bead_start_pos_arr[particle_count][1] = (j+1)*unit_step
bead_start_pos_arr[particle_count][2] = z_offset#system.box_l[0]/2.0
particle_count = particle_count+1
# Check if the correct grafting density is implemented
#=====================================================
min_x = +10000000
max_x = -10000000
min_y = +10000000
max_y = -10000000
for i in range (Num_polymers_in_brush):
if(bead_start_pos_arr[i][0]<min_x):
min_x = bead_start_pos_arr[i][0]
if(bead_start_pos_arr[i][0]>max_x):
max_x = bead_start_pos_arr[i][0]
if(bead_start_pos_arr[i][1]<min_y):
min_y = bead_start_pos_arr[i][1]
if(bead_start_pos_arr[i][1]>max_y):
max_y = bead_start_pos_arr[i][1]
max_x = max_x
min_x = min_x-unit_step
max_y = max_y
min_y = min_y-unit_step
print(min_x, max_x, min_y, max_y)
graf_dens_calc = Num_polymers_in_brush/((max_x-min_x)*(max_y-min_y))
print("Calculated grafting density is : ", graf_dens_calc )
Num_polymer_ls_seq=[]
#Num_poly_read= np.zeros((20,20))
total_num_beads = 0
Num_poly_read = np.loadtxt("/work/keerthirk/spherical_brush/attractive_LJ/PolydispersityInd_1/PolymerList.txt" )
lets_start=0
for j in range (len(Num_poly_read)):
total_num_beads = total_num_beads + (Num_poly_read[j][0]*Num_poly_read[j][1])
# Num_monomers = int(Num_poly_read[j][1])
for i in range (int(Num_poly_read[j][1])):
lets_start= lets_start +1
print(lets_start , Num_poly_read[j][0])
Num_polymer_ls_seq.append(Num_poly_read[j][0])
random.shuffle(Num_polymer_ls_seq)
list_of_linear_positions = np.zeros((Num_polymers_in_brush, Num_monomers_maximum, 3), dtype=float)
for i in range (len(Num_polymer_ls_seq)):
Count_monomers_in_this_poly=Num_polymer_ls_seq[i]
for j in range(int(Count_monomers_in_this_poly)):
list_of_linear_positions[i][j][0] = bead_start_pos_arr[i][0]
list_of_linear_positions[i][j][1] = bead_start_pos_arr[i][1]
list_of_linear_positions[i][j][2] = bead_start_pos_arr[i][2]+(1.0*j)
'''
list_of_linear_positions = np.empty((Num_polymers_in_brush,Num_beads_each_polymer, 3), dtype=float)
#print('list_of_linear_positions: Shape: ', list_of_linear_positions.shape )
#print( list_of_linear_positions )
for i_poly in range (Num_polymers_in_brush):
for i_monomer in range (Num_beads_each_polymer):
# if(i_monomer==0):
# list_of_linear_positions[i_poly][i_monomer] = bead_start_pos_arr[i_poly]
# else:
list_of_linear_positions[i_poly][i_monomer][0] = bead_start_pos_arr[i_poly][0]
list_of_linear_positions[i_poly][i_monomer][1] = bead_start_pos_arr[i_poly][1]
list_of_linear_positions[i_poly][i_monomer][2] = bead_start_pos_arr[i_poly][2]+(1*i_monomer)
'''
pi =np.pi
print("Piiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii", pi)
#================================Setting up the walls at Lz=0 and Lz=box_l_z====================
if (wall_offset!=0):
raise RuntimeError("Wall offset must be at zero to Lz when using ELC gap explicitly")
# bottom wall, normal pointing in the +z direction, laid at z=0.1
floor = espressomd.shapes.Wall(normal=[0, 0, 1], dist=wall_offset)
c1 = system.constraints.add(
particle_type=type_constraint_A, penetrable=False, only_positive=False, shape=floor)
steps = 1
wall_pr_in_x = (int)(box_l_x/steps)
wall_pr_in_y = (int)(box_l_y/steps)
particle_pos_floor=np.empty(((wall_pr_in_x*wall_pr_in_y),3), dtype=float)
particle_pos_ceil=np.empty(((wall_pr_in_x*wall_pr_in_y),3), dtype=float)
wall_pr_id=0
for i in range (wall_pr_in_x):
for j in range (wall_pr_in_y):
particle_pos_floor[wall_pr_id][0] =(i*steps)
particle_pos_floor[wall_pr_id][1] =(j*steps)
particle_pos_floor[wall_pr_id][2] =wall_offset
wall_pr_id=wall_pr_id+1;
#print("!!!!!!!!!!!!!!!!!Printing particle floor positions......\n")
#print(particle_pos_floor.shape, "\n")
#print(particle_pos_floor)
# top wall, normal pointing in the -z direction, laid at z=49.9, since the
# normal direction points down, dist is -49.9
ceil = espressomd.shapes.Wall(normal=[0, 0, -1], dist=-(box_l_z_tube - wall_offset)) #WHY NEGATIVE
c2 = system.constraints.add(
particle_type=type_constraint_B, penetrable=False, only_positive=False, shape=ceil)
wall_pr_id=0
for i in range (wall_pr_in_x):
for j in range (wall_pr_in_y):
particle_pos_ceil[wall_pr_id][0] =(i*steps)
particle_pos_ceil[wall_pr_id][1] =(j*steps)
particle_pos_ceil[wall_pr_id][2] =(box_l_z_tube-wall_offset)
wall_pr_id=wall_pr_id+1;
print("!!!!!!!!!!!!!!!!!Printing particle ceil positions......\n")
#print(particle_pos_ceil.shape, "\n")
#print(particle_pos_ceil)
#David I figured a small technicality related to the equiliberation without break of bonds . Actually as you suggested if we only call 10^6 times integrator without electrostatics and then switch on electrostatics . The system still blew up. Because in my case my system initially starts with no counterions , so the presence of huge intra chain repulsion still blew the system even after warmup. So I had to make reaction calls as well when equiliberating without electrostatics , so that by the time electrostatics is switched on there is enough screening by counterions within the brush to avoid huge repulsive forces
#visualizer = espressomd.visualization.openGLLive(system,particle_coloring='type')
#visualizer.run()
#visualizer.screenshot(f'screenshot_wall.png')
#POLYMER_PARAMS = {'n_polymers': Num_polymers_in_brush, 'beads_per_chain':25, 'bond_length': 1, 'seed': 42, 'min_distance': 0.9, 'start_positions':}
#POLYMER_PARAMS = {'n_polymers': Num_polymers_in_brush, 'beads_per_chain': Num_beads_each_polymer, 'bond_length': 1, 'seed': 42, 'min_distance': 0.9,'start_positions':bead_start_pos_arr}#, 'bond_angle':pi/4}
bjerrum=2.0
#system.seed=np.random.randint(np.random.randint(1000000))# DOUBT WHY SHOWING PROBLEM
#Ensure Charge neutrality with the int used rounding off it can go wrong
#N_POLY = Num_polymers_in_brush*Num_beads_each_polymer#int(c_poly*Volume)#N_A + N_HA = N_POLY
N_POLY = total_num_beads
N_HA = N_POLY
Na_cpoly_vol=(N_HA-N_POLY)
N_A=np.abs(Na_cpoly_vol)
N_H = 0
N_OH = 0# int((cOH_bulk*Volume))
N_Na = 0#int((cNa_bulk*Volume))
N_Cl = 0#int((cCl_bulk*Volume))
N_HA_zwit = 0
N_A_zwit = 0
N_H2A_zwit=0
Nions=[N_H, N_A, N_HA, N_OH, N_Na, N_Cl, N_HA_zwit, N_A_zwit, N_H2A_zwit]
print('N_H-',N_H, "N_HA-", N_HA, " N_OH-",N_OH, " N_Na-",N_Na, " N_Cl-",N_Cl, " N_A-",N_A, "N_HA_zwit", N_HA_zwit,"N_A_zwit", N_A_zwit,"N_H2A_zwit", N_H2A_zwit)
print("----------------------------->Ionic strength: ",ionic_strength_bulk)
#print ("---------------------------->Concentration of A- ions: ", (N_A/Volume))
#===========================================================================================
#===============================SET UP INTERACTIONS==========================================
#LJ_EPSILON = 1.0
#LJ_SIGMA = 1.0
#_______________________introduce fene to system as a bonded interaction_________________
fene = espressomd.interactions.FeneBond(k=30, d_r_max=2.0)
system.bonded_inter.add(fene)
#harmonic = HarmonicBond(k=30.0, r_0=0.0)
#system.bonded_inter.add(harmonic)
#__________________________LJ intercation between counterions, monomers and salt_______________
# ((((((( IDEAL CASE CHANGE )))))))))))
#for i in types:
# system.non_bonded_inter[i, type_constraint_A].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
# system.non_bonded_inter[i, type_constraint_B].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
# ion-ion interaction
for i in types_without_zwitterion:
for j in types_without_zwitterion:
system.non_bonded_inter[i, j].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
for i in types_without_polymer:# Goto line 1036 to correct for raspberry ions
system.non_bonded_inter[i, type_HA_zwit].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
system.non_bonded_inter[i, type_H2A_zwit].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
system.non_bonded_inter[i, type_A_zwit].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
for i in types_polymer:# Goto line 1036 to correct for raspberry ions
system.non_bonded_inter[i, type_HA_zwit].lennard_jones.set_params(epsilon=LJ_EPSILON+1, sigma=LJ_SIGMA, cutoff=LJ_SIGMA * 2.5, shift="auto")
system.non_bonded_inter[i, type_H2A_zwit].lennard_jones.set_params(epsilon=LJ_EPSILON+1, sigma=LJ_SIGMA, cutoff=LJ_SIGMA * 2.5, shift="auto")
system.non_bonded_inter[i, type_A_zwit].lennard_jones.set_params(epsilon=LJ_EPSILON+1, sigma=LJ_SIGMA, cutoff=LJ_SIGMA * 2.5, shift="auto")
#for i in types_polymer:
# system.non_bonded_inter[i, type_HA_zwit].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
# system.non_bonded_inter[i, type_H2A_zwit].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
# system.non_bonded_inter[i, type_A_zwit].wca.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA)
# system.non_bonded_inter[i, j].lennard_jones.set_params(epsilon=LJ_EPSILON, sigma=LJ_SIGMA, cutoff=LJ_SIGMA * 2**(1.0/6.0), shift="auto")
#_________________________Build polymer with fene potential________________________________
#Note: espressomd.polymer.linear_polymer_positions returns a 3D numpy array . SInce we have a
#list conatining N entries (y cols) each with 3 positional values (z cols) its essentially 2D . SO we have to invoke
#by default the list_of_linear_positions[0] whcih is of the size list_of_linear_positions[0][N][3]
# Here list_of_linear_positions is the self defined linear array of polymers in a PE brush
start_part_id_list=[]
track_brush_particle_id=[]
def build_polymer( type_of_bond_interaction):
global track_brush_particle_id
# list_of_linear_positions = espressomd.polymer.linear_polymer_positions( **polymer_params)
# print ("Building a polymer with parameters: ", polymer_params)
# print(list_of_linear_positions)
# print(list_of_linear_positions.shape)
# print (list_of_linear_positions[:][0])
for N_pol in range (len(Num_polymer_ls_seq)):
Count_monomers_in_this_poly=Num_polymer_ls_seq[N_pol]
# print("len(Num_polymer_ls_seq)", len(Num_polymer_ls_seq))
par_prev=None
start_par = 1
for i in range(len(list_of_linear_positions[N_pol])): # here since positions is a list of list of lists shape(10,50,3) ,positions[N_poly] will give a list of 50 monomer.pos of the (N_polyth-1) chain.
if(i<Count_monomers_in_this_poly):
par=system.part.add(pos=list_of_linear_positions[N_pol][i], type=type_HA, q=charges[type_HA])
track_brush_particle_id.append(par.id)
print(N_pol , i , par.pos)
if start_par==1:
start_par=0
par.fix = [True, True, True]
start_part_id_list.append(par.id)
if par_prev is not None:
par.add_bond((type_of_bond_interaction, par_prev))
par_prev = par
"""
previous_part = None
for i in list_of_linear_positions[0]:
part=system.part.add(pos=i, type=type_A, q=charges[type_A])
if previous_part:
part.add_bond((type_of_bond_interaction, previous_part))
previous_part = part
"""
print("Building polymer brush .....")
#build_polymer( fene)# We are initializing a chain with all ions as HA ions, with zero A-
#particle_id = system.part.all().id
#particle_type = system.part.all().type
#particle_pos = system.part.all().pos
#print("POlymer", system.part.all().pos)
#visualizer = espressomd.visualization.openGLLive(system,particle_coloring='type')
#visualizer.run()
#visualizer.screenshot(f'polymer_brush_1.png')
#vmd_file = open("movie.out", "a")
num_ls = []
#num_ls.append(Num_polymers_in_brush*Num_beads_each_polymer)
#np.savetxt("movie.out" , np.column_stack([particle_pos]), fmt='%.7f\t', delimiter='\t')
#np.savetxt("movie_ls.out" , particle_pos, fmt='%.7f\t', delimiter='\t')
#____________________________Add counterions and salt in system_____________________________
#N_ions=[10]
#counter_ions=[]
"""
ion_positions=np.empty((3),dtype=float)
print ("Setting counterions H+ at t=0....")
for i in range(N_H):
ion_positions[0] = np.random.random(1) * system.box_l[0]
ion_positions[1] = np.random.random(1) * system.box_l[1]
# ion_positions[2] = (np.random.random(1) * box_l_z_tube) + wall_offset
rg1=wall_offset+5
rg2=box_l_z_tube-wall_offset-5
ion_positions[2] = ((rg2-rg1)*np.random.random(1)) + rg1 #rg1-rg2 desired (rg2-rg1)*a + rg1
par = system.part.add(pos=ion_positions, type=type_H , q=charges[type_H])
# print ("Particle_id: ",par, " ; Particle Pos: ", par.pos, " ; Particle Type: ", par.type," ; Particle Charge: ", par.q)
print ("Setting counterions HA at t=0....")
for i in range(N_HA):
# ion_positions = np.random.random(3) * system.box_l
ion_positions[0] = np.random.random(1) * system.box_l[0]
ion_positions[1] = np.random.random(1) * system.box_l[1]
# ion_positions[2] = (np.random.random(1) * box_l_z_tube) + wall_offset
rg1=wall_offset+5
rg2=box_l_z_tube-wall_offset-5
ion_positions[2] = ((rg2-rg1)*np.random.random(1)) + rg1 #rg1-rg2 desired (rg2-rg1)*a + rg1
par = system.part.add(pos=ion_positions, type=type_HA , q=charges[type_HA])
# print ("Particle_id: ",par, " ; Particle Pos: ", par.pos, " ; Particle Type: ", par.type," ; Particle Charge: ", par.q)
"""
part_positions = system.part.all().pos
for itr1 in part_positions:
if(itr1[2]<wall_offset or itr1[2]>(box_l_z_tube-wall_offset)):
print("!!!!!!!!!!!!!!Particle going outside in z-direction !!!!!!!", itr1)
#visualizer.screenshot(f'screenshot_2.png')
#If want to start a system with all ions both res and sys within the system then;
#particle_id=[]
#print(N_H," ",N_OH," ",N_Na," ",N_Cl," ",N_A," ",N_HA," ",N_H+N_OH+N_Na+N_Cl+N_A+N_HA)
#particle_id = []
particle_id = system.part.all().id
particle_type = system.part.all().type
sum_charge=0
for i in particle_id:
p=system.part.by_id(i)
sum_charge = sum_charge+p.q
# print(p.type," ", p.q)
if(abs(sum_charge)>1e-3):
raise ValueError("System is not neutral. Charge is "+ str(sum_charge))
if(abs(cNa_bulk+cH_bulk-cOH_bulk-cCl_bulk+cH2A_bulk-cA_bulk)>1e-14):
raise RuntimeError("bulk is not electroneutral")
print('Bulk: ','N_H-',(cH_bulk*Volume), " N_OH-",(cOH_bulk*Volume), " N_Na-",(cNa_bulk*Volume), " N_Cl-",(cCl_bulk*Volume), 'N_HA_zwit', (cHA_bulk*Volume), 'N_H2A_zwit', (cH2A_bulk*Volume), 'N_A_zwit', (cA_bulk*Volume))
print('System started with: ','N_H-',N_H, "N_HA-", N_HA, " N_OH-",N_OH, " N_Na-",N_Na, " N_Cl-",N_Cl, " N_A-",N_A, "N_HA_zwit", N_HA_zwit,"N_A_zwit", N_A_zwit,"N_H2A_zwit", N_H2A_zwit)
"""
#____________________________Set up electrostatic interactions______________________________
# ((((((( IDEAL CASE CHANGE )))))))))))
p3m = electrostatics.P3M(prefactor=bjerrum*temperature, accuracy=1e-3)
elc = espressomd.electrostatics.ELC(
actor=p3m, maxPWerror=1e-3, gap_size=elc_gap)
system.actors.add(elc)
#system.actors.add(p3m)
print("P3M parameters:\n")
p3m_params = p3m.get_params()
for key in list(p3m_params.keys()):
print("{} = {}".format(key, p3m_params[key]))
"""
#============================================================================================
#============================SYSTEM WARMING AND OVERLAP REMOVES==============================
def remove_overlap(system, sd_params):
system.integrator.set_steepest_descent(f_max=0,
gamma=sd_params['damping'],
max_displacement=sd_params['max_displacement'])
system.integrator.run(0)
maxforce = np.max(np.linalg.norm(system.part.all().f, axis=1))
energy = system.analysis.energy()['total']
i = 0
while i < sd_params['max_steps'] // sd_params['emstep']:
prev_maxforce = maxforce
prev_energy = energy
system.integrator.run(sd_params['emstep'])
maxforce = np.max(np.linalg.norm(system.part.all().f, axis=1))
relforce = np.abs((maxforce - prev_maxforce) / prev_maxforce)
energy = system.analysis.energy()['total']
relener = np.abs((energy - prev_energy) / prev_energy)
if i > 1 and (i + 1) % 4 == 0:
print(f"minimization step: {(i+1)*sd_params['emstep']:4.0f}"
f" max. rel. force change:{relforce:+3.3e}"
f" rel. energy change:{relener:+3.3e}")
if relforce < sd_params['f_tol'] or relener < sd_params['e_tol']:
break
i += 1
system.integrator.set_vv()
STEEPEST_DESCENT_PARAMS = {'f_tol': 1e-2,
'e_tol': 1e-5,
'damping': 30,
'max_steps': 30000,
'max_displacement': 0.0001,
'emstep': 50}
'''
**********************************************************
Umbrella Sampling
**********************************************************
'''
z_min=0
z_max = 50
z_min_init=z_min
bin_size=0.5#1.0#(z_max-z_min)
num_of_bins=(int)((z_max-z_min)/bin_size)
k_harmonic=3.0
#For metafile
file_name_ls=[]
minimum_ls=[]
kspring_ls=[]
#===========================================Umbrella Sampling==========================================
K_har = k_harmonic
r_min=-5# THis sometimes causes error if taken too large like > 50 ...why , also too large like 30 was causing issue with missing peaks too
r_max=5
energy_width_r=0.2
N_points = (int)(((r_max-r_min)/energy_width_r)+1)
tabulated_force=[]
tabulated_energy=[]
for tab in range (N_points):
r_p = r_min + (tab*energy_width_r)
energy_rp = 0.5*K_har*((r_p-0)**2)
force_rp = -K_har*(r_p-0)
tabulated_energy.append(energy_rp)
tabulated_force.append(force_rp)
#*************************************************
# Setting up a raspberry particle
#*************************************************
# Ion types RASPBERRY
#############################################################
TYPE_CENTRAL = len(types)
TYPE_SURFACE = len(types)+1
# Interaction parameters (Lennard-Jones for raspberry)
radius_col = 3.
harmonic_radius = 3.0
# the subscript c is for colloid and s is for salt (also used for the surface beads)
eps_ss = 1. # LJ epsilon between the colloid's surface particles.
sig_ss = 1. # LJ sigma between the colloid's surface particles.
eps_cs = 48. # LJ epsilon between the colloid's central particle and surface particles.
sig_cs = radius_col # LJ sigma between the colloid's central particle and surface particles (colloid's radius).
a_eff = 0.32 # effective hydrodynamic radius of a bead due to the discreteness of LB.
# the LJ potential with the central bead keeps all the beads from simply collapsing into the center
system.non_bonded_inter[TYPE_SURFACE, TYPE_CENTRAL].wca.set_params(epsilon=eps_cs, sigma=sig_cs)
system.non_bonded_inter[type_HA_zwit, TYPE_CENTRAL].wca.set_params(epsilon=eps_cs, sigma=sig_cs)
system.non_bonded_inter[type_H2A_zwit, TYPE_CENTRAL].wca.set_params(epsilon=eps_cs, sigma=sig_cs)
system.non_bonded_inter[type_A_zwit, TYPE_CENTRAL].wca.set_params(epsilon=eps_cs, sigma=sig_cs)
# the LJ potential (WCA potential) between surface beads causes them to be roughly equidistant on the
# colloid surface
type_on_surface = [TYPE_SURFACE, type_HA_zwit, type_H2A_zwit, type_A_zwit]
for i in type_on_surface:
for j in type_on_surface:
system.non_bonded_inter[i, j].wca.set_params(epsilon=eps_ss, sigma=sig_ss)
# the harmonic potential pulls surface beads towards the central colloid bead
col_center_surface_bond = espressomd.interactions.HarmonicBond(k=3000., r_0=harmonic_radius)
system.bonded_inter.add(col_center_surface_bond)
center = system.box_l / 2
colPos = center