forked from hoogerheide/autonomous
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmolgroups.py
More file actions
1838 lines (1480 loc) · 80.1 KB
/
molgroups.py
File metadata and controls
1838 lines (1480 loc) · 80.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy
from scipy.special import erf
from scipy.interpolate import PchipInterpolator, CubicHermiteSpline, interpn
from scipy.spatial.transform import Rotation
from scipy.ndimage.filters import gaussian_filter
from periodictable.fasta import xray_sld
from components import Component
class nSLDObj:
def __init__(self, name=None):
self.bWrapping = True
self.bConvolution = False
self.bProtonExchange = False
self.dSigmaConvolution = 1
self.iNumberOfConvPoints = 7
self.absorb = 0
self.z = 0
self.l = 0
self.vol = 0
self.nSL = 0
self.nf = 0
self.sigma = 0
if name is not None:
self.name = name
def fnGetAbsorb(self, z):
return self.absorb
# returns a n-point gaussian interpolation of the area within 4 sigma
# all area calculations are routed through this function, whether they use convolution or not
# convolution works only for objects with fixed nSLD. Broadening an nSLD profile is not as direct as
# broadening a nSL profile. For reason, however, objects report a nSLD(z) and not a nSL(z)
# if it becomes necessary to broaden profiles with variable nSLD, structural changes to the code
# have to be implemented.
def fnGetArea(self, z):
raise NotImplementedError()
def fnGetProfiles(self, z):
raise NotImplementedError()
def fnGetConvolutedArea(self, dz):
# TODO: use scipy image filters or numpy convolution to do this.
if self.bConvolution:
dnormsum = 0
dsum = 0
for i in range(self.iNumberOfConvPoints):
dd = 8 / float(self.iNumberOfConvPoints*i) - 4
dgauss = numpy.exp((-0.5)*dd*dd) # (sigma_convolution)^2/(sigma_convolution)^2 cancels
dnormsum += dgauss
dsum += self.fnGetArea(dz + dd * self.dSigmaConvolution) * dgauss
if dnormsum != 0:
return dsum/dnormsum
else:
return 0
else:
return self.fnGetArea(dz)
def fnGetLowerLimit(self):
raise NotImplementedError()
def fnGetnSLD(self, z):
raise NotImplementedError()
def fnGetUpperLimit(self):
raise NotImplementedError()
def fnGetZ(self):
return self.z
def fnSetConvolution(self, sigma_convolution, iNumberOfConvPoints):
self.bConvolution = True
self.dSigmaConvolution = sigma_convolution
self.iNumberOfConvPoints = iNumberOfConvPoints
def fnWriteData2File(self, f, cName, z):
header = "z"+cName+" a"+cName+" nsl"+cName
area, nsl, _ = self.fnGetProfiles(z)
A = numpy.vstack((z, area, nsl)).T
numpy.savetxt(f, A, fmt='%0.6e', delimiter=' ', comments='', header=header)
f.write('\n')
# TODO: implement wrapping
def fnWriteData2Dict(self, rdict, z):
area, nsl, nsld = self.fnGetProfiles(z)
rdict['zaxis'] = z
rdict['area'] = area
rdict['nsl'] = nsl
rdict['nsld'] = nsld
return rdict
def fnWritePar2File(self, fp, cName, z):
raise NotImplementedError()
def fnWritePar2Dict(self, rdict, cName, z):
# Same as fnWritePar2File, but output is saved in a dictionary
raise NotImplementedError()
@staticmethod
def fnWriteConstant(fp, name, darea, dSLD, z):
header = "Constant " + name + " area " + str(darea) + " \n" + \
"z_" + name + " a_" + name + " nsl_" + name
area = darea * numpy.ones_like(z)
nsl = dSLD * darea * numpy.gradient(z)
A = numpy.vstack((z, area, nsl)).T
numpy.savetxt(fp, A, fmt='%0.6e', delimiter=' ', comments='', header=header)
fp.write('\n')
def fnWriteConstant2Dict(self, rdict, name, darea, dSLD, z):
rdict[name] = {}
rdict[name]['header'] = "Constant " + name + " area " + str(darea)
rdict[name]['area'] = darea
rdict[name]['sld'] = dSLD
constarea = numpy.ones_like(z) * darea
constsld = numpy.ones_like(z) * dSLD
rdict[name]['zaxis'] = z
rdict[name]['area'] = constarea
rdict[name]['nsl'] = constsld * numpy.gradient(z) *constarea
rdict[name]['nsld'] = constsld
return rdict
# Philosophy for this first method: You simply add more and more volume and nSLD to the
# volume and nSLD array. After all objects have filled up those arrays the maximal area is
# determined which is the area per molecule and unfilled volume is filled with bulk solvent.
# Hopefully the fit algorithm finds a physically meaningful solution. There has to be a global
# hydration paramter for the bilayer.
# Returns maximum area
def fnWriteProfile(self, z, aArea=None, anSL=None):
# do we want a 0.5 * stepsize shift? I believe refl1d FunctionalLayer uses
# z = numpy.linspace(0, dimension * stepsize, dimension, endpoint=False)
# z, aArea, anSL must be numpy arrays with the same shape
# TODO implement wrapping
# TODO implement absorption
aArea = numpy.zeros_like(z) if aArea is None else aArea
anSL = numpy.zeros_like(z) if anSL is None else anSL
assert(aArea.shape == z.shape)
assert(anSL.shape == z.shape)
area, nsl, _ = self.fnGetProfiles(z)
dMaxArea = area.max()
aArea += area
anSL += nsl
return dMaxArea, aArea, anSL
def fnOverlayProfile(self, z, aArea, anSL, dMaxArea):
# z, aArea, anSL must be numpy arrays with the same shape
assert (aArea.shape == z.shape)
assert (anSL.shape == z.shape)
# TODO implement wrapping
# TODO implement absorption
area, nsl, _ = self.fnGetProfiles(z)
temparea = aArea + area
# find any area for which the final area will be greater than dMaxArea
overmax = temparea > dMaxArea
# note: unphysical overfill will trigger the following assertion error
# TODO: implement a correction instead of throwing an error
assert (not numpy.any((temparea - dMaxArea) > aArea))
anSL[overmax] = anSL[overmax] * (1 - ((temparea[overmax] - dMaxArea)/aArea[overmax])) + nsl[overmax]
aArea[overmax] = dMaxArea
# deal with area for which the final area is not greater than dMaxArea
aArea[~overmax] += area[~overmax]
anSL[~overmax] += nsl[~overmax]
return aArea, anSL
class CompositenSLDObj(nSLDObj):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def fnFindSubgroups(self):
# this should be run at the end of init. Could also store keys if memory is an issue
# and then use self.__dict__[key]
# Could use a "subgroup adder" function that adds to subgroups
self.subgroups = [getattr(self, attr) for attr in dir(self) if isinstance(getattr(self, attr), nSLDObj)]
def fnGetProfiles(self, z):
area = numpy.zeros_like(z)
nsl = numpy.zeros_like(z)
nsld = numpy.zeros_like(z)
# make sure FindSubGroups was called. TODO: speed tests whether this is too expensive to do every time
if not hasattr(self, 'subgroups'):
self.fnFindSubgroups()
for g in self.subgroups:
newarea, newnsl, _ = g.fnGetProfiles(z)
area += newarea
nsl += newnsl
nsld = numpy.zeros_like(z)
pos = (area > 0)
nsld[pos] = nsl[pos] / (area[pos] * numpy.gradient(z)[pos])
return area * self.nf, nsl * self.nf, nsld
def fnWritePar2File(self, f, cName, z):
if not hasattr(self, 'subgroups'):
self.fnFindSubgroups()
for g in self.subgroups:
# this allows objects with the same names from multiple bilayers
g.fnWritePar2File(f, cName+'.'+g.name, z)
def fnWritePar2Dict(self, rdict, cName, z):
if not hasattr(self, 'subgroups'):
self.fnFindSubgroups()
for g in self.subgroups:
# this allows objects with the same names from multiple bilayers
rdict = g.fnWritePar2Dict(rdict, cName+'.'+g.name, z)
return rdict
class Box2Err(nSLDObj):
def __init__(self, dz=20, dsigma1=2, dsigma2=2, dlength=10, dvolume=10, dnSL=0, dnumberfraction=1, name=None):
super().__init__(name=name)
self.z = dz
self.sigma1 = dsigma1
self.sigma2 = dsigma2
self.l = dlength
self.init_l = dlength
self.vol = dvolume
self.nSL = dnSL
self.nf = dnumberfraction
self.nsldbulk_store = 0.
self.nSL2 = None
def fnGetProfiles(self, z, bulknsld=0):
if bulknsld != 0:
self.nsldbulk_store = bulknsld
# calculate area
# Gaussian function definition, integral is volume, return value is area at positions z
if (self.l != 0) and (self.sigma1 != 0) and (self.sigma2 != 0):
area = erf((z - self.z + 0.5 * self.l) / (numpy.sqrt(2) * self.sigma1))
# result = math.erf((dz - self.z + 0.5 * self.l) / math.sqrt(2) / self.sigma1)
# result -= math.erf((dz - self.z - 0.5 * self.l) / math.sqrt(2) / self.sigma2)
area -= erf((z - self.z - 0.5 * self.l) / (numpy.sqrt(2) * self.sigma2))
area *= (self.vol / self.l) * 0.5
area *= self.nf
else:
area = numpy.zeros_like(z)
# calculate nSLD
nsld = self.fnGetnSL(bulknsld) / self.vol * numpy.ones_like(z) if self.vol != 0 else numpy.zeros_like(z)
# calculate nSL.
nsl = area * nsld * numpy.gradient(z)
return area, nsl, nsld
def fnGetnSL(self, bulknsld):
if self.bProtonExchange:
if self.vol != 0:
return ((bulknsld + 0.56e-6) * self.nSL2 + (6.36e-6 - bulknsld) * self.nSL) / (6.36e-6 + 0.56e-6)
else:
return 0.
else:
return self.nSL
# Gaussians are cut off below and above 3 sigma double
def fnGetLowerLimit(self):
return self.z - 0.5 * self.l - 3 * self.sigma1
def fnGetUpperLimit(self):
return self.z + 0.5 * self.l + 3 * self.sigma2
# 7/6/2021 new feature: only use proton exchange if nSL2 is explicitly set!
def fnSetnSL(self, _nSL, _nSL2=None):
self.nSL = _nSL
if _nSL2 is not None:
self.nSL2 = _nSL2
self.bProtonExchange = True
else:
self.bProtonExchange = False
def fnSetSigma(self, sigma1, sigma2=None):
self.sigma1 = sigma1
self.sigma2 = sigma1 if sigma2 is None else sigma2
def fnSetZ(self, dz):
self.z = dz
def fnWritePar2File(self, fp, cName, z):
fp.write("Box2Err "+cName+" z "+str(self.z)+" sigma1 "+str(self.sigma1)+" sigma2 "+str(self.sigma2)+" l "
+ str(self.l)+" vol "+str(self.vol)+" nSL "+str(self.nSL)+" nSL2 "+str(self.nSL2)+" nf "
+ str(self.nf)+" \n")
self.fnWriteData2File(fp, cName, z)
def fnWritePar2Dict(self, rdict, cName, z):
rdict[cName] = {}
rdict[cName]['header'] = "Box2Err " + cName + " z " + str(self.z) + " sigma1 " + str(self.sigma1) + \
" sigma2 " + str(self.sigma2) + " l " + str(self.l) + " vol " + str(self.vol) + \
" nSL " + str(self.nSL) + " nSL2 " + str(self.nSL2) + " nf " + str(self.nf)
rdict[cName]['z'] = self.z
rdict[cName]['sigma1'] = self.sigma1
rdict[cName]['sigma2'] = self.sigma2
rdict[cName]['l'] = self.l
rdict[cName]['vol'] = self.vol
rdict[cName]['nSL'] = self.nSL
rdict[cName]['nSL2'] = self.nSL2
rdict[cName]['nf'] = self.nf
rdict[cName] = self.fnWriteData2Dict(rdict[cName], z)
return rdict
class ComponentBox(Box2Err):
""" Box2Err from a components.Component object"""
def __init__(self, molecule=None, xray_wavelength=None, **kwargs):
assert molecule is not None, 'Molecule must be specified'
assert isinstance(molecule, Component), 'Molecule must be a components.Component object'
super().__init__(dvolume=molecule.cell_volume, dlength=molecule.length, **kwargs)
self.fnSetnSL(*molecule.fnGetnSL(xray_wavelength))
# TODO: A headgroup class must contain an "innerleaflet" flag that determines whether the headgroup
# is in the inner or outer leaflet. The profiles so obtained should be flipped. This should perhaps
# be standardized, (1) by creating a CompositeHeadgroup class that has this flag already, and (2) by
# finding a reasonable way of flipping the profile after calculating it (removes lots of if statements)
class PC(CompositenSLDObj):
def __init__(self, name='PC', innerleaflet=False, xray_wavelength=None, **kwargs):
# innerleaflet flag locates it in the inner leaflet and flips the order of cg, phosphate,
# and choline groups. If False, it's the outer leaflet
super().__init__(name=name, **kwargs)
from components import carbonyl_glycerol, phosphate, choline
self.cg = ComponentBox(name='cg', molecule=carbonyl_glycerol, xray_wavelength=xray_wavelength)
self.phosphate = ComponentBox(name='phosphate', molecule=phosphate, xray_wavelength=xray_wavelength)
self.choline = ComponentBox(name='choline', molecule=choline, xray_wavelength=xray_wavelength)
self.innerleaflet = innerleaflet
self.groups = {"cg": self.cg, "phosphate": self.phosphate, "choline": self.choline}
if innerleaflet:
self.cg.sigma2, self.cg.sigma1 = 2.53, 2.29
self.phosphate.sigma2, self.phosphate.sigma1 = 2.29, 2.02
self.choline.sigma2, self.choline.sigma1 = 2.02, 2.26
else:
self.cg.sigma1, self.cg.sigma2 = 2.53, 2.29
self.phosphate.sigma1, self.phosphate.sigma2 = 2.29, 2.02
self.choline.sigma1, self.choline.sigma2 = 2.02, 2.26
self.cg.nf=1
self.phosphate.nf=1
self.choline.nf=1
self.l = 9.575
self.init_l = self.l
self.vol = self.cg.vol+self.phosphate.vol+self.choline.vol
self.nSL = self.cg.nSL+self.phosphate.nSL+self.choline.nSL
self.ph_relative_pos = .58
self.nf = 1.
self.fnFindSubgroups()
self.fnAdjustParameters()
def fnAdjustParameters(self):
# make sure no group is larger than the entire length of the headgroup
for g in self.subgroups:
g.l = min(self.init_l, g.l)
if self.innerleaflet:
self.cg.z = self.z + 0.5 * self.l - 0.5 * self.cg.l
self.choline.z = self.z - 0.5 * self.l + 0.5 * self.choline.l
z0 = self.z - 0.5 * self.l + 0.5 * self.phosphate.l
z1 = self.z + 0.5 * self.l - 0.5 * self.phosphate.l
self.phosphate.z = z0 + (z1 - z0) * (1 - self.ph_relative_pos)
else:
self.cg.z = self.z - 0.5 * self.l + 0.5*self.cg.l
self.choline.z = self.z + 0.5 * self.l - 0.5*self.choline.l
z0 = self.z - 0.5*self.l + 0.5 * self.phosphate.l
z1 = self.z + 0.5 * self.l - 0.5*self.phosphate.l
self.phosphate.z = z0 + (z1 - z0) * self.ph_relative_pos
def fnSet(self, l=None, ph_relative_pos=None, cg_nSL=None, ch_nSL=None, ph_nSL=None):
if cg_nSL is not None:
self.cg.nSL = cg_nSL
if ch_nSL is not None:
self.choline.nSL = ch_nSL
if ph_nSL is not None:
self.phosphate.nSL = ph_nSL
if l is not None:
self.l = l
if ph_relative_pos is not None:
self.ph_relative_pos = ph_relative_pos
self.fnAdjustParameters()
def fnGetLowerLimit(self):
return self.choline.fnGetLowerLimit() if self.innerleaflet else self.cg.fnGetLowerLimit()
def fnGetUpperLimit(self):
return self.cg.fnGetUpperLimit() if self.innerleaflet else self.choline.fnGetUpperLimit()
def fnGetnSL(self, bulknsld=None):
return self.cg.nSL + self.phosphate.nSL + self.choline.nSL
def fnGetZ(self):
return self.z
def fnSetSigma(self, sigma):
self.cg.sigma1 = sigma
self.cg.sigma2 = sigma
self.phosphate.sigma1 = sigma
self.phosphate.sigma2 = sigma
self.choline.sigma1 = sigma
self.choline.sigma2 = sigma
def fnSetZ(self, dz):
self.z = dz
self.fnAdjustParameters()
def fnWritePar2File(self, fp, cName, z):
prefix = "PCm" if self.innerleaflet else "PC"
fp.write(prefix + " "+cName+" z "+str(self.z)+" l "+str(self.l)+" vol " +
str(self.cg.vol + self.phosphate.vol + self.choline.vol)+" nf " + str(self.nf)+" \n")
self.fnWriteData2File(fp, cName, z)
super().fnWritePar2File(fp, cName, z)
def fnWritePar2Dict(self, rdict, cName, z):
prefix = "PCm" if self.innerleaflet else "PC"
rdict[cName] = {}
rdict[cName]['header'] = prefix + " " + cName + " z " + str(self.z) + " l " + str(self.l) + " vol "
rdict[cName]['header'] += str(self.cg.vol + self.phosphate.vol + self.choline.vol) + " nf " + str(self.nf)
rdict[cName]['z'] = self.z
rdict[cName]['l'] = self.l
rdict[cName]['vol'] = self.cg.vol + self.phosphate.vol + self.choline.vol
rdict[cName]['nf'] = self.nf
rdict[cName] = self.fnWriteData2Dict(rdict[cName], z)
rdict = super().fnWritePar2Dict(rdict, cName, z)
return rdict
class PCm(PC):
# deprecated. Use PC(innerleaflet=True)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cg.sigma2 = 2.53
self.cg.sigma1 = 2.29
self.phosphate.sigma2 = 2.29
self.phosphate.sigma1 = 2.02
self.choline.sigma2 = 2.02
self.choline.sigma1 = 2.26
self.fnAdjustParameters()
def fnAdjustParameters(self):
self.cg.z = self.z + 0.5 * self.l - 0.5 * self.cg.l
self.choline.z = self.z - 0.5 * self.l + 0.5 * self.choline.l
z0 = self.z - 0.5 * self.l + 0.5 * self.phosphate.l
z1 = self.z + 0.5 * self.l - 0.5 * self.phosphate.l
self.phosphate.z = z0 + (z1 - z0) * (1 - self.ph_relative_pos)
def fnGetLowerLimit(self):
return self.choline.fnGetLowerLimit()
def fnGetUpperLimit(self):
return self.cg.fnGetUpperLimit()
def fnWritePar2File(self, fp, cName, z):
fp.write("PCm " + cName + " z " + str(self.z) + " l " + str(self.l) + " vol " +
str(self.cg.vol + self.phosphate.vol + self.choline.vol) + " nf " + str(self.nf) + " \n")
self.fnWriteData2File(fp, cName, z)
super().fnWritePar2File(fp, cName, z)
def fnWritePar2Dict(self, rdict, cName, z):
rdict[cName] = {}
rdict[cName]['header'] = "PCm " + " " + cName + " z " + str(self.z) + " l " + str(self.l) + " vol "
rdict[cName]['header'] += str(self.cg.vol + self.phosphate.vol + self.choline.vol) + " nf " + str(self.nf)
rdict[cName]['z'] = self.z
rdict[cName]['l'] = self.l
rdict[cName]['vol'] = self.cg.vol + self.phosphate.vol + self.choline.vol
rdict[cName]['nf'] = self.nf
rdict[cName] = self.fnWriteData2Dict(rdict[cName], z)
rdict = super().fnWritePar2Dict(rdict, cName, z)
return rdict
class BLM(CompositenSLDObj):
def __init__(self, lipids, lipid_nf, xray_wavelength=None, **kwargs):
""" Free bilayer object. Requires:
o lipids: a list of components.Lipid objects
o lipid_nf: a list of number fractions (not necessarily normalized) of
equal length to 'lipids'
To use an xray probe, set xray_wavelength to the appropriate value in Angstroms."""
def _unpack_lipids():
""" Helper function for BLM classes that unpacks a lipid list into headgroup objects
and lists of acyl chain and methyl volumes and nSLs. Creates the following attributes:
o headgroups1: a list of inner leaflet headgroup objects
o headgroups2: a list of outer leaflet headgroup objects
NB: each object in headgroups1 and headgroups2 is created as a standalone attribute in "self"
so that searching for all nSLDObj in self will return each headgroup individually as
headgroup1_1, headgroup1_2, ... headgroup1_n for n lipids. Similarly for headgroup2.
o vol_acyl_lipids: a numpy array of acyl chain volumes
o vol_methyl_lipids: a numpy array of methyl volumes
o nsl_acyl_lipids: a numpy array of acyl chain nSL
o nsl_methyl_lipids: a numpy array of methyl nSL
"""
# create objects for each lipid headgroup and a composite tail object
# TODO: create separate lipid objects so methyl sigmas can be different for different species
for i, lipid in enumerate(lipids):
ihg_name = 'headgroup1_%i' % (i + 1)
ohg_name = 'headgroup2_%i' % (i + 1)
if isinstance(lipid.headgroup, Component):
# populates nSL, nSL2, vol, and l
ihg_obj = ComponentBox(name=ihg_name, molecule=lipid.headgroup, xray_wavelength=xray_wavelength)
ohg_obj = ComponentBox(name=ohg_name, molecule=lipid.headgroup, xray_wavelength=xray_wavelength)
elif issubclass(lipid.headgroup, CompositenSLDObj):
ihg_obj = lipid.headgroup(name=ihg_name, innerleaflet=True, xray_wavelength=xray_wavelength)
ohg_obj = lipid.headgroup(name=ohg_name, innerleaflet=False, xray_wavelength=xray_wavelength)
else:
raise TypeError('Lipid.hg must be a Headgroup object or a subclass of CompositenSLDObj')
# Note that because there's always one lipid, the objects self.headgroups1[0]
# and self.headgroups2[0] always exist
self.__setattr__(ihg_name, ihg_obj)
self.headgroups1.append(self.__getattribute__(ihg_name))
self.__setattr__(ohg_name, ohg_obj)
self.headgroups2.append(self.__getattribute__(ohg_name))
# find null headgroups to exclude from averaging over headgroup properties
self.null_hg1 = numpy.array([hg.vol <= 0.0 for hg in self.headgroups1], dtype=bool)
self.null_hg2 = numpy.array([hg.vol <= 0.0 for hg in self.headgroups2], dtype=bool)
self.vol_acyl_lipids[i] = lipid.tails.cell_volume
self.vol_methyl_lipids[i] = lipid.methyls.cell_volume
if xray_wavelength is None:
self.nsl_acyl_lipids[i] = lipid.tails.sld * lipid.tails.cell_volume * 1e-6
self.nsl_methyl_lipids[i] = lipid.methyls.sld * lipid.methyls.cell_volume * 1e-6
else:
self.nsl_acyl_lipids[i] = xray_sld(lipid.tails.formula, wavelength=xray_wavelength)[
0] * lipid.tails.cell_volume * 1e-6
self.nsl_methyl_lipids[i] = xray_sld(lipid.methyls.formula, wavelength=xray_wavelength)[
0] * lipid.methyls.cell_volume * 1e-6
self.initial_hg1_lengths = numpy.array([hg1.l for hg1 in self.headgroups1])
super().__init__(**kwargs)
assert len(lipids) == len(lipid_nf), \
'List of lipids and number fractions must be of equal length, not %i and %i' % (len(lipids), len(lipid_nf))
assert len(lipids) > 0, 'Must specify at least one lipid'
# normalize number fractions. This allows ratios of lipids to be given instead of number fractions
self.lipid_nf = numpy.array(lipid_nf) / numpy.sum(lipid_nf)
n_lipids = len(lipids)
self.lipids = lipids # store this information
self.headgroups1 = [] # list of inner headgroups
self.headgroups2 = [] # list of outer headgroups
self.null_hg1 = numpy.zeros(n_lipids)
self.null_hg2 = numpy.zeros(n_lipids)
self.vol_acyl_lipids = numpy.zeros(n_lipids) # list of acyl chain volumes
self.nsl_acyl_lipids = numpy.zeros(n_lipids) # list of acyl chain nsls
self.vol_methyl_lipids = numpy.zeros(n_lipids) # list of acyl chain methyl volumes
self.nsl_methyl_lipids = numpy.zeros(n_lipids) # list of acyl chain methyl nsls
_unpack_lipids()
self.lipid1 = Box2Err(name='lipid1')
self.methyl1 = Box2Err(name='methyl1')
self.methyl2 = Box2Err(name='methyl2')
self.lipid2 = Box2Err(name='lipid2')
self.defect_hydrocarbon = Box2Err(name='defect_hc')
self.defect_headgroup = Box2Err(name='defect_hg')
self.nf = 1.
self.vf_bilayer = 1.0
self.absorb = 0.
self.l_lipid1 = 11.
self.l_lipid2 = 11.
self.bulknsld = -0.56e-6
self.normarea = 60.
self.startz = 50.
self.sigma = 2.
self.methyl_sigma = 2.
self.radius_defect = 100.
self.hc_substitution_1 = 0
self.hc_substitution_2 = 0
self._calc_av_hg()
self.initial_hg1_l = self.av_hg1_l
self.fnAdjustParameters()
self.fnFindSubgroups()
def _calc_av_hg(self):
# calculate average headgroup lengths, ignore zero volume (e.g. cholesterol)
self.av_hg1_l = numpy.sum(numpy.array([hg.l for hg, use in zip(self.headgroups1, ~self.null_hg1) if use]) *
self.lipid_nf[~self.null_hg1]) / numpy.sum(self.lipid_nf[~self.null_hg1])
self.av_hg2_l = numpy.sum(numpy.array([hg.l for hg, use in zip(self.headgroups2, ~self.null_hg2) if use]) *
self.lipid_nf[~self.null_hg2]) / numpy.sum(self.lipid_nf[~self.null_hg2])
def fnAdjustParameters(self):
self._adjust_lipids()
self._adjust_z(self.startz + self.av_hg1_l)
self._adjust_defects()
self.fnSetSigma(self.sigma)
def _adjust_lipids(self):
self.l_lipid1 = max(self.l_lipid1, 0.01)
self.l_lipid2 = max(self.l_lipid2, 0.01)
for nf in self.lipid_nf:
nf = max(nf, 0)
# this is changed normalization behavior, but it's a bit more intuitive
self.lipid_nf /= numpy.sum(self.lipid_nf)
self.vf_bilayer = max(self.vf_bilayer, 1E-5)
self.vf_bilayer = min(self.vf_bilayer, 1)
# calculate average headgroup lengths, ignore zero volume (e.g. cholesterol)
self.av_hg1_l = numpy.sum(numpy.array([hg.l for hg, use in zip(self.headgroups1, ~self.null_hg1) if use]) *
self.lipid_nf[~self.null_hg1]) / numpy.sum(self.lipid_nf[~self.null_hg1])
self.av_hg2_l = numpy.sum(numpy.array([hg.l for hg, use in zip(self.headgroups2, ~self.null_hg2) if use]) *
self.lipid_nf[~self.null_hg2]) / numpy.sum(self.lipid_nf[~self.null_hg2])
# outer hydrocarbons
l_ohc = self.l_lipid2
nf_ohc_lipid = self.lipid_nf
V_ohc = numpy.sum(nf_ohc_lipid * (self.vol_acyl_lipids - self.vol_methyl_lipids))
nSL_ohc = numpy.sum(nf_ohc_lipid * (self.nsl_acyl_lipids - self.nsl_methyl_lipids))
self.normarea = V_ohc / l_ohc
c_s_ohc = self.vf_bilayer
c_A_ohc = 1
c_V_ohc = 1
self.lipid2.l = l_ohc
self.lipid2.vol = V_ohc
self.lipid2.nSL = nSL_ohc
self.lipid2.nf = c_s_ohc * c_A_ohc * c_V_ohc
# outer methyl
nf_om_lipid = nf_ohc_lipid
# cholesterol has a methyl volume of zero and does not contribute
V_om = numpy.sum(nf_om_lipid * self.vol_methyl_lipids)
l_om = l_ohc * V_om / V_ohc
nSL_om = numpy.sum(nf_om_lipid * self.nsl_methyl_lipids)
c_s_om = c_s_ohc
c_A_om = 1
c_V_om = 1
self.methyl2.l = l_om
self.methyl2.vol = V_om
self.methyl2.nSL = nSL_om
self.methyl2.nf = c_s_om * c_A_om * c_V_om
# inner hydrocarbons
l_ihc = self.l_lipid1
nf_ihc_lipid = nf_ohc_lipid
V_ihc = numpy.sum(nf_ihc_lipid * (self.vol_acyl_lipids - self.vol_methyl_lipids))
nSL_ihc = numpy.sum(nf_ihc_lipid * (self.nsl_acyl_lipids - self.nsl_methyl_lipids))
c_s_ihc = self.vf_bilayer
c_A_ihc = self.normarea * l_ihc / V_ihc
c_V_ihc = 1
self.lipid1.l = l_ihc
self.lipid1.vol = V_ihc
self.lipid1.nSL = nSL_ihc
self.lipid1.nf = c_s_ihc * c_A_ihc * c_V_ihc
# inner methyl
nf_im_lipid = nf_ihc_lipid
# cholesterol has a methyl volume of zero and does not contribute
V_im = numpy.sum(nf_im_lipid * self.vol_methyl_lipids)
l_im = l_ihc * V_im / V_ihc
nSL_im = numpy.sum(nf_im_lipid * self.nsl_methyl_lipids)
c_s_im = c_s_ihc
c_A_im = c_A_ihc
c_V_im = 1
self.methyl1.l = l_im
self.methyl1.vol = V_im
self.methyl1.nSL = nSL_im
self.methyl1.nf = c_s_im * c_A_im * c_V_im
# headgroup size and position
for hg1, nf_ihc, hg2, nf_ohc in zip(self.headgroups1, nf_ihc_lipid, self.headgroups2, nf_ohc_lipid):
hg2.nf = c_s_ohc * c_A_ohc * nf_ohc * (1 - self.hc_substitution_2)
hg1.nf = c_s_ihc * c_A_ihc * nf_ihc * (1 - self.hc_substitution_1)
if hasattr(hg1, 'fnAdjustParameters'):
hg1.fnAdjustParameters()
if hasattr(hg2, 'fnAdjustParameters'):
hg2.fnAdjustParameters()
# defects
def _adjust_defects(self):
hclength = self.lipid1.l + self.methyl1.l + self.methyl2.l + self.lipid2.l
hglength = self.av_hg1_l + self.av_hg2_l
if self.radius_defect<(0.5*(hclength+hglength)):
self.radius_defect = 0.5 * (hclength+hglength)
volhalftorus = numpy.pi**2 * (self.radius_defect - (2. * hclength / 3. / numpy.pi)) * hclength * hclength / 4.
volcylinder = numpy.pi * self.radius_defect * self.radius_defect * hclength
defectarea = volhalftorus / volcylinder * (1 - self.vf_bilayer) * self.normarea
self.defect_hydrocarbon.vol = defectarea * hclength
self.defect_hydrocarbon.l = hclength
self.defect_hydrocarbon.z = self.lipid1.z - 0.5 * self.lipid1.l + 0.5 * hclength
self.defect_hydrocarbon.nSL = self.lipid2.nSL / self.lipid2.vol * self.defect_hydrocarbon.vol
self.defect_hydrocarbon.fnSetSigma(self.sigma)
self.defect_hydrocarbon.nf = 1
defectratio = self.defect_hydrocarbon.vol / self.lipid2.vol
self.defect_headgroup.vol = defectratio * numpy.sum([hg.nf * hg.vol for hg in self.headgroups2])
self.defect_headgroup.l = hclength + hglength
self.defect_headgroup.z = self.lipid1.z - 0.5 * self.lipid1.l - \
0.5 * self.av_hg1_l + 0.5 * (hclength + hglength)
self.defect_headgroup.nSL = defectratio * numpy.sum([hg.nf * hg.fnGetnSL(self.bulknsld)
for hg in self.headgroups2])
self.defect_headgroup.fnSetSigma(self.sigma)
self.defect_headgroup.nf = 1
def _adjust_z(self, startz):
# startz is the position of the hg1/lipid1 interface.
# change here: use average headgroup length instead of a specific headgroup
self.lipid1.z= startz + 0.5 * self.lipid1.l
self.methyl1.z = self.lipid1.z + 0.5 * (self.lipid1.l + self.methyl1.l)
self.methyl2.z = self.methyl1.z + 0.5 * (self.methyl1.l + self.methyl2.l)
self.lipid2.z = self.methyl2.z + 0.5 * (self.methyl2.l + self.lipid2.l)
for hg1, hg2 in zip(self.headgroups1, self.headgroups2):
hg1.fnSetZ(self.lipid1.z - 0.5 * self.lipid1.l - 0.5 * hg1.l)
hg2.fnSetZ(self.lipid2.z + 0.5 * self.lipid2.l + 0.5 * hg2.l)
# return value of center of the membrane
def fnGetCenter(self):
return self.methyl1.z + 0.5 * self.methyl1.l
# Use limits of molecular subgroups
def fnGetLowerLimit(self):
return min([hg.fnGetLowerLimit() for hg in self.headgroups1])
def fnGetUpperLimit(self):
return max([hg.fnGetUpperLimit() for hg in self.headgroups2])
def fnSet(self, sigma, bulknsld, startz, l_lipid1, l_lipid2, vf_bilayer,
nf_lipids=None, hc_substitution_1=0.,
hc_substitution_2=0., radius_defect=100.):
self.sigma = sigma
self.bulknsld = bulknsld
self.startz = startz
self.l_lipid1 = l_lipid1
self.l_lipid2 = l_lipid2
self.vf_bilayer = vf_bilayer
if nf_lipids is not None: # pass None to keep lipid_nf unchanged
assert len(nf_lipids) == len(self.lipids), \
'nf_lipids must be same length as number of lipids in bilayer, not %i and %i' % (len(nf_lipids),
len(self.lipids))
self.lipid_nf = numpy.array(nf_lipids)
self.hc_substitution_1 = hc_substitution_1
self.hc_substitution_2 = hc_substitution_2
self.radius_defect = radius_defect
self.fnAdjustParameters()
def fnSetSigma(self, sigma):
for hg1, hg2 in zip(self.headgroups1, self.headgroups2):
hg1.fnSetSigma(sigma)
hg2.fnSetSigma(sigma)
self.lipid1.fnSetSigma(sigma,numpy.sqrt(sigma**2+self.methyl_sigma**2))
self.methyl1.fnSetSigma(numpy.sqrt(sigma**2+self.methyl_sigma**2), numpy.sqrt(sigma**2+self.methyl_sigma**2))
self.methyl2.fnSetSigma(numpy.sqrt(sigma**2+self.methyl_sigma**2), numpy.sqrt(sigma**2+self.methyl_sigma**2))
self.lipid2.fnSetSigma(numpy.sqrt(sigma**2+self.methyl_sigma**2),sigma)
self.defect_hydrocarbon.fnSetSigma(sigma)
self.defect_headgroup.fnSetSigma(sigma)
def fnWritePar2File(self, fp, cName, z):
super().fnWritePar2File(fp, cName, z)
self.fnWriteConstant(fp, cName+"_normarea", self.normarea, 0, z)
def fnWritePar2Dict(self, rdict, cName, z):
rdict = super().fnWritePar2Dict(rdict, cName, z)
rdict = self.fnWriteConstant2Dict(rdict, cName + ".normarea", self.normarea, 0, z)
return rdict
class ssBLM(BLM):
"""
Solid supported lipid bilayer
"""
def __init__(self, lipids, lipid_nf, xray_wavelength=None, **kwargs):
""" Solid supported bilayer object. Requires:
o lipids: a list of components.Lipid objects
o lipid_nf: a list of number fractions (not necessarily normalized) of
equal length to 'lipids'
To use an xray probe, set xray_wavelength to the appropriate value in Angstroms.
"""
# add ssBLM-specific subgroups
self.substrate = Box2Err(name='substrate')
self.siox = Box2Err(name='siox')
self.substrate.l = 40
self.substrate.z = 0
self.substrate.nf = 1
self.rho_substrate = 2.07e-6
self.l_siox = 1
self.rho_siox = 3.55e-6
self.siox.l = 20
self.siox.z = self.substrate.z + self.substrate.l / 2.0 + self.siox.l / 2.0
self.siox.nf = 1
self.l_submembrane = 10.
self.global_rough = 2.0
super().__init__(lipids, lipid_nf, xray_wavelength=xray_wavelength, **kwargs)
def fnAdjustParameters(self):
self._adjust_lipids()
# substrate
self.substrate.vol = self.normarea * self.substrate.l
self.substrate.nSL = self.rho_substrate * self.substrate.vol
self.siox.l = self.l_siox
self.siox.vol = self.normarea * self.siox.l
self.siox.nSL = self.rho_siox * self.siox.vol
self.siox.z=self.substrate.z + self.substrate.l / 2 + 0.5 * self.siox.l
self._adjust_z(self.substrate.z + self.substrate.l / 2 + self.siox.l + self.l_submembrane + self.av_hg1_l)
self._adjust_defects()
self.fnSetSigma(self.sigma)
def fnSetSigma(self, sigma):
super().fnSetSigma(sigma)
self.substrate.fnSetSigma(self.global_rough)
self.siox.fnSetSigma(self.global_rough)
def fnGetLowerLimit(self):
return self.substrate.fnGetLowerLimit()
# does this make sense since this goes to negative z and isn't intended to be used?
def fnSet(self, _sigma, _bulknsld, _global_rough, _rho_substrate, _rho_siox, _l_siox, _l_submembrane, _l_lipid1,
_l_lipid2, _vf_bilayer, _nf_lipids=None, _hc_substitution_1=0.,
_hc_substitution_2=0., _radius_defect=100.):
self.sigma = _sigma
self.bulknsld = _bulknsld
self.global_rough = _global_rough
self.rho_substrate = _rho_substrate
self.rho_siox = _rho_siox
self.l_siox = _l_siox
self.l_submembrane = _l_submembrane
self.l_lipid1 = _l_lipid1
self.l_lipid2 = _l_lipid2
self.vf_bilayer = _vf_bilayer
if _nf_lipids is not None: # pass None to keep lipid_nf unchanged
assert len(_nf_lipids)==len(self.lipids), \
'nf_lipids must be same length as number of lipids in bilayer, not %i and %i' % \
(len(_nf_lipids), len(self.lipids))
self.lipid_nf = numpy.array(_nf_lipids)
self.hc_substitution_1 = _hc_substitution_1
self.hc_substitution_2 = _hc_substitution_2
self.radius_defect = _radius_defect
self.fnAdjustParameters()
# ------------------------------------------------------------------------------------------------------
# Tethered Lipid bilayer
# ------------------------------------------------------------------------------------------------------
class tBLM(BLM):
"""
Tethered lipid bilayer
"""
def __init__(self, lipids, lipid_nf, tether, filler, xray_wavelength=None, **kwargs):
"""
Tethered lipid bilayer. Requires:
o tether: a components.Tether object o lipids: a list of components.Lipid objects
o lipid_nf: a list of number fractions (not necessarily normalized) of
equal length to 'lipids' describing the tether.
o filler: a components.Component object describing the filler molecule, including its length
To use an xray probe, set xray_wavelength to the appropriate value in Angstroms.
"""
# add ssBLM-specific subgroups
self.substrate = Box2Err(name='substrate')
self.nf_tether = 0.3
self.l_tether=8.0
self.mult_tether = 7.0/3.0
self.xray_wavelength = xray_wavelength
# change these to Headgroup2Box
self.bME = ComponentBox(name='bME', molecule=filler, xray_wavelength=xray_wavelength)
self.tether_bme = Box2Err(name='tether_bme')
self.tether_free = Box2Err(name='tether_free')
self.tether_hg = Box2Err(name='tether_hg')
self.tether = Component(name='tether', formula=tether.tether.formula,
cell_volume=tether.tether.cell_volume, length=self.l_tether)
self.tether.nSLs = self.tether.fnGetnSL(xray_wavelength=xray_wavelength)
self.tetherg = Component(name='tetherg', formula=tether.tetherg.formula,
cell_volume=tether.tetherg.cell_volume, length=10.0)
self.tetherg.nSLs = self.tetherg.fnGetnSL(xray_wavelength=xray_wavelength)
self.substrate.l = 40
self.substrate.z = 0
self.substrate.nf = 1
self.rho_substrate = 2.07e-6
self.global_rough = 2.0
self.vol_acyl_tether = tether.tails.cell_volume
self.vol_methyl_tether = tether.methyls.cell_volume
if xray_wavelength is None:
self.nSL_acyl_tether = tether.tails.sld * tether.tails.cell_volume * 1e-6
self.nSL_methyl_tether = tether.methyls.sld * tether.methyls.cell_volume * 1e-6
else:
self.nSL_acyl_tether = xray_sld(tether.tails.formula, wavelength=xray_wavelength)[0] * tether.tails.cell_volume * 1e-6
self.nSL_methyl_tether = xray_sld(tether.methyls.formula, wavelength=xray_wavelength)[0] * tether.methyls.cell_volume * 1e-6
self.initial_bME_l = self.bME.l
super().__init__(lipids, lipid_nf, xray_wavelength=xray_wavelength, **kwargs)
def fnAdjustParameters(self):
self._adjust_lipids()
# substrate
self.substrate.vol = self.normarea * self.substrate.l
self.substrate.nSL = self.rho_substrate * self.substrate.vol
# set all lengths
self.bME.z = 0.5 * self.bME.l + self.substrate.z + self.substrate.l * 0.5
self.tether_bme.z = self.bME.z
self.tether_free.z = self.tether_bme.z + 0.5 * self.tether_bme.l + 0.5 * self.tether_free.l
self.tether_hg.z = self.tether_free.z + 0.5 * self.tether_free.l + 0.5 * self.tether_hg.l
self._adjust_z(self.tether_hg.z + 0.5 * self.tether_hg.l)
self._adjust_defects()
self.fnSetSigma(self.sigma)
def _adjust_lipids(self):
# sufficiently different from parent class that code is repeated here with small adjustments
# TODO: split into inner and outer leaflets so this can be made more efficient
self.l_lipid1 = max(self.l_lipid1, 0.01)
self.l_lipid2 = max(self.l_lipid2, 0.01)
for nf in self.lipid_nf:
nf = max(nf, 0)
# this is changed normalization behavior, but it's a bit more intuitive
self.lipid_nf /= numpy.sum(self.lipid_nf)
self.vf_bilayer = max(self.vf_bilayer, 1E-5)
self.vf_bilayer = min(self.vf_bilayer, 1)
# outer hydrocarbons
l_ohc = self.l_lipid2
nf_ohc_lipid = self.lipid_nf
V_ohc = numpy.sum(nf_ohc_lipid * (self.vol_acyl_lipids - self.vol_methyl_lipids))
nSL_ohc = numpy.sum(nf_ohc_lipid * (self.nsl_acyl_lipids - self.nsl_methyl_lipids))