-
Notifications
You must be signed in to change notification settings - Fork 2
/
naming.py
763 lines (609 loc) · 23 KB
/
naming.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
"""
Module naming provides functions and objects to get and read names of all
directories and files used throughout this project, as well as a glossary of
commonly used variables.
"""
from active_particles.exponents import float_to_letters, letters_to_float,\
significant_figures
from active_particles.init import get_env
from collections import OrderedDict
from itertools import chain
from copy import deepcopy
from os import getcwd
from os import environ as envvar
from os import listdir as ls
from os.path import join as joinpath
# DEFAULT NAMES
sim_directory = joinpath(get_env('HOME'), 'active_particles_data') # simulation data directory
out_directory = joinpath(sim_directory, 'out') # launch output directory
parameters_file = 'param.p' # simulation parameters file
log_file = 'log-output.log' # simulation log output file
wrapped_trajectory_file = 'trajectory.gsd' # wrapped trajectory file (with periodic boundary conditions)
unwrapped_trajectory_file = 'trajectory.dat' # unwrapped trajectory file (without periodic boundary conditions)
# GLOSSARY
class Glossary:
"""
This class references VarInfo objects.
"""
def __init__(self, *entries):
"""
Positional arguments
--------------------
entries : active_particles.naming.VarInfo object
Information about a variable.
"""
self.entries = entries
def __getitem__(self, varname):
"""
Called by self[varname].
Parameters
----------
varname : string
Generic name of variable.
Returns
-------
entry : active_particles.naming.VarInfo
Informations about variable 'varname' in glossary.
"""
return next((entry for entry in self.entries
if entry.name == varname), None)
def __add__(self, entry):
"""
Called by self + ...
Parameters
----------
entry : active_particles.naming.VarInfo object
New entry to add to glossary.
Returns
-------
gloassry : active_particles.naming.Glossary object
Augmented glossary.
"""
self.entries += (entry,)
return self
class VarInfo:
"""
This class save informations about a given variable.
"""
def __init__(self, name, definition, symbol, format):
"""
Parameters
----------
name : string
Generic name.
definition : string
Brief description of the variable.
symbol : string
LaTeX symbol to use in legends.
format : formatting string
Format to use in legends.
"""
self.name = name
self.definition = definition
self.symbol = symbol
self.format = format
def __str__(self):
"""
Prints description of variable.
"""
return self.definition
def legend(self, value):
"""
Parameters
----------
value : *
Value of variable.
Returns
-------
legend : string
Formatted string '{variable} = {value}'.
"""
return self.symbol + '=' + self.format.format(value)
glossary = Glossary(*map(lambda entry: VarInfo(*entry), (
# | NAME | DEFINITION | SYMBOL | FORMAT |
('density', 'surface packing fraction', r'$\phi', '{:1.2f}'),
('vzero', 'self-propelling velocity', r'$\tilde{v}$', '{:.2e}'),
('dr', 'rotational diffusion constant', r'$\tilde{\nu}_r$', '{:.2e}'),
('N', 'number of particles', r'$N$', '{:.2e}'),
('init_frame', 'initial frame', r'$S_{init}$', '{:.2e}'),
('frame', 'time frame', r'$T$', '{:.2e}'),
('dt', 'lag time', r'$\Delta t$', '{:.2e}'),
('int_max', 'maximum number of intervals', r'$S_{max}$', '{:.2e}'),
('int_period', 'period of intervals', r'$S_{period}$', '{:.2e}'),
('Ncases', 'number of boxes in one direction of a grid',
r'$N_{cases}$', '{:.2e}'),
('r_cut', 'cut-off radius', r'$r_{cut}$', '{:.2e}'),
('sigma', 'length scale of Gaussian function', r'$\sigma$', '{:.2e}'),
('box_size', 'length of the box in one dimension', r'$L$', '{:.3e}'),
('launch', 'index of simulation launch', 'launch', '{:d}')
)))
# FILES NAMING
_image_extension = '.eps' # default image extension
_movie_extension = '.mp4' # default movie extension
class _File:
"""
Naming files and directories.
This is the superclass which provides methods to get and read names for
all subclasses defined specifically per files which we will call
'standards'.
All subclasses must be initiated with
> self.name : string
Generic name.
> self.parameters : ordered dictionary
Hash table of parameters and their abbreviations.
> self.extension : string
File extension.
"""
def filename(self, **definitions):
"""
Returns a list of name parts which the keyword arguments enables to
define.
Optional keyword arguments
--------------------------
definitions : float, int or bool
Defined parameters (e.g., density=0.1).
Returns
-------
name_parts : list of strings
List of defined name parts.
"""
name_parts = [] # list of defined name parts
buffer = self.name # consecutive defined attributes
for param in self.parameters: # looping through file name parameters
buffer += self.parameters[param] # parameter abbreviation
try:
if definitions[param] == None: raise KeyError
buffer += str(float_to_letters(definitions[param])) # defined value of parameter
except KeyError: # if parameter is not defined
name_parts += [buffer] # add buffer to defined name parts
buffer = ''
buffer += self.extension # adding extension to name parts
name_parts += [buffer]
return name_parts
def filename_length(self):
"""
Returns the length of the filename according to its name, parameters
and extensions.
Returns
-------
length : int
Length of filename.
"""
length = len(self.name)
for parameter in self.parameters.values():
length += len(parameter) + 1 + significant_figures
length += len(self.extension)
return length
def get_files(self, directory=getcwd(), **definitions):
"""
Returns list of files which correpond to the keyword arguments.
Parameters
----------
directory : string
Files directory. (default: current working directory)
Optional keyword arguments
--------------------------
definitions : float, int or bool
Defined parameters (e.g., density=0.1).
Returns
-------
files : list of strings
List of files correponding to parameters.
"""
length = self.filename_length() # length of filename
name_parts = self.filename(**definitions) # list of defined name parts
return [file for file in ls(directory) if
all(part in file for part in name_parts)
and len(file) == length]
def get_data(self, file, *parameter):
"""
Returns values of parameters which can be read from the file name.
Parameters
----------
file : string
File name.
Optional positional arguments
-----------------------------
parameter : string
Name of parameter in self.parameters.
Returns
-------
par_values : list of floats
List of requested parameters values.
"""
par_values = [] # list of requested parameters values.
for param in parameter: # for all requested parameters
if param in self.parameters: # requested parameter exists
par_values += [letters_to_float(
file.split(self.parameters[param])[1][
:significant_figures + 1]
)] # parameter value translated to float
return par_values
def add_ext(self, ext_parameters=None, ext_extension=None):
"""
From a default standard, this function returns an extended standard
with additional parameters and different extension.
Parameters
----------
ext_parameters : ordered dictionary
Hash table of additional parameters and their abbreviations.
(default: None)
NOTE: if ext_parameters == None, parameters remain unchanged.
ext_extension : string
Different file extension. (default: None)
NOTE: if ext_extension == None, the extension remains unchanged.
Returns
-------
ext_self : active_particles.naming standard
Extended standard object.
"""
ext_self = deepcopy(self) # creates a deep copy of the standard
if ext_parameters != None: ext_self.parameters = OrderedDict(chain(
self.parameters.items(), ext_parameters.items())) # extended ordered dictionary of parameters
if ext_extension != None: ext_self.extension = ext_extension # extended standard extension
return ext_self
def image(self):
"""
This function is the default image name generator, which only changes
file extension with _image_extension.
"""
return self.add_ext(OrderedDict(), _image_extension)
def out(self):
"""
This function is the default output file name generator, which only
changes file extension with '.out'.
"""
return self.add_ext(OrderedDict(), '.out')
class _CorFile(_File):
"""
Naming correlation files.
"""
def __init__(self, name, **kwargs):
"""
Architecture of file name.
Parameters
----------
name : string
Generic name of correlation file.
Optional keyword arguments
--------------------------
ext_parameters : ordered dictionary
Hash table of additional parameters and their abbreviations.
"""
self.name = name + endpoint() # generic name
self.parameters = OrderedDict([
('density', '_D'), ('vzero', '_V'), ('dr', '_R'), ('N', '_N'),
('init_frame', '_I'), ('dt', '_T'), ('int_max', '_M'),
('Ncases', '_C')
]) # parameters and corresponding abbreviations (in order)
self.extension = '.pickle' # file extension
if 'ext_parameters' in kwargs:
self.parameters = self.add_ext(kwargs['ext_parameters'],
self.extension).parameters # add additional parameters
if 'BOX_SIZE' in envvar: # modified box size
self.parameters = OrderedDict(chain(self.parameters.items(),
{'box_size': '_B'}.items()))
if 'X_ZERO' in envvar or 'Y_ZERO' in envvar: # modified centre of the box
self.parameters = OrderedDict(chain(self.parameters.items(),
OrderedDict([('x_zero', '_X'), ('y_zero', '_Y')]).items()))
class _ShearStrainVorticity(_CorFile):
"""
Naming shear strain and displacement vorticity files.
"""
def __init__(self, name, mode='fourier'):
"""
Architecture of file name.
Parameters
----------
name : string
Generic name.
mode : bool
Computation mode (default: fourier).
"""
self.mode = mode
if self.mode == 'real': # calculation in real space
ext_parameters = OrderedDict([('r_cut', '_RCUT'),
('sigma', '_SIGM')])
else:
ext_parameters = OrderedDict()
if self.mode == 'fourier': # calculation in Fourier space
name += 'ft'
elif self.mode == 'ovito': # calculation with OVITO
name += 'OVITO'
super().__init__(name, ext_parameters=ext_parameters) # initialise with superclass
def image(self):
"""
Image name generator, with additional Gaussian cut-off radius parameter
for calculation in Fourier space.
"""
if not(self.from_ft): return super().image()
else: return super().image().add_ext(OrderedDict([('r_cut', '_RCUT')]))
class Css(_ShearStrainVorticity):
"""
Naming shear strain files.
"""
def __init__(self, mode='fourier'):
"""
Architecture of file name.
Parameters
----------
mode : bool
Computation mode (default: fourier).
"""
super().__init__('Css', mode=mode) # initialise with superclass
class Ccc(_ShearStrainVorticity):
"""
Naming displacement vorticity files.
"""
def __init__(self, mode='fourier'):
"""
Architecture of file name.
Parameters
----------
mode : bool
Computation mode (default: fourier).
"""
super().__init__('Ccc', mode=mode) # initialise with superclass
class Cuu(_CorFile):
"""
Naming displacement correlation files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('Cuu') # initialise with superclass
class Cnn(_CorFile):
"""
Naming density correlation files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('Cnn') # initialise with superclass
class Cww(_CorFile):
"""
Naming displacement relative to centre of mass displacement correlation
files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('Cww') # initialise with superclass
class Cdd(_CorFile):
"""
Naming displacement norm correlation files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('Cdd') # initialise with superclass
class Cee(_CorFile):
"""
Naming displacement direction correlation files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('Cee') # initialise with superclass
class Ctt(_CorFile):
"""
Naming mean square norm of cross product of wave vector and displacement
Fourier transform.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('Ctt') # initialise with superclass
def image(self):
"""
Image name generator, with additional Gaussian cut-off radius
parameter.
"""
return super().image().add_ext(OrderedDict([('r_cut', '_RCUT')]))
class Cll(_CorFile):
"""
Naming mean square norm of dot product of wave vector and displacement
Fourier transform.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('Cll') # initialise with superclass
class _FrameFile(_File):
"""
Naming system image files.
"""
def __init__(self, name, **kwargs):
"""
Architecture of file name.
Parameters
----------
name : string
Generic name of image file.
Optional keyword arguments
--------------------------
ext_parameters : ordered dictionary
Hash table of additional parameters and their abbreviations.
"""
self.name = name # generic name
self.parameters = OrderedDict([
('density', '_D'), ('vzero', '_V'), ('dr', '_R'), ('N', '_N'),
('init_frame', '_I')
]) # parameters and corresponding abbreviations (in order)
self.extension = '.eps' # file extension
if 'ext_parameters' in kwargs:
self.parameters = self.add_ext(kwargs['ext_parameters'],
self.extension).parameters # add additional parameters
if 'BOX_SIZE' in envvar: # modified box size
self.parameters = OrderedDict(chain(self.parameters.items(),
{'box_size': '_B'}.items()))
if 'X_ZERO' in envvar or 'Y_ZERO' in envvar: # modified centre of the box
self.parameters = OrderedDict(chain(self.parameters.items(),
OrderedDict([('x_zero', '_X'), ('y_zero', '_Y')]).items()))
def movie(self, folder=False):
"""
Movie name generator.
Parameters
----------
folder : bool
Generate folder name.
"""
if folder:
ext_extension = ''
else: ext_extension = _movie_extension
ext_parameters = OrderedDict()
if 'FINAL_FRAME' in envvar:
ext_parameters = OrderedDict(chain(ext_parameters.items(),
OrderedDict([('frame_fin', '_F')]).items()))
if 'FRAME_PERIOD' in envvar:
ext_parameters = OrderedDict(chain(ext_parameters.items(),
OrderedDict([('frame_per', '_P')]).items()))
if 'FRAME_MAXIMUM' in envvar:
ext_parameters = OrderedDict(chain(ext_parameters.items(),
OrderedDict([('frame_max', '_M')]).items()))
return self.add_ext(ext_parameters, ext_extension)
class D2min(_FrameFile):
"""
Naming system images with D2min values.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('d', ext_parameters=OrderedDict([('dt', '_T')])) # initialise with superclass
class Velocity(_FrameFile):
"""
Naming system images with arrows along velocity directions files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('v') # initialise with superclass
class Trajectory(_FrameFile):
"""
Naming system images with displacements shown as arrows files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('t', ext_parameters=OrderedDict([('dt', '_T')])) # initialise with superclass
class Displacement(_FrameFile):
"""
Naming system images with arrows along displacement directions files.
"""
def __init__(self):
"""
Architecture of file name.
"""
super().__init__('u', ext_parameters=OrderedDict([('dt', '_T')])) # initialise with superclass
class Msd(_File):
"""
Naming mean square displacement files.
"""
def __init__(self, distribution=False):
"""
Architecture of file name.
Parameters
----------
distribution : bool
Distribution of square displacements file rather than mean square
displacement file. (default: False)
"""
self.name = 'msd_dist' if distribution else 'msd_sterr' # generic name
self.parameters = OrderedDict([
('density', '_D'), ('vzero', '_V'), ('dr', '_R'), ('N', '_N'),
('init_frame', '_I'), ('int_max', '_M'), ('int_period', '_P')
]) # parameters and corresponding abbreviations (in order)
self.extension = '.pickle' if distribution else '.csv' # file extension
class VarN(_File):
"""
Naming local densities densities.
"""
def __init__(self, final_frame=False):
"""
Architecture of file name.
Parameters
----------
final_frame : bool
Compute with a maximum frame. (default: False)
"""
self.name = 'varN' # generic name
self.parameters = OrderedDict([
('density', '_D'), ('vzero', '_V'), ('dr', '_R'), ('N', '_N'),
('init_frame', '_I'), ('int_max', '_M'), ('Ncases', '_C'),
('box_size', '_B')
]) # parameters and corresponding abbreviations (in order)
if final_frame: self.parameters = OrderedDict(chain(
self.parameters.items(),
OrderedDict([('fin_frame', '_F')]).items()))
self.extension = '.pickle' # file extension
class AHB2D(_File):
"""
Naming simulations of 2D active brownian uniformly polydisperse particles
directories.
"""
def __init__(self):
"""
Architecture of file name.
"""
self.name = '' # generic name
self.parameters = OrderedDict([
('density', 'D'), ('vzero', '_V'), ('dr', '_R'), ('N', '_N'),
('launch', '_L')
]) # parameters and corresponding abbreviations (in order)
self.extension = '' # file extension
def filename(self, directory=getcwd(), define_launch=False, **definitions):
"""
Returns a list of name parts which the keyword arguments enables to
define.
Parameters
----------
directory : string
Directory in which the folder will be created.
define_launch : bool
Set launch number as function of the number of directories with
identical parameters already existing, if launch number not
defined. (default: False)
NOTE: if True, definitions have to ENTIRELY define directory name.
Optional keyword arguments
--------------------------
definitions : float, int or bool
Defined parameters (e.g., density=0.1).
Returns
-------
name_parts : list of strings
List of defined name parts.
"""
if define_launch and not('launch' in definitions): # launch number to be defined
definitions['launch'] = len(super().get_files(**definitions,
launch=None))
return super().filename(**definitions)
def endpoint():
"""
Consider a variable A which depends on space, time and a lag time (e.g.,
displacement). It is possible to measure
(i) A between times t and t + dt for a particle which is at position r at
time t: A(r, t ; t, t + dt)
(ii) A between times t and t + dt for a particle which is at position r at
time t + dt: A(r, t + dt ; t, t + dt)
and calculate correlations over space and time in both cases.
We will add a 'b' following the name of the correlation for files which
have produced considering case (i).
e.g., for displacement correlations, filenames will begin with 'Cuub'
if correlations were calculated for displacements between times t and
t + dt between particles at position r at time t.
Case (i) corresponds to environment variable 'ENDPOINT' set as False or not
set, while case (ii) corresponds to environment variable 'ENDPOINT' set as
True.
"""
if get_env('ENDPOINT', default=False, vartype=bool): return ''
return 'b'