/
libcli.py
753 lines (618 loc) · 21.4 KB
/
libcli.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
"""
Shared operations for client interfaces.
This module contains functions and classes that are shared amongst the
client interfaces. It contains also others used to enhance the user
experience.
"""
import argparse
import os
import sys
from datetime import datetime
from functools import wraps
import numpy as np
from taurenmd import _BANNER, __version__
from taurenmd import core as tcore
from taurenmd import log, references
from taurenmd.logger import CMDFILE
def load_args(ap):
"""Load user arguments."""
cmd = ap.parse_args()
return cmd
def maincli(ap, main):
"""
Client main function.
Operates when client is called directly outside the
``taurenmd`` client interface.
- Reads input parameters
- saves inpu command to log file
- runs client ``main`` function
- saves references to log file
Returns
-------
The result value from client ``main`` function.
"""
cmd = load_args(ap)
save_command(CMDFILE, *sys.argv)
result = main(**vars(cmd))
save_references()
return result
def add_reference(ref):
"""
Add reference decorator.
Example
-------
>>> @add_reference(str)
>>> def myfunct():
>>> ...
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
references.add(ref)
result = func(*args, **kwargs)
return result
return wrapper
return decorator
def save_references():
"""Save used references to log file."""
with open(CMDFILE, 'a') as fh:
fh.write('References:\n')
fh.write(tcore.ref_taurenmd)
fh.write('\n'.join(sorted(list(references))))
fh.write('\n\n')
# https://stackoverflow.com/questions/4042452
class CustomParser(argparse.ArgumentParser):
"""Custom Parser class."""
def error(self, message):
"""Present error message."""
self.print_help()
self.print_usage()
sys.stderr.write('*** INPUT ERROR: {}\n'.format(message))
sys.stderr.write('*** read the usage details above\n')
sys.exit(2)
class ParamsToDict(argparse.Action):
"""
Convert command-line parameters in an argument to a dictionary.
Example
-------
Where ``-x`` is an optional argument of the command-line client
interface.
>>> par1=1 par2='my name' par3=[1,2,3]
>>> {'par1': 1, 'par2': 'my name', 'par3': [1, 2, 3]}
"""
def __call__(self, parser, namespace, values, option_string=None):
"""Execute."""
bool_value = {
'true': True,
'false': False,
}
param_dict = {}
for kv in values:
# print(param_dict, kv)
try:
k, v = kv.split('=')
except ValueError:
param_dict[kv] = True
else:
if ',' in v:
vs = v.split(',')
try:
param_dict[k] = tuple(float(i) for i in vs)
except (ValueError, TypeError):
param_dict[k] = tuple(i for i in vs)
else:
try:
param_dict[k] = float(v)
except (ValueError, TypeError): # is string or list
param_dict[k] = bool_value.get(v.lower(), v)
namespace.plotvars = param_dict
setattr(namespace, self.dest, True)
def save_command(fname, *args):
"""
Append the execution command to a log file.
Parameters
----------
fname : string or Path
The file name of the log file where to append the command.
*args : strings
String parts that compose the command.
"""
with open(fname, 'a') as fh:
fh.write(
'[{}][taurenmd {}] {}\n'.format(
datetime.now().strftime("%d/%B/%Y, %H:%M:%S"),
__version__,
' '.join(represent_argument(a) for a in args),
)
)
def represent_argument(arg):
"""
Represent argument in a string.
If argument has spaces represents string with quotation marks ".
"""
sarg = str(arg)
if sarg.count(' ') > 0:
return '{!r}'.format(sarg)
else:
return sarg
def add_subparser(parser, module):
"""
Add a subcommand to a parser.
Parameters
----------
parser : `argparse.add_suparsers object <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers>`_
The parser to add the subcommand to.
module
A python module containing the characteristics of a taurenmd
client interface. Client interface modules require the following
attributes: ``__doc__`` which feeds the `description argument <https://docs.python.org/3/library/argparse.html#description>`_
of `add_parser <https://docs.python.org/3/library/argparse.html#other-utilities>`_,
``_help`` which feeds `help <https://docs.python.org/3/library/argparse.html#help>`_,
``ap`` which is an `ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_,
and a ``main`` function, which executes the main logic of the interface.
""" # noqa: E501
new_ap = parser.add_parser(
module._name,
description=module.ap.description,
help=module._help,
parents=[module.ap],
add_help=False,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
new_ap.set_defaults(func=module.main)
# arguments list
# a: angle unit
# d: trajectory output
# e: slice stop
# g: atom selections
# i: sort input by trail int
# l: selection
# o: topology output
# p: slice step
# r: reference frame
# s: slice start
# t: framelist
# plot: plot
# x: export data to table
# z: plane selection
def add_version_arg(parser):
"""
Add version ``-v`` option to parser.
Displays a message informing the current version.
Also accessible via ``--version``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to add the version argument.
""" # noqa: E501
parser.add_argument(
'-v',
'--version',
action='version',
# the _BANNER contains information on the version number
version=(
f'{_BANNER}\n'
f'A record of the previous versions can be found at:\n'
f'https://taurenmd.readthedocs.io/en/latest/changelog.html\n'
)
)
def add_angle_unit_arg(parser):
"""
Add angle unit selectiona argument to parser.
Is defined by ``-a`` and ``--aunit``.
Wether angles are to be calculated in degrees or radians.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to add the topology positionl argument.
""" # noqa: E501
parser.add_argument(
'-a',
'--aunit',
help='Angular unit, either degrees or radians.',
choices=['degrees', 'radians'],
default='degrees',
)
def add_insort_arg(parser):
"""
Sort input by trail int.
Applies :py:func:`taurenmd.libs.libio.sort_numbered_input`.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to add the insort argument.
""" # noqa: E501
parser.add_argument(
'-i',
'--insort',
help=(
'Sorts input trajectories paths according to their tail numbers, '
'if paths are formatted as follows: my_trajectory_#.dcd, '
'where # is a number. Defaults to `False`.'
),
action='store_true',
)
def add_topology_arg(parser):
"""
Add topology positional argument to parser.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to add the topology positionl argument.
""" # noqa: E501
parser.add_argument(
'topology',
help='Path to the topology file.',
type=str,
)
def add_trajectories_arg(parser):
"""
Add trajectory positional argument to parser.
Accepts multiple trajectory files.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to add the trajectory positionl argument.
""" # noqa: E501
parser.add_argument(
'trajectories',
help=(
'Path to the trajectory files. '
'If multiple files are given, '
'trajectories will be concatenated by input order.'
),
nargs='+',
)
def add_trajectory_arg(parser):
"""
Add trajectory positional argument to parser.
Accepts a single trajectory file.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to add the trajectory positionl argument.
""" # noqa: E501
parser.add_argument(
'trajectory',
help='Path to the trajectory file.',
)
def add_slice_arg(parser):
"""
Add start, stop and step slicing arguments.
Slicing arguments are according to `Python Slice object <https://docs.python.org/3/library/functions.html#slice>`_
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to add the trajectory positionl argument.
""" # noqa: E501
parser.add_argument(
'-s',
'--start',
help=(
'The starting index for the frame slicing. '
'Frames are 0-indexed, so the first frame is -s 0. '
'The starting index is inclusive. '
'Defaults to None, considers from the beginning.'
),
default=None,
type=int,
)
parser.add_argument(
'-e',
'--stop',
help=(
'The ending index for the frame slicing. '
'Frames are 0-indexed, so the last frame of a 500 frame '
'trajectory is index 499, but because '
'the ending index is exclusive, -e 500 is required. '
'Defaults to None, considers to the end.'
),
default=None,
type=int,
)
parser.add_argument(
'-p',
'--step',
help=(
'The periodicity step value for the frame slicing, '
'-p 10 means every 10 frames. '
'Defaults to None, considers every 1 frame.'
),
default=None,
type=int,
)
def add_atom_selection_arg(parser):
"""
Add selection optional argument.
Selection argument is a string that defines the atom selection,
this is defined by ``-l`` and ``--selection``, and defaults to ``all``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the selection argument.
""" # noqa: E501
parser.add_argument(
'-l',
'--selection',
help=(
'Atom selection for the output trajectory. '
'Selection rules are as defined by the MD analysis '
'library used by the client interface. '
'For instructions read the main command-line client description. '
'Defaults to \'all\'.'
),
default='all',
type=str,
)
def add_atom_selections_arg(parser):
"""
Add selections optional argument.
Selections argument is a string that defines a list of atom selections,
this is defined by ``-g`` and ``--selections``, and defaults to ``all``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the selections argument.
""" # noqa: E501
parser.add_argument(
'-g',
'--selections',
help=(
'List of atom selections to operate with. '
'Selection rules are as defined by the MD analysis '
'library used by the client interface. '
'For instructions read the main command-line client description. '
'Defaults to None, uses a single selection considering all '
'atoms. '
"Example: -g 'segid A' 'segid B' 'name CA'"
),
default=None,
nargs='+',
)
def add_frame_list_arg(parser):
"""
Add frame list argument.
Registers a list of frame numbers, is defined by ``-t`` and ``--flist``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the flist argument.
""" # noqa: E501
parser.add_argument(
'-t',
'--flist',
help=(
'List of frames (time steps) to consider.'
'If applicable, this can used instead of the start, stop '
'and step slicing arguments.'
),
default=False,
nargs='+',
type=int,
)
def add_plane_selection_arg(parser):
"""
Add plane selection argument.
Plane selection is a selection of three regions separated by 'or'
operator.
Is defined by ``-z`` and ``--plane-selection``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the plane-selection argument.
""" # noqa: E501
parser.add_argument(
'-z',
'--plane-selection',
help=(
'Three selection strings representing three atom regions. '
'The plane is defined by the three centres of geometry '
'of the three selections. For example: '
'-z \'segid A\' \'segid B\' \'segid C\'.'
),
required=True,
nargs=3,
)
def add_reference_frame_arg(parser):
"""
Add a reference frame argument.
Reference frame is the frame to compute the parameter against.
Depending on the client logic the reference frame might have different
meanings.
Is defined by ``-r`` and ``--ref-frame``.
Defaults to ``0``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the refence-frame argument.
""" # noqa: E501
parser.add_argument(
'-r',
'--ref-frame',
help=(
'The frame in the trajectory that serves as '
'reference to compute against.'
'Defaults to 0.'
),
default=0,
type=int,
)
def add_plot_arg(parser):
"""
Add plot parameters.
Plot kwargs that will be passed to the plotting function.
Defined by ``--plot``.
If given, plot results. Additional arguments can be given to
specify the plot parameters.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the plot argument.
""" # noqa: E501
parser.add_argument(
'--plot',
help=(
'Plot results. '
'Additional arguments can be given to configure the plot '
'style. '
'Example: --plot xlabel=frames ylabel=RMSD color=red.'
'Accepted plot arguments are defined by the function used '
'to plot the result. The main description of this client '
'which plotting function is used. '
'Defaults to ``None``, no plot is produced.'
),
nargs='*',
default=False,
action=ParamsToDict,
)
def add_top_output_arg(parser):
"""
Add argument to export first frame as topology PDB file.
Defined by ``-o`` and ``--top-output``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the topology output argument.
""" # noqa: E501
parser.add_argument(
'-o',
'--top-output',
help=(
'Export edited trajectory first frame as topololy file. '
'You can specify the exact file name, otherwise, defaults to '
'input trajectory path + \'_frame0.pdb\'. '
'Also, if name starts with \'_\', it is used as file suffix, '
'if name ends with \'_\', it is used as prefix, instead.'
),
default=False,
const='_frame0.pdb',
nargs='?',
)
def add_traj_output_arg(parser):
"""
Add argument to export trajectory after client modifications.
Defined by ``-d`` and ``--traj-output``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the trajectory output argument.
""" # noqa: E501
parser.add_argument(
'-d',
'--traj-output',
help=(
'Modified trajectory output file name. '
'File type will be defined by file name extension. '
'Defaults to traj_out.dcd.'
),
default='traj_out.dcd',
)
def add_data_export_arg(parser):
"""
Add export argument.
Export argument configures data export to a text file in table format.
Is defined by ``-x`` and ``--export``.
Parameters
----------
parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
The argument parser to which add the export argument.
""" # noqa: E501
parser.add_argument(
'-x',
'--export',
help=(
'Export calculated values to a CSV file. '
'Defaults to \'results.csv\', alternatively, '
'you can give a specific file name.'
),
default=False,
const='results.csv',
nargs='?',
)
class ProgressBar:
"""
Contextualizes a Progress Bar.
Parameters
----------
total : int convertable
The total number o iteractions expected.
prefix : str
Some prefix to enhance readability.
suffix : str
Some suffix to enhance readability.
decimals : int-convertable
The demicals to show in percentage.
Defaults to `1`.
bar_length : int, float, -convertable
The length of the bar.
If not provided (``None``), uses half of the terminal window.
Thanks to for the initial template function:
https://dev.to/natamacm/progressbar-in-python-a3n
Examples
--------
>>> with ProgressBar(5000, suffix='frames') as PB:
>>> for i in trajectory:
>>> # do something
>>> PB.increment()
"""
def __init__(
self,
total,
prefix='',
suffix='',
decimals=1,
bar_length=None,
):
if bar_length is None:
try:
_columns, _rows = os.get_terminal_size()
except OSError:
log.error(
'ERROR: Could not retrive size of ProgressBar '
'from terminal window. Using the default of `50`. '
'Everything else is normal.'
)
# this trick is used to guarantee 100% test coverage
_columns = 100
bar_length = _columns // 2
total = int(total)
self.prefix = prefix
self.suffix = suffix
self.str_format = "{0:." + str(int(decimals)) + "f}"
# using Numpy
self.percentages = np.linspace(0, 100, total + 1, endpoint=True)
# 49.7 µs ± 5.34 µs per loop (7 runs, 10000 loops each)
# Not using Numpy
# self.percentages = [i / total * 100 for i in range(total + 1)]
# 974 µs ± 38.8 µs per loop (7 runs, 1000 loops each)
self.filled_length = \
np.round(bar_length * self.percentages / 100).astype(int)
self.counter = 0
self.total = total
self.bar_length = bar_length
assert len(self.percentages) == total + 1
assert len(self.percentages) == len(self.filled_length)
def __enter__(self):
bar = '-' * self.bar_length
percents = self.str_format.format(self.percentages[0])
sys.stdout.write(
f'\r{self.prefix} |{bar}| '
f'{percents}% {self.counter}/{self.total} {self.suffix}'
)
self.counter += 1
return self
def __exit__(self, *args):
sys.stdout.write('\n')
sys.stdout.flush()
def increment(self):
"""Print next progress bar increment."""
t = self.total
c = self.counter
prefix = self.prefix
suffix = self.suffix
bl = self.bar_length
percents = self.str_format.format(self.percentages[c])
fl = self.filled_length[c]
bar = f"{'█' * fl}{'-' * (bl - fl)}"
sys.stdout.write(f'\r{prefix} |{bar}| {percents}% {c}/{t} {suffix}')
self.counter += 1