-
Notifications
You must be signed in to change notification settings - Fork 0
/
structure.py
606 lines (504 loc) · 20.4 KB
/
structure.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
"""
Module flow provides classes to compute and analyse positions to characterise
the structure of systems of ABPs.
(see https://yketa.github.io/DAMTP_MSC_2019_Wiki/#ABP%20structure%20characteristics)
"""
from coll_dyn_activem.read import Dat
from coll_dyn_activem.maths import pycpp, g2Dto1D, wave_vectors_2D, DictList,\
angle, linspace, Histogram, mean_sterr, relative_positions, normalise1D,\
wave_vectors_dq
import numpy as np
from operator import itemgetter
from multiprocessing import Pool
from freud.locality import Voronoi
from freud.box import Box
class Positions(Dat):
"""
Compute and analyse positions from simulation data.
(see https://yketa.github.io/DAMTP_MSC_2019_Wiki/#Active%20Brownian%20particles)
"""
def __init__(self, filename, skip=1, corruption=None):
"""
Loads file.
Parameters
----------
filename : string
Name of input data file.
skip : int
Skip the `skip' first computed frames in the following calculations.
(default: 1)
NOTE: This can be changed at any time by setting self.skip.
NOTE: This does not apply to .datN files.
corruption : str or None
Pass corruption test for given file type (see
coll_dyn_activem.read.Dat). (default: None)
NOTE: if corruption == None, then the file has to pass corruption
tests.
"""
super().__init__(filename, loadWork=False, corruption=corruption) # initialise with super class
self.skip = skip # skip the `skip' first frames in the analysis
def getParticleDensity(self, time, nBoxes=None):
"""
Returns particle density at `time' as grid where each box is equal to
the number of particles in the corresponding region of space divided by
the surface of this region.
Parameters
----------
time : int
Frame index.
nBoxes : int
Number of grid boxes in each direction. (default: None)
NOTE: if nBoxes == None, then nBoxes = int(sqrt(self.N)).
Returns
-------
rho : (nBoxes, nBoxes) float Numpy array
Particle density grid.
"""
time = int(time)
if nBoxes == None: nBoxes = np.sqrt(self.N)
nBoxes = int(nBoxes)
# dV = (self.L/nBoxes)**2
return self.toGrid(time,
np.full((self.N,), fill_value=1),
nBoxes=nBoxes, box_size=self.L, centre=(0, 0), average=False)#/dV
def getLocalDensity(self, time, nBoxes=None):
"""
Returns local packing fraction defined as the ratio of particles'
volume to the volume of the corresponding box, where the system has been
divided in `nBoxes'x`nBoxes' linearly spaced square boxes of identical
size.
NOTE: particle volumes are computed with a factor 2^(1/6) on diameters.
Parameters
----------
time : int
Frame index.
nBoxes : int
Number of grid boxes in each direction. (default: None)
NOTE: if nBoxes == None, then nBoxes = int(sqrt(self.N)).
Returns
-------
localPhi : (nBoxes**2,) float numpy array
Array of local packing fraction.
"""
time = int(time)
if nBoxes == None: nBoxes = np.sqrt(self.N)
nBoxes = int(nBoxes)
dV = (self.L/nBoxes)**2
surfaces = self.toGrid(time,
(np.pi/4.)*(((2**(1./6.))*self.diameters)**2),
nBoxes=nBoxes, box_size=self.L, centre=(0, 0), average=False)
return surfaces.flatten()/dV
def getLocalParticleDensity(self, time, a):
"""
Returns local packing fraction for each particle defined as the ratio of
particles' volume to the volume of the square box of size `a' around
each particle.
NOTE: particle volumes are computed with a factor 2^(1/6) on diameters.
Parameters
----------
time : int
Frame index.
a : float
Size of the box in which to compute densities.
Returns
-------
localPhi : (self.N,) float numpy array
Array of local packing fraction.
"""
# positions = self.getPositions(time)
#
# surfaces = np.zeros((self.N,))
# for particle in range(self.N):
# surfaces[particle] = ((np.pi/4.)*(((2**(1./6.))*self.diameters[
# (np.abs(
# relative_positions(positions, positions[particle], self.L))
# < a/2).all(axis=-1)])**2)).sum()
#
# return surfaces/(a**2)
return pycpp.getLocalParticleDensity(
a, self.getPositions(time), self.L, self.diameters)
def getLocalDensityVoronoi(self, time, phi=True):
"""
Returns local packing fraction defined as the ratio of particles'
volume to the volume of the corresponding voronoi cells.
NOTE: particle volumes are computed with a factor 2^(1/6) on diameters.
(see self._voronoi)
Parameters
----------
time : int
Frame index.
phi : bool
Returns local packing fraction instead of inverse local volume.
(default: True)
Returns
-------
localPhi : (self.N,) float numpy array
Array of local packing fraction.
"""
volumes = self._voronoi(time).volumes
if phi: return ((np.pi/4.)*(((2**(1./6.))*self.diameters)**2))/volumes
else: return 1./volumes
def getNeighbourList(self, time):
"""
Get list of neighbours and bond length for particles in the system at
`time' from Voronoi tesselation.
(see self._voronoi)
Parameters
----------
time : int
Frame index.
Returns
-------
neighbours : coll_dyn_activem.maths.DictList
Neighbour list :
(key) particle index,
(0) neighbour index,
(1) neighbour distance.
"""
neighbours = DictList()
voro = self._voronoi(time)
for ((i, j), d) in zip(voro.nlist[:], voro.nlist.distances):
neighbours[i] += [[j, d]]
return neighbours
def getBondOrderParameter(self, time, *particle, arg=False):
"""
Get hexatic bond orientational order parameter at `time'.
Parameters
----------
time : int
Frame index.
particle : int
Indexes of particles.
NOTE: if none is given, then all particles are returned.
arg : bool
Compute argument of the bond order parameter rather than bond order
parameter itself. (default: False)
Returns
-------
psi : (self.N,) complex numpy array
Bond orientational order parameter.
"""
neighbours = self.getNeighbourList(time)
positions = self.getPositions(time)
psi = np.zeros((self.N,), dtype=complex)
for i in range(self.N):
for j, _ in neighbours[i]:
psi[i] += np.exp(1j*6*angle(
self._diffPeriodic(positions[i][0], positions[j][0]),
self._diffPeriodic(positions[i][1], positions[j][1])))
psi[i] /= len(neighbours[i])
if arg: psi = np.angle(psi)
if particle == (): return psi
return np.array(itemgetter(*particle)(psi))
def nPositions(self, int_max=None):
"""
Returns array of positions.
Parameters
----------
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
Returns
-------
positions : (*, self.N) float numpy array
Array of computed positions.
"""
return np.array(list(map(
lambda time0: self.getPositions(time0),
self._time0(int_max=int_max))))
def nParticleDensity(self, int_max=None, nBoxes=None):
"""
Returns array of particle density as grids.
Parameters
----------
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
nBoxes : int
Number of grid boxes in each direction. (default: None)
NOTE: if nBoxes==None, then None is passed to
self.getParticleDensity.
Returns
-------
rho : (*, nBoxes, nBoxes) float numpy array
Array of particle density grids.
"""
return np.array(list(map(
lambda time0: self.getParticleDensity(time0, nBoxes=nBoxes),
self._time0(int_max=int_max))))
def nDistances(self, int_max=None, scale_diameter=False):
"""
Returns distances between the particles of the system.
Parameters
----------
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
scale_diameter : bool
Divide the distance between pairs of particles by the sum of the
radii of the particles in the pair. (default: False)
Returns
-------
distances : (*, self.N(self.N - 1)/2) float Numpy array
Array of computed distances.
"""
return np.array(
[pycpp.getDistances(self.getPositions(t), self.L,
diameters=(self.diameters if scale_diameter else None))
for t in self._time0(int_max=int_max)])
def structureFactor(self, nBins, kmin=None, kmax=None,
int_max=None, nBoxes=None):
"""
Returns static structure factor averaged along directions of space
(assuming isotropy) as a histogram.
Parameters
----------
nBins : int
Number of histogram bins.
kmin : float or None
Minimum (included) wavevector norm in the histogram. (default: None)
NOTE: if kmin == None then None is passed to pycpp.g2Dto1Dgridhist.
kmax : float or None
Maximum (excluded) wavevector norm in the histogram. (default: None)
NOTE: if kmax == None then None is passed to pycpp.g2Dto1Dgridhist.
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
nBoxes : int
Number of grid boxes in each direction. (default: None)
NOTE: if nBoxes==None, then nBoxes = int(sqrt(self.N)).
Returns
-------
S : (*, 3) float Numpy array
Array of (k, S(k), Sstd(k)) with S(k) the cylindrically averaged
structure factor at minimum wavevector k of corresponding bin, and
Sstd(k) the standard deviation on this measure.
"""
particleDensity = self.nParticleDensity(int_max=int_max, nBoxes=nBoxes)
nBoxes = particleDensity.shape[1]
# _S2D = np.array(list(map(
# lambda _rho:
# (lambda FFT: np.real(np.conj(FFT)*FFT))
# (np.fft.fft2(_rho)),
# particleDensity)))/self.N
S2D = np.zeros((nBoxes, nBoxes))
for rho in particleDensity:
S2D += (lambda FFT: np.real(np.conj(FFT)*FFT))(np.fft.fft2(rho))/(
self.N*len(particleDensity))
k2D = np.sqrt(
(wave_vectors_2D(nBoxes, nBoxes, self.L/nBoxes)**2).sum(axis=-1))
# S = pycpp.g2Dto1Dgridhist(_S2D.mean(axis=0), k2D, nBins,
S = pycpp.g2Dto1Dgridhist(S2D, k2D, nBins,
vmin=kmin, vmax=kmax)
S[:, 2] /= np.sqrt(len(particleDensity)) # change standard deviation to standard error
return S
# def structureFactor(self, *q, dq=0.1, int_max=None):
# """
# Returns static structure factor averaged along directions of space
# (assuming isotropy).
#
# Parameters
# ----------
# q : float
# Wave vector norms at which to compute structure factor.
# dq : float
# Width of wave vector norm interval. (default: 0.1)
# int_max : int or None
# Maximum number of frames to consider. (default: None)
# NOTE: If int_max == None, then take the maximum number of frames.
# WARNING: This can be very big.
#
# Returns
# -------
# S : (*, 3) float Numpy array
# Array of (k, S(k), stdErr S(k)) with S(k) the cylindrically averaged
# structure factor.
# """
#
# wv_len = np.array(list(map(
# lambda qn: len(wave_vectors_dq(self.L, qn, dq)),
# q)))
# q = np.array(q)[wv_len > 0]
#
# FTsq = [] # list of squared density fourier transform
# for time in self._time0(int_max=int_max):
#
# pos = self.getPositions(time)
#
# FTsq += [
# list(map(
# lambda qn: np.mean(
# list(map(
# lambda qv: (np.abs(np.sum(
# np.exp(-1j*(qv*pos).sum(axis=-1))))**2),
# wave_vectors_dq(self.L, qn, dq))),
# axis=0),
# q))]
#
# return np.array([[qn, *mean_sterr(dFTsq/self.N)]
# for qn, dFTsq in zip(q, np.transpose(FTsq))])
def sk(self, *k, dk=0.1, int_max=None):
"""
Returns static structure factor averaged along directions of space
(assuming isotropy) as a histogram.
Parameters
----------
k : float
Wave vector at which to evaluate the structure factor.
dk : float
Width of wave vector norm interval. (default: 0.1)
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
Returns
-------
S : (*, 3) float Numpy array
Array of (k, S(k), Sstd(k)) with S(k) the cylindrically averaged
structure factor at minimum wavevector k of corresponding bin, and
Sstd(k) the standard deviation on this measure.
"""
K = np.array(k)
positions = np.array(list(map(
lambda t0: self.getPositions(t0),
self._time0(int_max=int_max))))
S = []
for pos in positions:
S += [list(map(
lambda kn: np.mean(
list(map(
lambda kv: np.abs(np.sum(
np.exp(-1j*(kv*pos).sum(axis=-1, keepdims=True))
))**2,
wave_vectors_dq(self.L, kn, dk))),
axis=0)/self.N,
K))]
S = np.array([[k, *mean_sterr(s)] for k, s in zip(K, np.transpose(S))])
return S
def densityCorrelation(self, int_max=None, nBoxes=None):
"""
Returns particle spacial density averaged along directions of space
(assuming isotropy).
NOTE: Correlations are computed with FFT.
Parameters
----------
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
nBoxes : int
Number of grid boxes in each direction. (default: None)
NOTE: if nBoxes==None, then None is passed to
self.getParticleDensity.
Returns
-------
G : float Numpy array
Array of (r, G(r)) with G(r) the averaged density correlation at
radius r.
"""
particleDensity = self.nParticleDensity(int_max=int_max, nBoxes=nBoxes)
nBoxes = particleDensity.shape[1]
_G2D = np.array(list(map(
lambda _rho:
(lambda G2D: G2D*(self.rho/(G2D[0, 0]*((self.L/nBoxes)**2))))(
(lambda FFT: np.real(np.fft.ifft2(np.conj(FFT)*FFT)))
(np.fft.fft2(_rho - self.N/(nBoxes**2)))),
particleDensity)))
return g2Dto1D(_G2D.mean(axis=0), self.L)
def pairDistribution(self, Nbins, min=None, max=None, int_max=None,
scale_diameter=False):
"""
Returns pair distribution function as an histogram of distances between
pairs of particles.
Parameters
----------
Nbins : int
Number of histogram bins.
min : float or None
Minimum included value for histogram bins. (default: None)
NOTE: if min == None then 0 is taken.
NOTE: values lesser than to min will be ignored.
max : float or None
Maximum excluded value for histogram bins. (default: None)
NOTE: if max == None then self.L/2 is taken.
NOTE: values greater than or equal to max will be ignored.
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
scale_diameter : bool
Divide the distance between pairs of particles by the sum of the
radii of the particles in the pair. (default: False)
Returns
-------
gp : float Numpy array
Array of (r, gp(r), errgp(r)) with gp(r) the proportion of pairs at
distance r and errgp(r) the standard error on this measure.
"""
if min == None: min = 0
if max == None: max = self.L/2
hist = np.array(list(map(
# lambda t: (lambda dist: pycpp.getHistogramLinear(dist,
# Nbins, min, max)/dist.size)(
# pycpp.getDistances(self.getPositions(t), self.L,
# diameters=(
# self.diameters if scale_diameter else None))),
lambda t: pycpp.pairDistribution(
Nbins, min, max, self.getPositions(t), self.L,
diameters=(
self.diameters if scale_diameter else None)),
self._time0(int_max=int_max))))
bins = np.array([min + (b + 0.5)*(max - min)/Nbins
for b in range(Nbins)])
histErr = np.array([mean_sterr(h) for h in np.transpose(hist)])
histErr *= (self.L**2)/((max - min)/Nbins)
return np.array([[b, *h/(2*np.pi*b)] for b, h in zip(bins, histErr)])
def _time0(self, int_max=None):
"""
Returns array of frames at which to compute positions.
Parameters
----------
int_max : int or None
Maximum number of frames to consider. (default: None)
NOTE: If int_max == None, then take the maximum number of frames.
WARNING: This can be very big.
Returns
-------
time0 : (*,) int numpy array
Array of frames.
"""
if self._type == 'datN':
time0 = self.time0
else:
time0 = np.array(range(self.skip, self.frames))
if int_max == None: return time0
indexes = linspace(0, time0.size, int_max, endpoint=False)
return np.array(itemgetter(*indexes)(time0), ndmin=1)
def _voronoi(self, time, centre=None):
"""
Compute Voronoi tesselation of the system at `time'.
Parameters
----------
time : int
Frame index.
centre : (2,) float array-like or None
Centre of the box to consider. (default: None)
NOTE: if centre == None, then centre = (self.L/2, self.L/2).
Returns
-------
voro : freud.locality.Voronoi
Voronoi tesselation.
"""
if type(centre) is type(None): centre = (self.L/2., self.L/2.)
voro = Voronoi()
voro.compute((
Box.square(self.L),
np.concatenate(
(self.getPositions(time, centre=centre),
np.zeros((self.N, 1))),
axis=-1)))
return voro