/
script.py
1369 lines (1230 loc) · 42.9 KB
/
script.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
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
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2021, Johannes Köster"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
import inspect
import itertools
import os
from snakemake import sourcecache
from snakemake.sourcecache import (
LocalSourceFile,
SourceCache,
SourceFile,
infer_source_file,
)
import tempfile
import textwrap
import sys
import pickle
import subprocess
import collections
import re
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Tuple, Pattern, Union, Optional
from urllib.request import urlopen, pathname2url
from urllib.error import URLError
from snakemake.utils import format
from snakemake.logging import logger
from snakemake.exceptions import WorkflowError
from snakemake.shell import shell
from snakemake.common import (
MIN_PY_VERSION,
SNAKEMAKE_SEARCHPATH,
ON_WINDOWS,
smart_join,
is_local_file,
)
from snakemake.io import git_content, split_git_path
from snakemake.deployment import singularity
# TODO use this to find the right place for inserting the preamble
PY_PREAMBLE_RE = re.compile(r"from( )+__future__( )+import.*?(?P<end>[;\n])")
PathLike = Union[str, Path, os.PathLike]
class Snakemake:
def __init__(
self,
input_,
output,
params,
wildcards,
threads,
resources,
log,
config,
rulename,
bench_iteration,
scriptdir=None,
):
# convert input and output to plain strings as some remote objects cannot
# be pickled
self.input = input_._plainstrings()
self.output = output._plainstrings()
self.params = params
self.wildcards = wildcards
self.threads = threads
self.resources = resources
self.log = log._plainstrings()
self.config = config
self.rule = rulename
self.bench_iteration = bench_iteration
self.scriptdir = scriptdir
def log_fmt_shell(self, stdout=True, stderr=True, append=False):
"""
Return a shell redirection string to be used in `shell()` calls
This function allows scripts and wrappers support optional `log` files
specified in the calling rule. If no `log` was specified, then an
empty string "" is returned, regardless of the values of `stdout`,
`stderr`, and `append`.
Parameters
---------
stdout : bool
Send stdout to log
stderr : bool
Send stderr to log
append : bool
Do not overwrite the log file. Useful for sending output of
multiple commands to the same log. Note however that the log will
not be truncated at the start.
The following table describes the output:
-------- -------- -------- ----- -------------
stdout stderr append log return value
-------- -------- -------- ----- ------------
True True True fn >> fn 2>&1
True False True fn >> fn
False True True fn 2>> fn
True True False fn > fn 2>&1
True False False fn > fn
False True False fn 2> fn
any any any None ""
-------- -------- -------- ----- -----------
"""
return _log_shell_redirect(self.log, stdout, stderr, append)
def _log_shell_redirect(
log: Optional[PathLike],
stdout: bool = True,
stderr: bool = True,
append: bool = False,
) -> str:
"""
Return a shell redirection string to be used in `shell()` calls
This function allows scripts and wrappers support optional `log` files
specified in the calling rule. If no `log` was specified, then an
empty string "" is returned, regardless of the values of `stdout`,
`stderr`, and `append`.
Parameters
---------
stdout : bool
Send stdout to log
stderr : bool
Send stderr to log
append : bool
Do not overwrite the log file. Useful for sending output of
multiple commands to the same log. Note however that the log will
not be truncated at the start.
The following table describes the output:
-------- -------- -------- ----- -------------
stdout stderr append log return value
-------- -------- -------- ----- ------------
True True True fn >> fn 2>&1
True False True fn >> fn
False True True fn 2>> fn
True True False fn > fn 2>&1
True False False fn > fn
False True False fn 2> fn
any any any None ""
-------- -------- -------- ----- -----------
"""
if not log:
return ""
lookup = {
(True, True, True): " >> {0} 2>&1",
(True, False, True): " >> {0}",
(False, True, True): " 2>> {0}",
(True, True, False): " > {0} 2>&1",
(True, False, False): " > {0}",
(False, True, False): " 2> {0}",
}
return lookup[(stdout, stderr, append)].format(str(log))
class REncoder:
"""Encoding Pyton data structures into R."""
@classmethod
def encode_numeric(cls, value):
if value is None:
return "as.numeric(NA)"
return str(value)
@classmethod
def encode_value(cls, value):
if value is None:
return "NULL"
elif isinstance(value, str):
return repr(value)
elif isinstance(value, Path):
return repr(str(value))
elif isinstance(value, dict):
return cls.encode_dict(value)
elif isinstance(value, bool):
return "TRUE" if value else "FALSE"
elif isinstance(value, int) or isinstance(value, float):
return str(value)
elif isinstance(value, collections.abc.Iterable):
# convert all iterables to vectors
return cls.encode_list(value)
else:
# Try to convert from numpy if numpy is present
try:
import numpy as np
if isinstance(value, np.number):
return str(value)
except ImportError:
pass
raise ValueError("Unsupported value for conversion into R: {}".format(value))
@classmethod
def encode_list(cls, l):
return "c({})".format(", ".join(map(cls.encode_value, l)))
@classmethod
def encode_items(cls, items):
def encode_item(item):
name, value = item
return '"{}" = {}'.format(name, cls.encode_value(value))
return ", ".join(map(encode_item, items))
@classmethod
def encode_dict(cls, d):
d = "list({})".format(cls.encode_items(d.items()))
return d
@classmethod
def encode_namedlist(cls, namedlist):
positional = ", ".join(map(cls.encode_value, namedlist))
named = cls.encode_items(namedlist.items())
source = "list("
if positional:
source += positional
if named:
source += ", " + named
source += ")"
return source
class JuliaEncoder:
"""Encoding Pyton data structures into Julia."""
@classmethod
def encode_value(cls, value):
if value is None:
return "nothing"
elif isinstance(value, str):
return repr(value)
elif isinstance(value, Path):
return repr(str(value))
elif isinstance(value, dict):
return cls.encode_dict(value)
elif isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, int) or isinstance(value, float):
return str(value)
elif isinstance(value, collections.abc.Iterable):
# convert all iterables to vectors
return cls.encode_list(value)
else:
# Try to convert from numpy if numpy is present
try:
import numpy as np
if isinstance(value, np.number):
return str(value)
except ImportError:
pass
raise ValueError(
"Unsupported value for conversion into Julia: {}".format(value)
)
@classmethod
def encode_list(cls, l):
return "[{}]".format(", ".join(map(cls.encode_value, l)))
@classmethod
def encode_items(cls, items):
def encode_item(item):
name, value = item
return '"{}" => {}'.format(name, cls.encode_value(value))
return ", ".join(map(encode_item, items))
@classmethod
def encode_positional_items(cls, namedlist):
encoded = ""
for index, value in enumerate(namedlist):
encoded += "{} => {}, ".format(index + 1, cls.encode_value(value))
return encoded
@classmethod
def encode_dict(cls, d):
d = "Dict({})".format(cls.encode_items(d.items()))
return d
@classmethod
def encode_namedlist(cls, namedlist):
positional = cls.encode_positional_items(namedlist)
named = cls.encode_items(namedlist.items())
source = "Dict("
if positional:
source += positional
if named:
source += named
source += ")"
return source
class ScriptBase(ABC):
editable = False
def __init__(
self,
path,
source,
basedir,
input_,
output,
params,
wildcards,
threads,
resources,
log,
config,
rulename,
conda_env,
conda_base_path,
container_img,
singularity_args,
env_modules,
bench_record,
jobid,
bench_iteration,
cleanup_scripts,
shadow_dir,
is_local,
):
self.path = path
self.source = source
self.basedir = basedir
self.input = input_
self.output = output
self.params = params
self.wildcards = wildcards
self.threads = threads
self.resources = resources
self.log = log
self.config = config
self.rulename = rulename
self.conda_env = conda_env
self.conda_base_path = conda_base_path
self.container_img = container_img
self.singularity_args = singularity_args
self.env_modules = env_modules
self.bench_record = bench_record
self.jobid = jobid
self.bench_iteration = bench_iteration
self.cleanup_scripts = cleanup_scripts
self.shadow_dir = shadow_dir
self.is_local = is_local
def evaluate(self, edit=False):
assert not edit or self.editable
fd = None
try:
# generate preamble
preamble = self.get_preamble()
# write script
dir_ = ".snakemake/scripts"
os.makedirs(dir_, exist_ok=True)
with tempfile.NamedTemporaryFile(
suffix="." + self.path.get_filename(), dir=dir_, delete=False
) as fd:
self.write_script(preamble, fd)
# execute script
self.execute_script(fd.name, edit=edit)
except URLError as e:
raise WorkflowError(e)
finally:
if fd and self.cleanup_scripts:
os.remove(fd.name)
else:
if fd:
logger.warning("Not cleaning up %s" % fd.name)
else:
# nothing to clean up (TODO: ??)
pass
@property
def local_path(self):
path = self.path[7:]
if not os.path.isabs(path):
return smart_join(self.basedir, path)
return path
@abstractmethod
def get_preamble(self):
...
@abstractmethod
def write_script(self, preamble, fd):
...
@abstractmethod
def execute_script(self, fname, edit=False):
...
def _execute_cmd(self, cmd, **kwargs):
return shell(
cmd,
bench_record=self.bench_record,
conda_env=self.conda_env,
conda_base_path=self.conda_base_path,
container_img=self.container_img,
shadow_dir=self.shadow_dir,
env_modules=self.env_modules,
singularity_args=self.singularity_args,
resources=self.resources,
threads=self.threads,
**kwargs
)
class PythonScript(ScriptBase):
@staticmethod
def generate_preamble(
path,
source,
basedir,
input_,
output,
params,
wildcards,
threads,
resources,
log,
config,
rulename,
conda_env,
container_img,
singularity_args,
env_modules,
bench_record,
jobid,
bench_iteration,
cleanup_scripts,
shadow_dir,
is_local,
preamble_addendum="",
):
snakemake = Snakemake(
input_,
output,
params,
wildcards,
threads,
resources,
log,
config,
rulename,
bench_iteration,
path.get_basedir().get_path_or_uri(),
)
snakemake = pickle.dumps(snakemake)
# Obtain search path for current snakemake module.
# The module is needed for unpickling in the script.
# We append it at the end (as a fallback).
searchpath = SNAKEMAKE_SEARCHPATH
if container_img is not None:
searchpath = singularity.SNAKEMAKE_MOUNTPOINT
searchpath = repr(searchpath)
# For local scripts, add their location to the path in case they use path-based imports
if is_local:
searchpath += ", " + repr(path.get_basedir().get_path_or_uri())
return textwrap.dedent(
"""
######## snakemake preamble start (automatically inserted, do not edit) ########
import sys; sys.path.extend([{searchpath}]); import pickle; snakemake = pickle.loads({snakemake}); from snakemake.logging import logger; logger.printshellcmds = {printshellcmds}; {preamble_addendum}
######## snakemake preamble end #########
"""
).format(
searchpath=searchpath,
snakemake=snakemake,
printshellcmds=logger.printshellcmds,
preamble_addendum=preamble_addendum,
)
def get_preamble(self):
if isinstance(self.path, LocalSourceFile):
file_override = os.path.realpath(self.path.get_path_or_uri())
else:
file_override = self.path.get_path_or_uri()
preamble_addendum = (
"__real_file__ = __file__; __file__ = {file_override};".format(
file_override=repr(file_override)
)
)
return PythonScript.generate_preamble(
self.path,
self.source,
self.basedir,
self.input,
self.output,
self.params,
self.wildcards,
self.threads,
self.resources,
self.log,
self.config,
self.rulename,
self.conda_env,
self.container_img,
self.singularity_args,
self.env_modules,
self.bench_record,
self.jobid,
self.bench_iteration,
self.cleanup_scripts,
self.shadow_dir,
self.is_local,
preamble_addendum=preamble_addendum,
)
def write_script(self, preamble, fd):
fd.write(preamble.encode())
fd.write(self.source.encode())
def _is_python_env(self):
if self.conda_env is not None:
prefix = os.path.join(self.conda_env, "bin")
elif self.env_modules is not None:
prefix = self._execute_cmd("echo $PATH", read=True).split(":")[0]
else:
raise NotImplementedError()
return os.path.exists(os.path.join(prefix, "python"))
def _get_python_version(self):
out = self._execute_cmd(
"python -c \"import sys; print('.'.join(map(str, sys.version_info[:2])))\"",
read=True,
)
return tuple(map(int, out.strip().split(".")))
def execute_script(self, fname, edit=False):
py_exec = sys.executable
if self.container_img is not None:
# use python from image
py_exec = "python"
elif self.conda_env is not None or self.env_modules is not None:
if self._is_python_env():
py_version = self._get_python_version()
# If version is None, all fine, because host python usage is intended.
if py_version is not None:
if py_version >= MIN_PY_VERSION:
# Python version is new enough, make use of environment
# to execute script
py_exec = "python"
else:
logger.warning(
"Environment defines Python "
"version < {0}.{1}. Using Python of the "
"main process to execute "
"script. Note that this cannot be avoided, "
"because the script uses data structures from "
"Snakemake which are Python >={0}.{1} "
"only.".format(*MIN_PY_VERSION)
)
if ON_WINDOWS:
# use forward slashes so script command still works even if
# bash is configured as executable on Windows
py_exec = py_exec.replace("\\", "/")
# use the same Python as the running process or the one from the environment
self._execute_cmd("{py_exec} {fname:q}", py_exec=py_exec, fname=fname)
class RScript(ScriptBase):
@staticmethod
def generate_preamble(
path,
source,
basedir,
input_,
output,
params,
wildcards,
threads,
resources,
log,
config,
rulename,
conda_env,
container_img,
singularity_args,
env_modules,
bench_record,
jobid,
bench_iteration,
cleanup_scripts,
shadow_dir,
preamble_addendum="",
):
return textwrap.dedent(
"""
######## snakemake preamble start (automatically inserted, do not edit) ########
library(methods)
Snakemake <- setClass(
"Snakemake",
slots = c(
input = "list",
output = "list",
params = "list",
wildcards = "list",
threads = "numeric",
log = "list",
resources = "list",
config = "list",
rule = "character",
bench_iteration = "numeric",
scriptdir = "character",
source = "function"
)
)
snakemake <- Snakemake(
input = {},
output = {},
params = {},
wildcards = {},
threads = {},
log = {},
resources = {},
config = {},
rule = {},
bench_iteration = {},
scriptdir = {},
source = function(...){{
wd <- getwd()
setwd(snakemake@scriptdir)
source(...)
setwd(wd)
}}
)
{preamble_addendum}
######## snakemake preamble end #########
"""
).format(
REncoder.encode_namedlist(input_),
REncoder.encode_namedlist(output),
REncoder.encode_namedlist(params),
REncoder.encode_namedlist(wildcards),
threads,
REncoder.encode_namedlist(log),
REncoder.encode_namedlist(
{
name: value
for name, value in resources.items()
if name != "_cores" and name != "_nodes"
}
),
REncoder.encode_dict(config),
REncoder.encode_value(rulename),
REncoder.encode_numeric(bench_iteration),
REncoder.encode_value(path.get_basedir().get_path_or_uri()),
preamble_addendum=preamble_addendum,
)
def get_preamble(self):
return RScript.generate_preamble(
self.path,
self.source,
self.basedir,
self.input,
self.output,
self.params,
self.wildcards,
self.threads,
self.resources,
self.log,
self.config,
self.rulename,
self.conda_env,
self.container_img,
self.singularity_args,
self.env_modules,
self.bench_record,
self.jobid,
self.bench_iteration,
self.cleanup_scripts,
self.shadow_dir,
)
def write_script(self, preamble, fd):
fd.write(preamble.encode())
fd.write(self.source.encode())
def execute_script(self, fname, edit=False):
if self.conda_env is not None and "R_LIBS" in os.environ:
logger.warning(
"R script job uses conda environment but "
"R_LIBS environment variable is set. This "
"is likely not intended, as R_LIBS can "
"interfere with R packages deployed via "
"conda. Consider running `unset R_LIBS` or "
"remove it entirely before executing "
"Snakemake."
)
self._execute_cmd("Rscript --vanilla {fname:q}", fname=fname)
class RMarkdown(ScriptBase):
def get_preamble(self):
return textwrap.dedent(
"""
######## snakemake preamble start (automatically inserted, do not edit) ########
library(methods)
Snakemake <- setClass(
"Snakemake",
slots = c(
input = "list",
output = "list",
params = "list",
wildcards = "list",
threads = "numeric",
log = "list",
resources = "list",
config = "list",
rule = "character",
bench_iteration = "numeric",
scriptdir = "character",
source = "function"
)
)
snakemake <- Snakemake(
input = {},
output = {},
params = {},
wildcards = {},
threads = {},
log = {},
resources = {},
config = {},
rule = {},
bench_iteration = {},
scriptdir = {},
source = function(...){{
wd <- getwd()
setwd(snakemake@scriptdir)
source(...)
setwd(wd)
}}
)
######## snakemake preamble end #########
"""
).format(
REncoder.encode_namedlist(self.input),
REncoder.encode_namedlist(self.output),
REncoder.encode_namedlist(self.params),
REncoder.encode_namedlist(self.wildcards),
self.threads,
REncoder.encode_namedlist(self.log),
REncoder.encode_namedlist(
{
name: value
for name, value in self.resources.items()
if name != "_cores" and name != "_nodes"
}
),
REncoder.encode_dict(self.config),
REncoder.encode_value(self.rulename),
REncoder.encode_numeric(self.bench_iteration),
REncoder.encode_value(self.path.get_basedir().get_path_or_uri()),
)
def write_script(self, preamble, fd):
# Insert Snakemake object after the RMarkdown header
code = self.source
pos = next(itertools.islice(re.finditer(r"---\n", code), 1, 2)).start() + 3
fd.write(str.encode(code[:pos]))
preamble = textwrap.dedent(
"""
```{r, echo=FALSE, message=FALSE, warning=FALSE}
%s
```
"""
% preamble
)
fd.write(preamble.encode())
fd.write(code[pos:].encode())
def execute_script(self, fname, edit=False):
if len(self.output) != 1:
raise WorkflowError(
"RMarkdown scripts (.Rmd) may only have a single output file."
)
out = os.path.abspath(self.output[0])
self._execute_cmd(
'Rscript --vanilla -e \'rmarkdown::render("{fname}", output_file="{out}", quiet=TRUE, knit_root_dir = "{workdir}", params = list(rmd="{fname}"))\'',
fname=fname,
out=out,
workdir=os.getcwd(),
)
class JuliaScript(ScriptBase):
def get_preamble(self):
return textwrap.dedent(
"""
######## snakemake preamble start (automatically inserted, do not edit) ########
struct Snakemake
input::Dict
output::Dict
params::Dict
wildcards::Dict
threads::Int64
log::Dict
resources::Dict
config::Dict
rule::String
bench_iteration
scriptdir::String
#source::Any
end
snakemake = Snakemake(
{}, #input::Dict
{}, #output::Dict
{}, #params::Dict
{}, #wildcards::Dict
{}, #threads::Int64
{}, #log::Dict
{}, #resources::Dict
{}, #config::Dict
{}, #rule::String
{}, #bench_iteration::Int64
{}, #scriptdir::String
#, #source::Any
)
######## snakemake preamble end #########
""".format(
JuliaEncoder.encode_namedlist(self.input),
JuliaEncoder.encode_namedlist(self.output),
JuliaEncoder.encode_namedlist(self.params),
JuliaEncoder.encode_namedlist(self.wildcards),
JuliaEncoder.encode_value(self.threads),
JuliaEncoder.encode_namedlist(self.log),
JuliaEncoder.encode_namedlist(
{
name: value
for name, value in self.resources.items()
if name != "_cores" and name != "_nodes"
}
),
JuliaEncoder.encode_dict(self.config),
JuliaEncoder.encode_value(self.rulename),
JuliaEncoder.encode_value(self.bench_iteration),
JuliaEncoder.encode_value(self.path.get_basedir().get_path_or_uri()),
).replace(
"'", '"'
)
)
def write_script(self, preamble, fd):
fd.write(preamble.encode())
fd.write(self.source.encode())
def execute_script(self, fname, edit=False):
self._execute_cmd("julia {fname:q}", fname=fname)
class RustScript(ScriptBase):
@staticmethod
def generate_preamble(
path,
source,
basedir,
input_,
output,
params,
wildcards,
threads,
resources,
log,
config,
rulename,
conda_env,
container_img,
singularity_args,
env_modules,
bench_record,
jobid,
bench_iteration,
cleanup_scripts,
shadow_dir,
is_local,
preamble_addendum="",
):
# snakemake's namedlists will be encoded as a dict
# which stores the not-named items at the key "positional"
# and unpacks named items into the dict
def encode_namedlist(values):
values = list(values)
if len(values) == 0:
return dict(positional=[])
positional = [val for key, val in values if not key]
return dict(
positional=positional, **{key: val for key, val in values if key}
)
snakemake = dict(
input=encode_namedlist(input_._plainstrings()._allitems()),
output=encode_namedlist(output._plainstrings()._allitems()),
params=encode_namedlist(params.items()),
wildcards=encode_namedlist(wildcards.items()),
threads=threads,
resources=encode_namedlist(
{
name: value
for (name, value) in resources.items()
if name != "_cores" and name != "_nodes"
}.items()
),
log=encode_namedlist(log._plainstrings()._allitems()),
config=encode_namedlist(config.items()),
rulename=rulename,
bench_iteration=bench_iteration,
scriptdir=path.get_basedir().get_path_or_uri(),
)
import json
json_string = json.dumps(dict(snakemake))
# Obtain search path for current snakemake module.
# We append it at the end (as a fallback).
searchpath = SNAKEMAKE_SEARCHPATH
if container_img is not None:
searchpath = singularity.SNAKEMAKE_MOUNTPOINT
searchpath = repr(searchpath)
# For local scripts, add their location to the path in case they use path-based imports
if is_local:
searchpath += ", " + repr(path.get_basedir().get_path_or_uri())
return textwrap.dedent(
"""
json_typegen::json_typegen!("Snakemake", r###"{json_string}"###, {{
"/bench_iteration": {{
"use_type": "Option<usize>"
}},
"/input/positional": {{
"use_type": "Vec<String>"
}},
"/output/positional": {{
"use_type": "Vec<String>"
}},
"/log/positional": {{
"use_type": "Vec<String>"
}},
"/wildcards/positional": {{
"use_type": "Vec<String>"
}},
}});
pub struct Iter<'a, T>(std::slice::Iter<'a, T>);
impl<'a, T> Iterator for Iter<'a, T> {{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {{
self.0.next()
}}
}}
macro_rules! impl_iter {{
($($s:ty),+) => {{
$(
impl IntoIterator for $s {{
type Item = String;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {{
self.positional.into_iter()
}}
}}
impl<'a> IntoIterator for &'a $s {{
type Item = &'a String;
type IntoIter = Iter<'a, String>;
fn into_iter(self) -> Self::IntoIter {{
Iter(self.positional.as_slice().into_iter())
}}
}}
)+