-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommandLines.py
827 lines (764 loc) · 32.4 KB
/
commandLines.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
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
import os, argparse, inspect, textwrap, shutil, re, json
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from typing import Union, Callable, Sequence, List, Tuple
class cmdConnect:
"""
Exposes a Python function by creating command line arguments for function parameters automatically.
Attributes:
----------
fun
The function we want to expose to the command line.
doc
Parsed docstring of the function (dictionary)
spect
Result of the inspection (object)
params
Parameters that belong to the master function (list)
args
Argparse object created during init (object)
eval
Runs the function (function)
results
Stores the value(s) returned by the function
save
Saves the result(s) to file(s) if file output was specified. Prints the result as a string otherwise (function)
"""
def __init__(
self,
fun: Callable,
paramtune: Union[None, dict] = None,
):
"""
Adds parameters of the function to argparse.
Sets output files if needed.
Parameters
----------
fun
The function we want to expose to the command line.
paramtune
A dictionary of tuples for those parameters that need extra settings in argparse.
Keys are the parameter names in the function if associated with the input.
First element of the tuple specifies if the argument is associated with the input (`0`) or the output.
Last element is a dictionary, passed as keyword arguments to argparse.
The remaining elements inbetween will be passed as positional arguments (alternative names for the parameter).
"""
finetuned = {
"self": (
0,
"--denied",
{
"dest": "self",
"default": None,
"help": "A mock switch to prevent self of a function defined in an object get exposed.",
},
)
}
if paramtune is None:
paramtune = dict()
finetuned.update(paramtune)
paramtune = finetuned.copy()
argreverse = dict()
# Collect information on the master function and its parameters
doc = self.parseDocstring(fun)
pars = doc["params"]
spect = inspect.getfullargspec(fun)
parser = argparse.ArgumentParser(
description=doc["description"],
formatter_class=argparse.RawTextHelpFormatter,
)
arglist = list()
if isinstance(spect.args, list):
arglist += spect.args
if isinstance(spect.varargs, list):
arglist += spect.varargs
if isinstance(spect.kwonlyargs, list):
arglist += spect.kwonlyargs
pardef = spect.kwonlydefaults
# Add version and an option that shows what is the master function and what other functions are defined in the script
dcs = fun.__doc__
if dcs is None:
dcs = ""
long_doc = "The master function:\n\n"
long_doc += fun.__name__ + "\n"
long_doc += dcs + "\n\n\n"
long_doc += "The helper functions:\n\n"
for n, f in [
o
for o in inspect.getmembers(inspect.getmodule(fun))
if inspect.isfunction(o[1])
]:
if n not in ["main", fun.__name__]:
long_doc += n + "\n"
dc = f.__doc__
if dc is None:
dc = ""
long_doc += dc + "\n\n\n"
try:
parser.add_argument(
"-version",
"--version",
action="version",
version=inspect.getmodule(fun).__version__,
help="Displays script version if supplied",
)
except:
pass
parser.add_argument(
"-i",
"--inspect",
action="version",
version=long_doc,
help="Shows what functions are defined",
)
# Add a switch to peek into the results by printing or saving the first N lines only
parser.add_argument(
"-p",
"--peek",
dest="displayMax",
type=lambda s: [x for x in s.split(",")],
help="Peek into the results by printing or saving the first N lines only",
)
parser.register("action", "exappend", self.ExtendAction)
# Add an instance for every parameter of the master function to the main argparse parser
for p in arglist:
help_msg = ""
if p in pars:
help_msg = pars[p]
tune = False
if p in paramtune:
t = paramtune[p]
if t[0] == 0:
tune = True
else:
tune = True
t = [0, p]
if tune:
if type(t[-1]) == dict:
kwargs = t[-1]
args = t[1:-1]
else:
kwargs = dict()
args = t[1:]
if "help" not in kwargs:
kwargs["help"] = help_msg
if "default" not in kwargs:
if spect.kwonlydefaults is not None:
if p in spect.kwonlydefaults:
kwargs["default"] = spect.kwonlydefaults[p]
if "type" not in kwargs:
if p in spect.annotations:
tp = spect.annotations[p]
if tp in (int, float, list, tuple):
kwargs["type"] = tp
else:
try:
if list in tp.__args__:
kwargs["type"] = list
except:
pass
# Solve the comma or space problem
if "type" in kwargs:
if kwargs["type"] in [
list,
tuple,
"str_list",
"int_list",
"float_list",
]:
if "nargs" not in kwargs:
kwargs["nargs"] = "*"
if "action" not in kwargs:
kwargs["action"] = "exappend"
if "default" in kwargs:
if kwargs["default"] is not None:
kwargs["default"] = []
if kwargs["type"] in ["int_list", "float_list"]:
if kwargs["type"] == "int_list":
kwargs["type"] = self.intSplitter
else:
kwargs["type"] = self.floatSplitter
else:
kwargs["type"] = lambda s: s.split(",")
if "default" in kwargs and len(t) < 3:
kwargs["dest"] = p
args[0] = "--" + p
if "dest" in kwargs:
argreverse[kwargs["dest"]] = args[0] + " "
else:
argreverse[args[0]] = ""
parser.add_argument(*args, **kwargs)
else:
parser.add_argument(p, help=help_msg)
argreverse[args[0]] = ""
# Parameters defined in the finetune dictionary, but not belonging to the master input, are assumed to belong to the output
returnlen = 1
outnames = dict()
for remaining in set(paramtune.keys()) - set(arglist + ["self"]):
t = paramtune[remaining]
o = t[0]
if t[1] is None:
if o > returnlen:
returnlen = o
else:
if type(t[-1]) == dict:
kwargs = t[-1]
args = t[1:-1]
else:
kwargs = dict()
args = t[1:]
if "dest" in kwargs:
outnames[o] = kwargs["dest"]
else:
outnames[o] = args[0]
if o > returnlen:
returnlen = o
parser.add_argument(*args, **kwargs)
rl = []
for i in range(returnlen):
rl.append([outnames.pop(i + 1, None), None])
# Bind information that might be reused later to the object
self.fun = fun
self.doc = doc
self.spect = spect
self.params = arglist
self.cmd_args = parser
self.argreverse = argreverse
self.results = rl
class ExtendAction(argparse.Action):
"""
Redefine the extension module of Argparse to support multiple list notations in command line.
"""
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest) or []
if type(items) is not list:
items = []
for v in values:
items += v
setattr(namespace, self.dest, items)
def eval(self):
"""
Run the master function and store its results.
"""
self.args, rest = self.cmd_args.parse_known_args()
args, kwargs = [], dict()
spected = self.spect.args
for p in self.params:
if p in spected:
args.append(getattr(self.args, p))
else:
kwargs[p] = getattr(self.args, p)
rs = self.fun(*args, *rest, **kwargs)
if rs is not None:
if len(self.results) > 1:
for i in range(len(rs)):
try:
resfile = self.results[i][0]
if resfile is not None:
resfile = getattr(self.args, resfile)
except:
resfile = None
try:
self.results[i] = (resfile, rs[i])
except:
self.results.append((resfile, rs[i]))
else:
try:
resfile = self.results[0][0]
if resfile is not None:
resfile = getattr(self.args, resfile)
except:
resfile = None
self.results = [(resfile, rs)]
return
def save(
self,
filenames: Union[None, str, list] = None,
formatfunctions: Union[None, Callable, list] = None,
formatargs: Union[None, dict, list] = None,
) -> None:
"""
Save the output of the master function.
Parameters
----------
filenames
Overwrite the default value (None, meaning the string will be printed) of the file names.
formatfunctions
Specify how the output should be formatted. Using default formatters, (e.g. every list element in a new line) if not set.
formatargs
A dictionary of arguments for each format function that will be passed on.
"""
N = len(self.results)
if formatfunctions is not None:
if type(formatfunctions) is Callable:
formatfunctions = formatfunctions
else:
formatfunctions = []
for i in range(N):
formatfunctions.append(None)
if formatargs is not None:
if type(formatargs) is dict:
formatargs = formatargs
else:
for i in range(N):
if formatargs[i] is None:
formatargs[i] = dict()
else:
formatargs = []
for i in range(N):
formatargs.append(dict())
for i in range(N):
o = ""
fn, r = self.results[i]
to_be_written = True
if fn is not None:
if fn[-5:] in ".json":
to_be_written = False
if to_be_written:
if formatfunctions[i] is None:
if isinstance(r, (pd.DataFrame, plt.Axes, sns.matrix.ClusterGrid)):
pass
else:
if isinstance(
r, (str, int, float, dict, set, list, tuple, np.ndarray)
):
if isinstance(r, (int, float)):
r = str(r)
else:
if isinstance(r, (set, list, tuple, np.ndarray)):
if isinstance(r, set):
r = list(r)
row = r[0]
if isinstance(
row,
(str, int, float, set, list, tuple, np.ndarray),
):
if isinstance(row, str):
r = "\n".join(r) + "\n"
else:
if isinstance(row[0], plt.Axes):
rn = list()
for row in r:
rn.append(row[0])
r = rn
else:
if not isinstance(r, np.ndarray):
r = np.array(r)
r = r.astype(str)
if isinstance(row, (int, float)):
r = "\n".join(r) + "\n"
else:
r = (
"\n".join(
np.apply_along_axis(
lambda x: np.asarray(
"\t".join(x),
dtype=object,
),
1,
r,
)
)
+ "\n"
)
else:
if isinstance(row, dict):
colnames = set()
for d in r:
colnames.update(d.keys())
colnames = tuple(colnames)
t = (
"\t".join([str(x) for x in colnames])
+ "\n"
)
for d in r:
t += (
"\t".join(
[str(d[x]) for x in colnames]
)
+ "\n"
)
r = t
else:
if isinstance(row, plt.Axes):
r = row
else:
try:
r = (
"\n".join([str(x) for x in r])
+ "\n"
)
except:
print(
"No built-in method to save result ["
+ str(i)
+ "] of type "
+ type(r).__name__
)
else:
if isinstance(r, dict):
try:
k, row = r.popitem()
r[k] = row
except:
row = ""
if isinstance(row, (str, int, float)):
r = (
"\n".join(
[
str(x) + "\t" + str(y)
for x, y in r.items()
]
)
+ "\n"
)
else:
if isinstance(
row, (set, list, tuple, np.ndarray)
):
r = (
"\n".join(
[
str(x)
+ "\t"
+ "\t".join(
[str(z) for z in y]
)
for x, y in r.items()
]
)
+ "\n"
)
else:
if isinstance(row, dict):
colnames = set()
for k, d in r.items():
colnames.update(d.keys())
colnames = tuple(colnames)
t = (
"\t"
+ "\t".join(
[str(x) for x in colnames]
)
+ "\n"
)
for k, d in r.items():
t += (
k
+ "\t"
+ "\t".join(
[
str(d[x])
for x in colnames
]
)
+ "\n"
)
r = t
else:
try:
r = (
"\n".join(
[
str(x)
+ "\t"
+ str(y)
for x, y in r.items()
]
)
+ "\n"
)
except:
print(
"No built-in method to save result ["
+ str(i)
+ "] of type "
+ type(row).__name__
)
else:
try:
r = str(r)
except:
print(
"No built-in method to save result ["
+ str(i)
+ "] of type "
+ type(r).__name__
)
else:
r = formatfunctions[i](**formatargs[i])
if self.args.displayMax is not None and not isinstance(
r, plt.Axes, sns.matrix.ClusterGrid
):
rN = self.args.displayMax
if isinstance(r, pd.DataFrame):
rN = int(rN[0])
if rN > 0:
r = r.head(rN)
else:
r = r.tail(-1 * rN)
else:
if len(rN) == 1:
rN = rN[0]
rC = None
else:
rN, rC = rN[:2]
if rC not in ["", None]:
r = r[: int(rC)]
if rN not in ["", None]:
rN = int(rN)
r = r.split("\n")[:rN]
r = "\n".join(r)
if r[-1] != "\n":
r += "\n"
if fn is None:
if isinstance(r, plt.Axes):
print("Figure cannot be displayed")
else:
print(r)
else:
if isinstance(
r, (list, pd.DataFrame, plt.Axes, sns.matrix.ClusterGrid)
):
if isinstance(r, (list, pd.DataFrame)):
if isinstance(r, pd.DataFrame):
r.to_csv(fn, sep="\t")
else: # TODO: refactor this part into a separate figsaver function
tx = []
if isinstance(r[0], plt.Axes):
if (
fn.split(".")[-1]
in r[0].figure.canvas.get_supported_filetypes()
):
for i, e in enumerate(r):
nfn = os.path.realpath(
".".join(fn.split(".")[:-1])
+ "_"
+ str(i)
+ fn.split(".")[-1]
)
e.figure.savefig(nfn)
tx.append(nfn)
else:
for i, e in enumerate(r):
nfn = os.path.realpath(fn + "_" + str(i))
try:
e.figure.savefig(nfn + ".png")
except:
pass
e.figure.savefig(nfn + ".pgf")
tx.append(nfn + ".pgf")
else:
for i, e in enumerate(r):
nfn = os.path.realpath(
".".join(fn.split(".")[:-1])
+ "_"
+ str(i)
+ fn.split(".")[-1]
)
e.savefig(nfn)
tx.append(nfn)
with open(fn + ".txt", "w") as f:
f.write("\n".join(tx))
else:
if isinstance(r, plt.Axes):
if (
fn.split(".")[-1]
in r.figure.canvas.get_supported_filetypes()
):
r.figure.savefig(fn)
else:
try:
r.figure.savefig(fn + ".png")
except:
pass
r.figure.savefig(fn + ".pgf")
else:
r.savefig(fn)
else:
if fn[-5:] == ".json":
with open(fn, "w") as f:
json.dump(r, f)
else:
with open(fn, "w") as f:
f.write(r)
return
def parseDocstring(self, fun: Callable) -> dict:
"""
Parse the docstring of a function to extract parameter descriptions.
Parameters
----------
fun
The function we need the parsed docstring for.
Returns
-------
A dictionary with all the descriptions.
"""
PARAM_OR_RETURNS_REGEX = re.compile("(?:\s{2,}(Parameters|Returns)\s+-{3,})")
RETURNS_REGEX = re.compile("\s{2,}Returns\s+-{3,}\s+(?P<doc>.*)", re.S)
PARAMSTART_REGEX = re.compile("(?:\s{2,}Parameters\s+-{3,})")
PARAM_REGEX = re.compile("\s+(?P<name>[\*\w]+)\n\s+(?P<doc>.*)", re.M)
def reindent(string):
return "\n".join(l.strip() for l in string.strip().split("\n"))
params = dict()
returns = ""
short_description, description = "", ""
docstring = fun.__doc__
try:
docstring = docstring.strip()
except:
docstring = ""
if docstring:
lines = docstring.split("\n", 1)
short_description = lines[0]
if len(lines) > 1:
params_returns_desc = ""
match = PARAM_OR_RETURNS_REGEX.search(docstring)
if match:
long_desc_end = match.start()
params_returns_desc = docstring[long_desc_end:].strip()
description = docstring[:long_desc_end].rstrip()
match = RETURNS_REGEX.search(params_returns_desc)
if match:
returns = reindent(match.group("doc"))
long_desc_end = match.start()
params_returns_desc = params_returns_desc[:long_desc_end]
match = PARAMSTART_REGEX.search(params_returns_desc)
if match:
long_desc_start = match.end()
params_returns_desc = params_returns_desc[long_desc_start:]
params = dict(PARAM_REGEX.findall(params_returns_desc))
else:
description = short_description
return {
"description": description,
"short_description": short_description,
"params": params,
"returns": returns,
}
def intSplitter(self, s: str) -> list:
"""
Split a string into list of integers.
Changes NaN to zero.
Parameters
----------
s
The string(s) supplied via command line.
Returns
-------
List of integers.
"""
l = []
for e in s.split(","):
try:
e = int(e)
except:
e = 0
l.append(e)
return l
def floatSplitter(self, s: str) -> list:
"""
Split a string into list of floats.
Changes NaN to zero.
Parameters
----------
s
The string(s) supplied via command line.
Returns
-------
List of floats.
"""
l = []
for e in s.split(","):
try:
e = float(e)
except:
e = 0
l.append(e)
return l
def startScriptConneted(
dr: str,
) -> str:
"""
Adds a heading to autogenerated scripts with shebang and import of introSpect.
Parameters
----------
dr
The directory where to develompental packages live.
Returns
-------
A heading for scripts (in Nextflow bin).
"""
connected = (
"""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append('"""
+ dr
+ """')
import introSpect
"""
)
return connected[1:]
def endScriptConneted(
f: Callable,
modified_kws: str,
) -> str:
"""
Adds a footer to autogenerated scripts with a `main` function accessible to
commandline.
Parameters
----------
f
The most important function in the script that gets wrapped in `main` and exposed.
modified_kws
Command line arguments that are not autogenreated from the function, but added
manually. Typically those controlling execution (verbose) and output (file name).
Returns
-------
A footer for scripts (in Nextflow bin).
"""
connected = (
"""
def main():
mainFunction = introSpect.commandLines.cmdConnect("""
+ f
+ """, """
+ str(modified_kws)
+ """)
mainFunction.eval()
mainFunction.save()
return
if __name__ == '__main__':
main()
"""
)
return textwrap.dedent(connected)
def saveToScript(process, fn, dr, dependencies, modified_kws={}):
l_imports = dependencies["imports"]
l_packages = dependencies["inhouse_packages"]
l_packages = [os.path.dirname(os.path.abspath(__file__))] + l_packages
for i, p in enumerate(l_packages):
packdir = p.split("/")[-1]
if i > 0:
l_imports = ["import " + packdir] + l_imports
shutil.copytree(
p,
dr + "/packages/" + packdir,
dirs_exist_ok=True,
ignore=shutil.ignore_patterns(".*"),
)
recipe = textwrap.dedent(startScriptConneted(dr + "/packages"))
recipe += "\n" + "\n".join(l_imports) + "\n\n"
recipe += textwrap.dedent(inspect.getsource(process).replace("self,", ""))
for helper_fun in dependencies["helpers"]:
recipe += "\n" + textwrap.dedent(inspect.getsource(helper_fun)) + "\n"
recipe += endScriptConneted(process.__name__, modified_kws)
fn = dr + "/" + fn
with open(fn, "w") as f:
f.write(recipe)
os.chmod(fn, 0o775)
return