-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtouchpycli_batch.sh
More file actions
225 lines (186 loc) · 5.22 KB
/
touchpycli_batch.sh
File metadata and controls
225 lines (186 loc) · 5.22 KB
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
#!/usr/bin/bash
filename=$1
if [[ $# -eq 0 ]]; then
>&2 echo "Error: no arguments provided"
>&2 echo "USAGE: $(basename $0) [NEW_FILE_NAME]"
exit 1
fi
touch "${filename}.py"
chmod +x "${filename}.py"
template() {
cat <<'EOF'
#!/usr/bin/env python3
"""
BATCH Description
Input:
...
Output:
...
Purpose:
...
Prerequisites:
...
\033[1m\033[31mWARNING:\033[0m
...
"""
# TODO:
# - [ ]
from Bio import SeqIO
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import dataclass
from datetime import timedelta
from functools import partial
from itertools import combinations
from pathlib import Path
from typing import TextIO, NamedTuple
import argparse
import gzip
import logging
import numpy as np
import polars as pl
import shutil
import subprocess
import sys
import time
# =============================================================================
# Global config
# =============================================================================
# logger
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s -- %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger(__name__)
# =============================================================================
# CLI args
# =============================================================================
@dataclass
class Args:
indir: Path
outdir: Path
cpu: int
parallel: bool
def collect_args() -> Args:
"""Argument parser function"""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
# ===================================================
mainopts = parser.add_argument_group("Main options")
mainopts.add_argument(
"-i",
"--indir",
dest="indir",
type=Path,
metavar="DIR",
required=True,
help="Path to input directory base [Required]",
)
mainopts.add_argument(
"-o",
"--outdir",
type=Path,
required=False,
default=".",
metavar="DIR",
help="Output target directory [Optional][Default: cwd]",
)
# ===================================================
cpuopts = parser.add_argument_group("Parallel processing options")
cpuopts.add_argument(
"-C",
"--cpu",
type=int,
default=None,
metavar="CPU",
required=False,
help="Number of CPUs to use for parallelism [Default: max available]",
)
cpuopts.add_argument(
"-P",
"--parallel",
action="store_true",
help="Run script in parallel [Default: runs without parallel processing]",
)
# ===================================================
args = Args(**vars(parser.parse_args()))
return args
# =============================================================================
# Util
# =============================================================================
def open_gz(file: Path) -> TextIO:
"""Utility function: open file, even if it is gzipped"""
if file.suffix == ".gz":
return gzip.open(file, "rt")
else:
return open(file, "r")
# ==============================================================================
def collect_dirs(
base_dir: Path,
) -> list[Path]:
"""Glob for dirs
---
Args:
base_dir (Path): the base directory to search
Returns:
dirs (list[Path]): a list of all dirs
"""
# glob for all child directories in target dir
dirs = sorted([p for p in Path(base_dir).rglob("*") if p.is_dir()])
logger.info(f"Found {len(dirs)} child directories {base_dir}")
return dirs
# =============================================================================
# Core funcs.
# =============================================================================
def funca(
infile: Path,
args: Args,
) -> None:
"""Description
---
Args:
arg1 (dtype): description
Returns:
dtype: description
"""
# stuff
print("Hello world")
# =============================================================================
def main() -> None:
"""Workflow:
---
main
│
├── args
└── func
"""
t0 = time.perf_counter()
args = collect_args()
dirs = collect_dirs(base_dir=args.indir)
############### no parallel processing ##################
if not args.parallel:
for infile in infiles:
funca(infile=infile, outdir=args.outdir, args=args)
return
################# PARALLEL PROCESSING ###################
if args.parallel:
# make partial func
partial_funca = partial(
funca,
args=args,
)
# ProcessPoolExecutor
with ProcessPoolExecutor(max_workers=args.cpu) as exe:
list(exe.map(partial_funca, infiles))
################################################################
t1 = time.perf_counter()
readable_time = str(timedelta(seconds=int(t1 - t0)))
logger.info(f"FINISHED in {readable_time} h:m:s")
# =============================================================================
if __name__ == "__main__":
sys.exit(main())
EOF
}
template >"${filename}.py"