forked from MicPellegrino/densmap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdensmap.py
More file actions
2050 lines (1768 loc) · 75.2 KB
/
densmap.py
File metadata and controls
2050 lines (1768 loc) · 75.2 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
"""
A little library for processing density maps from molecular dynamics simulations
"""
import math
import numpy as np
import matplotlib as mpl
mpl.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.animation as manimation
import scipy as sc
from scipy import signal
import skimage as sk
from skimage import measure
"""
Circle fitting library (thanks to marian42: https://github.com/marian42/circle-fit.git)
"""
import circle_fit as cf
################################################################################
################################################################################
################################################################################
# A bit sloppy, but it works:
# True: 2021 (with header)
# False: 2020 (without header)
READ_HEADER = True
"""
#########################################################
### From strata program (courtesy of Petter Johanson) ###
#########################################################
"""
# 2021
FIELDS = ['X', 'Y', 'N', 'T', 'M', 'U', 'V']
def read_data(filename, decimals=5):
"""Read field data from a file name.
Determines which of the simple formats in this module to use and
returns data read using the proper function.
Coordinates are rounded to input number of decimals.
Args:
filename (str): A file to read data from.
Keyword Args:
decimals (int): Number of decimals for coordinates.
Returns:
(dict, dict): 2-tuple of dict's with data and information. See
strata.dataformats.read.read_data_file for more information.
"""
# 2021
if READ_HEADER :
with open(filename, 'rb') as fp:
fields, num_values, info = read_header(fp)
data = read_values(fp, num_values, fields)
x0, y0 = info['origin']
nx, ny = info['shape']
dx, dy = info['spacing']
x = x0 + dx * (np.arange(nx) + 0.5)
y = y0 + dy * (np.arange(ny) + 0.5)
xs, ys = np.meshgrid(x, y, indexing='ij')
grid = np.zeros((nx, ny), dtype=[(l, np.float) for l in FIELDS])
grid['X'] = xs
grid['Y'] = ys
for l in ['N', 'T', 'M', 'U', 'V']:
grid[l][data['IX'], data['IY']] = data[l]
grid = grid.ravel()
return {l: grid[l] for l in FIELDS}, info
# 2020
else:
def guess_read_function(filename):
"""Return handle to binary or plaintext function."""
def is_binary(filename, checksize=512):
with open(filename, 'r') as fp:
try:
fp.read(checksize)
return False
except UnicodeDecodeError:
return True
if is_binary(filename):
return read_binsimple
else:
return read_plainsimple
read_function = guess_read_function(filename)
data = read_function(filename)
for coord in ['X', 'Y']:
data[coord] = data[coord].round(decimals)
info = calc_information(data['X'], data['Y'])
x0, y0 = info['origin']
dx, dy = info['spacing']
nx, ny = info['shape']
x = x0 + dx * np.arange(nx, dtype=np.float64)
y = y0 + dy * np.arange(ny, dtype=np.float64)
xs, ys = np.meshgrid(x, y, indexing='ij')
data['X'] = xs.ravel()
data['Y'] = ys.ravel()
return data, info
#2020
def calc_information(X, Y):
"""Return a dict of system information calculated from input cell positions.
Calculates system origin ('origin'), bin spacing ('spacing'), number of cells
('num_bins') and shape ('shape').
Args:
X, Y (array_like): Arrays with cell positions.
Returns:
dict: Information about system in dictionary.
"""
def calc_shape(X, Y):
data = np.zeros((len(X), ), dtype=[('X', np.float), ('Y', np.float)])
data['X'] = X
data['Y'] = Y
data.sort(order=['Y', 'X'])
y0 = data['Y'][0]
nx = 1
try:
while np.abs(data['Y'][nx] - y0) < 1e-4:
nx += 1
except IndexError:
pass
ny = len(X) // nx
return nx, ny
def calc_spacing(X, Y, nx, ny):
def calc_1d(xs, n):
x0 = np.min(xs)
x1 = np.max(xs)
try:
return (x1 - x0) / (n - 1)
except:
return 0.0
dx = calc_1d(X, nx)
dy = calc_1d(Y, ny)
return dx, dy
def calc_origin(X, Y):
return X.min(), Y.min()
if len(X) != len(Y):
raise ValueError("Lengths of X and Y arrays not equal")
nx, ny = calc_shape(X, Y)
dx, dy = calc_spacing(X, Y, nx, ny)
x0, y0 = calc_origin(X, Y)
info = {
'shape': (nx, ny),
'spacing': (dx, dy),
'num_bins': nx * ny,
'origin': (x0, y0),
}
return info
# 2020
def read_binsimple(filename):
"""Return data and information read from a simple binary format.
Args:
filename (str): A file to read data from.
Returns:
dict: Data with field labels as keys.
"""
def read_file(filename):
# Fixed field order of format
fields = ['X', 'Y', 'N', 'T', 'M', 'U', 'V']
raw_data = np.fromfile(filename, dtype='float32')
# Unpack into dictionary
data = {}
stride = len(fields)
for i, field in enumerate(fields):
data[field] = raw_data[i::stride]
return data
data = read_file(filename)
return data
# 2020
def read_plainsimple(filename):
"""Return field data from a simple plaintext format.
Args:
filename (str): A file to read data from.
Returns:
dict: Data with field labels as keys.
"""
def read_file(filename):
raw_data = np.genfromtxt(filename, names=True)
# Unpack into dictionary
data = {}
for field in raw_data.dtype.names:
data[field] = raw_data[field]
return data
data = read_file(filename)
return data
# 2021
def read_values(fp, num_values, fields):
dtypes = {
'IX': np.uint64,
'IY': np.uint64,
'N': np.float32,
'T': np.float32,
'M': np.float32,
'U': np.float32,
'V': np.float32,
}
return {
l: np.fromfile(fp, dtype=dtypes[l], count=num_values)
for l in fields
}
#2021
def read_header(fp):
"""Read header information and forward the pointer to the data."""
def read_shape(line):
return tuple(int(v) for v in line.split()[1:3])
def read_spacing(line):
return tuple(float(v) for v in line.split()[1:3])
def read_num_values(line):
return int(line.split()[1].strip())
def parse_field_labels(line):
return line.split()[1:]
def read_header_string(fp):
buf_size = 1024
header_str = ""
while True:
buf = fp.read(buf_size)
pos = buf.find(b'\0')
if pos != -1:
header_str += buf[:pos].decode("ascii")
offset = buf_size - pos - 1
fp.seek(-offset, 1)
break
else:
header_str += buf.decode("ascii")
return header_str
info = {}
header_str = read_header_string(fp)
for line in header_str.splitlines():
line_type = line.split(maxsplit=1)[0].upper()
if line_type == "SHAPE":
info['shape'] = read_shape(line)
elif line_type == "SPACING":
info['spacing'] = read_spacing(line)
elif line_type == "ORIGIN":
info['origin'] = read_spacing(line)
elif line_type == "FIELDS":
fields = parse_field_labels(line)
elif line_type == "NUMDATA":
num_values = read_num_values(line)
info['num_bins'] = info['shape'][0] * info['shape'][1]
return fields, num_values, info
################################################################################
################################################################################
################################################################################
"""
Roughness parameter calculation
"""
rough_parameter = lambda a : (2.0/np.pi) * np.sqrt(a+1.0) * sc.special.ellipe(a/(a+1.0))
"""
Class for storing information regarding droplet spreding
"""
# Base class for storing flow data
"""
class flow_data :
# ...
"""
class droplet_data :
def __init__(droplet_data):
print("[densmap] Initializing contour data structure")
droplet_data.time = []
droplet_data.contour = []
droplet_data.branch_left = []
droplet_data.branch_right = []
droplet_data.foot_left = []
droplet_data.foot_right = []
droplet_data.angle_left = []
droplet_data.angle_right = []
droplet_data.sub_angle_left = []
droplet_data.sub_angle_right = []
droplet_data.cotangent_left = []
droplet_data.cotangent_right = []
droplet_data.circle_rad = []
droplet_data.circle_xc = []
droplet_data.circle_zc = []
droplet_data.circle_res = []
droplet_data.angle_circle = []
droplet_data.radius_circle = []
def merge(droplet_data, new_data):
new_time = [ droplet_data.time[-1] + t for t in new_data.time]
droplet_data.time = droplet_data.time + new_time
droplet_data.contour = droplet_data.contour + new_data.contour
droplet_data.branch_left = droplet_data.branch_left + new_data.branch_left
droplet_data.branch_right = droplet_data.branch_right + new_data.branch_right
droplet_data.foot_left = droplet_data.foot_left + new_data.foot_left
droplet_data.foot_right = droplet_data.foot_right + new_data.foot_right
droplet_data.angle_left = droplet_data.angle_left + new_data.angle_left
droplet_data.angle_right = droplet_data.angle_right + new_data.angle_right
droplet_data.cotangent_left = droplet_data.cotangent_left + new_data.cotangent_left
droplet_data.cotangent_right = droplet_data.cotangent_right + new_data.cotangent_right
droplet_data.circle_rad = droplet_data.circle_rad + new_data.circle_rad
droplet_data.circle_xc = droplet_data.circle_xc + new_data.circle_xc
droplet_data.circle_zc = droplet_data.circle_zc + new_data.circle_zc
droplet_data.circle_res = droplet_data.circle_res + new_data.circle_res
droplet_data.angle_circle = droplet_data.angle_circle + new_data.angle_circle
droplet_data.radius_circle = droplet_data.radius_circle + new_data.radius_circle
def save_to_file(droplet_data, save_dir):
print("[densmap] Saving to .txt files")
np.savetxt(save_dir+'/time.txt', np.array(droplet_data.time))
np.savetxt(save_dir+'/foot_l.txt', np.array(droplet_data.foot_left)[:,0])
np.savetxt(save_dir+'/foot_r.txt', np.array(droplet_data.foot_right)[:,0])
np.savetxt(save_dir+'/angle_l.txt', np.array(droplet_data.angle_left))
np.savetxt(save_dir+'/angle_r.txt', np.array(droplet_data.angle_right))
np.savetxt(save_dir+'/sub_angle_r.txt', np.array(droplet_data.sub_angle_right))
np.savetxt(save_dir+'/sub_angle_l.txt', np.array(droplet_data.sub_angle_left))
np.savetxt(save_dir+'/radius_fit.txt', droplet_data.radius_circle)
np.savetxt(save_dir+'/angle_fit.txt', droplet_data.angle_circle)
def plot_radius(droplet_data):
mpl.use("Agg")
droplet_data.spreading_radius = \
np.array(droplet_data.foot_right)-np.array(droplet_data.foot_left)
plt.figure()
plt.plot(droplet_data.time, droplet_data.spreading_radius[:,0], 'k-', label='contour')
plt.plot(droplet_data.time, droplet_data.radius_circle, 'g-', label='cap')
plt.title('Spreading radius', fontsize=20.0)
plt.xlabel('t [ps]', fontsize=20.0)
plt.ylabel('R(t) [nm]', fontsize=20.0)
plt.legend()
plt.show()
plt.savefig('spreading_radius.eps')
mpl.use("TkAgg")
def plot_angles(droplet_data):
mpl.use("Agg")
droplet_data.mean_contact_angle = \
0.5*(np.array(droplet_data.angle_right)+np.array(droplet_data.angle_left))
droplet_data.hysteresis = \
np.array(droplet_data.angle_right)-np.array(droplet_data.angle_left)
plt.figure()
plt.plot(droplet_data.time, droplet_data.mean_contact_angle, 'b-', label='average')
plt.plot(droplet_data.time, droplet_data.hysteresis, 'r-', label='difference')
plt.plot(droplet_data.time, droplet_data.angle_circle, 'g-', label='cap')
plt.title('Contact angle', fontsize=20.0)
plt.xlabel('t [ps]', fontsize=20.0)
plt.ylabel('theta(t) [deg]', fontsize=20.0)
plt.legend()
plt.show()
plt.savefig('contact_angles.eps')
mpl.use("TkAgg")
def movie_contour(droplet_data, crop_x, crop_z, dz, circle=True, contact_line=True, fun_sub=None, dfun_sub=None):
mpl.use("Agg")
print("[densmap] Producing movie of the interface dynamics")
FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title='Spreading Droplet Contour', artist='Michele Pellegrino',
comment='Just the tracked contour of a spreding droplet')
writer = FFMpegWriter(fps=30, metadata=metadata)
fig = plt.figure()
fig_cont, = plt.plot([], [], 'k-', linewidth=1.5)
# CURRENTLY TESTING: CONTACT LINE OVER ROUGH SUBSTRATES #
fig_left, = plt.plot([], [], 'r-', linewidth=1.0)
fig_right, = plt.plot([], [], 'b-', linewidth=1.0)
fig_pl, = plt.plot([], [], 'r.', linewidth=1.5)
fig_pr, = plt.plot([], [], 'b.', linewidth=1.5)
if not(fun_sub==None) :
x_eval = np.linspace(crop_x[0], crop_x[1], 500)
fig_substrate, = plt.plot([], [], 'm-', linewidth=1.0)
fig_substrate.set_data(x_eval, fun_sub(x_eval))
#########################################################
fig_cir, = plt.plot([], [], 'g-', linewidth=0.75)
plt.title('Droplet Spreading')
plt.xlabel('x [nm]')
plt.ylabel('z [nm]')
s = np.linspace(0,2*np.pi,250)
with writer.saving(fig, "contour_movie.mp4", 250):
for i in range( len(droplet_data.contour) ):
dx_l = dz * droplet_data.cotangent_left[i]
dx_r = dz * droplet_data.cotangent_right[i]
if circle :
circle_x = droplet_data.circle_xc[i] + droplet_data.circle_rad[i]*np.cos(s)
circle_z = droplet_data.circle_zc[i] + droplet_data.circle_rad[i]*np.sin(s)
fig_cont.set_data(droplet_data.contour[i][0,:], droplet_data.contour[i][1,:])
t_label = str(droplet_data.time[i])+' ps'
textvar = plt.text(1.5, 14.0, t_label)
if contact_line :
# CURRENTLY TESTING: CONTACT LINE OVER ROUGH SUBSTRATES #
fig_left.set_data([droplet_data.foot_left[i][0], droplet_data.foot_left[i][0]+dx_l],
[droplet_data.foot_left[i][1], droplet_data.foot_left[i][1]+dz])
fig_right.set_data([droplet_data.foot_right[i][0], droplet_data.foot_right[i][0]+dx_r],
[droplet_data.foot_right[i][1], droplet_data.foot_right[i][1]+dz])
fig_pl.set_data(droplet_data.foot_left[i][0], droplet_data.foot_left[i][1])
fig_pr.set_data(droplet_data.foot_right[i][0], droplet_data.foot_right[i][1])
#########################################################
if circle :
fig_cir.set_data(circle_x, circle_z)
plt.axis('scaled')
plt.xlim(crop_x[0], crop_x[1])
plt.ylim(crop_z[0], crop_z[1])
writer.grab_frame()
textvar.remove()
mpl.use("TkAgg")
def save_xvg(droplet_data, folder) :
for k in range(len(droplet_data.contour)) :
output_interface_xmgrace(droplet_data.contour[k], folder+"/interface_"+str(k+1).zfill(5)+".xvg")
class shear_data :
"""
Legend:
'bl' = bottom left
'br' = bottom right
'tl' = top left
'tr' = top right
"""
def __init__(self):
print("[densmap] Initializing contour data structure")
self.time = []
self.contour = []
self.branch = dict()
self.branch['bl'] = []
self.branch['br'] = []
self.branch['tl'] = []
self.branch['tr'] = []
self.foot = dict()
self.foot['bl'] = []
self.foot['br'] = []
self.foot['tl'] = []
self.foot['tr'] = []
self.angle = dict()
self.angle['bl'] = []
self.angle['br'] = []
self.angle['tl'] = []
self.angle['tr'] = []
self.cotangent = dict()
self.cotangent['bl'] = []
self.cotangent['br'] = []
self.cotangent['tl'] = []
self.cotangent['tr'] = []
self.circle_rad_l = []
self.circle_xc_l = []
self.circle_zc_l = []
self.circle_res_l = []
self.circle_rad_r = []
self.circle_xc_r = []
self.circle_zc_r = []
self.circle_res_r = []
self.xcom = []
self.zcom = []
self.angle_circle_mean = []
def save_to_file(self, save_dir):
print("[densmap] Saving to .txt files")
np.savetxt(save_dir+'/time.txt', np.array(self.time))
radius_upper = np.abs( np.array(self.foot['tr']) - np.array(self.foot['tl']) )
radius_lower = np.abs( np.array(self.foot['br']) - np.array(self.foot['bl']) )
position_upper = 0.5*np.abs( np.array(self.foot['tr']) + np.array(self.foot['tl']) )
position_lower = 0.5*np.abs( np.array(self.foot['br']) + np.array(self.foot['bl']) )
np.savetxt(save_dir+'/radius_upper.txt', radius_upper[:,0])
np.savetxt(save_dir+'/radius_lower.txt', radius_lower[:,0])
np.savetxt(save_dir+'/position_upper.txt', position_upper[:,0])
np.savetxt(save_dir+'/position_lower.txt', position_lower[:,0])
np.savetxt(save_dir+'/angle_bl.txt', self.angle['bl'])
np.savetxt(save_dir+'/angle_br.txt', self.angle['br'])
np.savetxt(save_dir+'/angle_tl.txt', self.angle['tl'])
np.savetxt(save_dir+'/angle_tr.txt', self.angle['tr'])
np.savetxt(save_dir+'/xcom.txt', self.xcom)
np.savetxt(save_dir+'/zcom.txt', self.zcom)
np.savetxt(save_dir+'/angle_circle.txt', self.angle_circle_mean)
def plot_radius(self, fig_name='spreading_radius.eps'):
mpl.use("Agg")
print("[densmap] Producing plot for spreading radius")
radius_upper = np.abs( np.array(self.foot['tr']) - np.array(self.foot['tl']) )
radius_lower = np.abs( np.array(self.foot['br']) - np.array(self.foot['bl']) )
plt.figure()
"""
Change once the upper half tracking is added
"""
plt.plot(self.time, radius_upper[:,0], 'k-', label='upper')
plt.plot(self.time, radius_lower[:,0], 'g-', label='lower')
plt.title('Spreading radius', fontsize=20.0)
plt.xlabel('t [ps]', fontsize=20.0)
plt.ylabel('R(t) [nm]', fontsize=20.0)
plt.legend()
plt.show()
plt.savefig(fig_name)
mpl.use("TkAgg")
def plot_angles(self, fig_name='contact_angles.eps'):
mpl.use("Agg")
print("[densmap] Producing plot for contact angles")
plt.figure()
plt.plot(self.time, self.angle['bl'], 'b-', label='bottom left')
plt.plot(self.time, self.angle['br'], 'r-', label='bottom right')
plt.plot(self.time, self.angle['tl'], 'c-', label='top left')
plt.plot(self.time, self.angle['tr'], 'm-', label='top right')
plt.title('Contact angle', fontsize=20.0)
plt.xlabel('t [ps]', fontsize=20.0)
plt.ylabel('theta(t) [deg]', fontsize=20.0)
plt.legend()
plt.show()
plt.savefig(fig_name)
mpl.use("TkAgg")
def movie_contour(self, crop_x, crop_z, dz, circle=True, contact_line=True):
mpl.use("Agg")
print("[densmap] Producing movie of the interface dynamics")
FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title='Spreading Droplet Contour', artist='Michele Pellegrino',
comment='Just the tracked contour of a spreding droplet')
writer = FFMpegWriter(fps=30, metadata=metadata)
fig = plt.figure()
fig_cont, = plt.plot([], [], '-', color='tab:gray', linewidth=1.5)
fig_fbl, = plt.plot([], [], 'b-', linewidth=1.0)
fig_fbr, = plt.plot([], [], 'r-', linewidth=1.0)
fig_ftl, = plt.plot([], [], 'c-', linewidth=1.0)
fig_ftr, = plt.plot([], [], 'm-', linewidth=1.0)
fig_pbl, = plt.plot([], [], 'b.', linewidth=1.5)
fig_pbr, = plt.plot([], [], 'r.', linewidth=1.5)
fig_ptl, = plt.plot([], [], 'c.', linewidth=1.5)
fig_ptr, = plt.plot([], [], 'm.', linewidth=1.5)
fig_pos_up, = plt.plot([], [], 'kx', linewidth=1.5)
fig_pos_lw, = plt.plot([], [], 'gx', linewidth=1.5)
fig_cir_right, = plt.plot([], [], 'k--', linewidth=1.00)
fig_cir_left, = plt.plot([], [], 'k--', linewidth=1.00)
fig_com, = plt.plot([], [], 'ks', linewidth=1.5)
plt.title('Droplet Shear')
plt.xlabel('x [nm]')
plt.ylabel('z [nm]')
s = np.linspace(0,2*np.pi,250)
with writer.saving(fig, "contour_movie.mp4", 250):
for i in range( len(self.contour) ):
dx_bl = dz * self.cotangent['bl'][i]
dx_br = dz * self.cotangent['br'][i]
dx_tl = dz * self.cotangent['tl'][i]
dx_tr = dz * self.cotangent['tr'][i]
if circle :
circle_x_l = self.circle_xc_l[i] + self.circle_rad_l[i]*np.cos(s)
circle_z_l = self.circle_zc_l[i] + self.circle_rad_l[i]*np.sin(s)
circle_x_r = self.circle_xc_r[i] + self.circle_rad_r[i]*np.cos(s)
circle_z_r = self.circle_zc_r[i] + self.circle_rad_r[i]*np.sin(s)
fig_cont.set_data(self.contour[i][0,:], self.contour[i][1,:])
fig_com.set_data(self.xcom[i], self.zcom[i])
t_label = str(self.time[i])+' ps'
"""
The position of the time label should be an input (or at leat a macro)
"""
textvar = plt.text(1.5, 14.0, t_label)
if contact_line :
fig_fbl.set_data([self.foot['bl'][i][0], self.foot['bl'][i][0]+dx_bl],
[self.foot['bl'][i][1], self.foot['bl'][i][1]+dz])
fig_fbr.set_data([self.foot['br'][i][0], self.foot['br'][i][0]+dx_br],
[self.foot['br'][i][1], self.foot['br'][i][1]+dz])
fig_pbl.set_data(self.foot['bl'][i][0], self.foot['bl'][i][1])
fig_pbr.set_data(self.foot['br'][i][0], self.foot['br'][i][1])
# Flipping again to the upper wall
fig_ftl.set_data([self.foot['tl'][i][0], self.foot['tl'][i][0]+dx_tl],
[crop_z-self.foot['tl'][i][1], crop_z-self.foot['tl'][i][1]-dz])
fig_ftr.set_data([self.foot['tr'][i][0], self.foot['tr'][i][0]+dx_tr],
[crop_z-self.foot['tr'][i][1], crop_z-self.foot['tr'][i][1]-dz])
fig_ptl.set_data(self.foot['tl'][i][0], crop_z-self.foot['tl'][i][1])
fig_ptr.set_data(self.foot['tr'][i][0], crop_z-self.foot['tr'][i][1])
fig_pos_up.set_data( 0.5*(self.foot['tl'][i][0]+self.foot['tr'][i][0]), \
0.5*(crop_z-self.foot['tl'][i][1]+crop_z-self.foot['tr'][i][1]) )
fig_pos_lw.set_data( 0.5*(self.foot['bl'][i][0]+self.foot['br'][i][0]), \
0.5*(self.foot['bl'][i][1]+self.foot['br'][i][1]) )
if circle :
fig_cir_left.set_data(circle_x_l, circle_z_l)
fig_cir_right.set_data(circle_x_r, circle_z_r)
plt.axis('scaled')
plt.xlim(0, crop_x)
plt.ylim(0, crop_z)
writer.grab_frame()
textvar.remove()
mpl.use("TkAgg")
def save_xvg(self, folder, mode='contour') :
if mode=='contour' :
for k in range(len(self.contour)) :
output_interface_xmgrace(self.contour[k], folder+"/interface_"+str(k+1).zfill(5)+".xvg")
elif mode=='interface' :
for k in range(len(self.branch['bl'])) :
output_interface_xmgrace(self.branch['bl'][k], folder+"/int_l_"+str(k+1).zfill(5)+".xvg")
for k in range(len(self.branch['br'])) :
output_interface_xmgrace(self.branch['br'][k], folder+"/int_r_"+str(k+1).zfill(5)+".xvg")
def plot_contact_line_pdf(self, N_in=0, fig_name='cl_pdf.eps') :
signal_tr = np.array(self.foot['tr'])[:,0]
N = len(signal_tr)
sign_mean_tr, sign_std_tr, bin_vector_tr, distribution_tr = position_distribution( signal_tr[N_in:], int(np.sqrt(N-N_in)) )
signal_tl = np.array(self.foot['tl'])[:,0]
sign_mean_tl, sign_std_tl, bin_vector_tl, distribution_tl = position_distribution( signal_tl[N_in:], int(np.sqrt(N-N_in)) )
signal_br = np.array(self.foot['br'])[:,0]
sign_mean_br, sign_std_br, bin_vector_br, distribution_br = position_distribution( signal_br[N_in:], int(np.sqrt(N-N_in)) )
signal_bl = np.array(self.foot['bl'])[:,0]
sign_mean_bl, sign_std_bl, bin_vector_bl, distribution_bl = position_distribution( signal_bl[N_in:], int(np.sqrt(N-N_in)) )
mpl.use("Agg")
print("[densmap] Producing plot for contact angles")
plt.figure()
plt.step(bin_vector_bl, distribution_bl, 'b-', label='BL, mean='+"{:.3f}".format(sign_mean_bl)+"nm")
plt.step(bin_vector_br, distribution_br, 'r-', label='BR, mean='+"{:.3f}".format(sign_mean_br)+"nm")
plt.step(bin_vector_tl, distribution_tl, 'c-', label='TL, mean='+"{:.3f}".format(sign_mean_tl)+"nm")
plt.step(bin_vector_tr, distribution_tr, 'm-', label='TR, mean='+"{:.3f}".format(sign_mean_tr)+"nm")
plt.title('CL PDF', fontsize=20.0)
plt.xlabel('position [nm]', fontsize=20.0)
plt.ylabel('PDF', fontsize=20.0)
plt.legend()
plt.show()
plt.savefig(fig_name)
mpl.use("TkAgg")
def dictionify( file_name, sp = '=' ) :
par_dict = dict()
par_file = open( file_name, 'r')
for line in par_file :
line = line.strip().replace(' ','')
cols = line.split(sp)
par_dict[cols[0]] = cols[1]
par_file.close()
return par_dict
class fitting_parameters :
time_step = 0.0 # [ps]
lenght_x = 0.0 # [nm]
lenght_z = 0.0 # [nm]
r_mol = 0.0 # [nm]
max_vapour_density = 0.0 # [MASS] -> give a look at flow program
substrate_location = 0.0 # [nm]
bulk_location = 0.0 # [nm]
simmetry_plane = 0.0 # [nm]
interpolation_order = 1 # [nondim.]
folder_name = '' # [string]
first_stamp = 0 # [int]
last_stamp = 0 # [int]
dz = 0.0 # [nm]
def __init__(fitting_parameters, par_file=None):
print("[densmap] Initializing fitting parameters data structure")
if par_file != None :
par_dict = dictionify(par_file)
fitting_parameters.time_step = \
float(par_dict['time_step'])
fitting_parameters.lenght_x = \
float(par_dict['lenght_x'])
fitting_parameters.lenght_z = \
float(par_dict['lenght_z'])
fitting_parameters.r_mol = \
float(par_dict['r_mol'])
fitting_parameters.max_vapour_density = \
float(par_dict['max_vapour_density'])
fitting_parameters.substrate_location = \
float(par_dict['substrate_location'])
fitting_parameters.bulk_location = \
float(par_dict['bulk_location'])
fitting_parameters.simmetry_plane = \
float(par_dict['simmetry_plane'])
fitting_parameters.interpolation_order = \
int(par_dict['interpolation_order'])
fitting_parameters.folder_name = \
par_dict['folder_name']
fitting_parameters.first_stamp = \
int(par_dict['first_stamp'])
fitting_parameters.last_stamp = \
int(par_dict['last_stamp'])
fitting_parameters.dz = \
float(par_dict['dz'])
"""
Read input file containing density map
"""
def read_density_file (
filename,
bin = 'y',
n_bin_x = 0,
n_bin_z = 0
) :
assert bin=='y' or bin=='n', \
"Specify whether the input file is binary (bin='y') or not (bin='n')"
# Read file format as produced from by the '-flow' oprion of mdrun
if bin=='y' :
# print('[densmap] Reading binary file in -flow format')
data, info = read_data(filename)
Nx = info['shape'][0]
Nz = info['shape'][1]
density_array = np.array( data['M'] )
density_array = density_array.reshape((Nx,Nz))
# Read file format as produced by densmap programme
else :
# print('[densmap] Reading text file in gmx densmap format')
assert n_bin_x > 0 and n_bin_z > 0, \
"Specify a positive number of bins when reading from gmx densmap output"
Nx = n_bin_x
Nz = n_bin_z
idx = 0
density_array = np.zeros( (Nx+1) * (Nz+1), dtype=float )
for line in open(filename, 'r'):
vals = np.array( [ float(i) for i in line.split() ] )
density_array[idx:idx+len(vals)] = vals
idx += len(vals)
density_array = density_array.reshape((Nx+1,Nz+1))
density_array = density_array[1:-1,1:-1]
return density_array
"""
Read velocity field from .dat data
"""
def read_velocity_file (
filename
) :
data, info = read_data(filename)
# print(data)
Nx = info['shape'][0]
Nz = info['shape'][1]
vel_x = np.array( data['U'] )
vel_z = np.array( data['V'] )
vel_x = vel_x.reshape((Nx,Nz))
vel_z = vel_z.reshape((Nx,Nz))
return vel_x, vel_z
"""
Read temperature field from .dat data
"""
def read_temperature_file (
filename
) :
data, info = read_data(filename)
# print(data)
Nx = info['shape'][0]
Nz = info['shape'][1]
temp = np.array( data['T'] )
temp = temp.reshape((Nx,Nz))
return temp
"""
Crops the array containg density values to the desired values
"""
def crop_density_map (
density_array,
new_x_s=0,
new_x_f=-1,
new_z_s=0,
new_z_f=-1
):
density_array_crop = density_array[new_x_s:new_x_f,new_z_s:new_z_f]
nx = density_array_crop.shape[0]
nz = density_array_crop.shape[1]
return density_array_crop, nx, nz
"""
Compute the gradient in (x,z) using central finite different scheme
"""
def gradient_density (
density_array,
hx,
hz
) :
assert hx>0 and hz>0, \
"Provide a finite positive value for the bin size in x and z direction"
nx = density_array.shape[0]
nz = density_array.shape[1]
grad_x = np.zeros((nx, nz), dtype=float)
grad_z = np.zeros((nx, nz), dtype=float)
for i in range(1, nx-1) :
for j in range (1, nz-1) :
grad_x[i,j] = 0.5*( density_array[i+1,j] - density_array[i-1,j] ) / hx
grad_z[i,j] = 0.5*( density_array[i,j+1] - density_array[i,j-1] ) / hz
return grad_x, grad_z
"""
Computes smoothing kernel
"""
def smooth_kernel (
radius,
hx,
hz
) :
assert hx>0 and hz>0, \
"Provide a finite positive value for the bin size in x and z direction"
sigma = 2*radius
Nker_x = int(sigma/hx)
Nker_z = int(sigma/hz)
smoother = np.zeros((2*Nker_x+1, 2*Nker_z+1))
for i in range(-Nker_x,Nker_x+1):
for j in range(-Nker_z,Nker_z+1):
dist2 = sigma**2-(i*hx)**2-(j*hz)**2
if dist2 >= 0:
smoother[i+Nker_x][j+Nker_z] = np.sqrt(dist2)
else :
smoother[i+Nker_x][j+Nker_z] = 0.0
smoother = smoother / np.sum(np.sum(smoother))
return smoother
"""
Convolute (periodically) the density map with the smoothing kernel
"""
def convolute (
density_array,
smoother
) :
smooth_density_array = sc.signal.convolve2d(density_array, smoother,
mode='same', boundary='wrap')
return smooth_density_array
"""
Identify the bulk density value by inspecting the density value distribution
"""
def detect_bulk_density (
density_array,
density_th,
n_hist_bins=100
) :
hist, bin_edges = np.histogram(density_array[density_array >= density_th].flatten(),
bins=n_hist_bins)
bulk_density = bin_edges[np.argmax(hist)]
return bulk_density
"""
Returns an array d[i][j] s.t.
"""
def density_indicator (
density_array,
target_density
) :
idx = np.zeros( density_array.shape, dtype=int )
idx[density_array >= target_density] = 1
return idx
"""
Identify the contour line corresponding to the desired density value
"""
def detect_contour (
density_array,
density_target,
hx,
hz
) :
assert hx>0 and hz>0, \
"Provide a finite positive value for the bin size in x and z direction"
contour = sk.measure.find_contours(density_array, density_target, fully_connected='high')
assert len(contour)>=1, \
"No contour line found for the target density value"
if len(contour)>1 :
# print( "[densmap] More than one contour found for the target density value (returning the one with most points)" )
contour = sorted(contour, key=lambda x : len(x))
# From indices space to physical space
h = np.array([[hx, 0.0],[0.0, hz]])
contour = np.matmul(h,(contour[-1].transpose()))
# Evaluate at the center of the bin
contour = contour + np.array([[0.5*hx],[0.5*hz]])
return contour
"""
Pin-point the contact line position over a corrugated substrate
"""
def detect_contact_rough(
contour,
delta_th,
fun_sub
) :
N = len(contour[0,:])
delta = np.abs( contour[1,:] - fun_sub(contour[0,:]) )
for i in range(N) :
if delta[i] > delta_th :
delta[i] = np.nan
else :
delta[i] = 0
x = contour[0,:] + delta
idx_l = np.nanargmin(x)
idx_r = np.nanargmax(x)
return idx_l, idx_r
"""
Left and right branch
"""
def retrace_local_profile (
contour,
z_th,
idx_l,
idx_r