Repository navigation
Expand file tree
/
Copy pathproject.py
More file actions
215 lines (170 loc) · 8.29 KB
/
Copy pathproject.py
File metadata and controls
215 lines (170 loc) · 8.29 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
# SPDX-FileCopyrightText: 2026 canoP authors
#
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""signac-flow project of a canoP campaign, copied into the campaign by canoP studio.
Each signac job of this project is a run; its directory holds its ini. The launch settings
(executable, environment, Slurm lines, processes, threads) are in the project document, key
"launch", written by the studio at each submission. A run may have its own execution settings
(nprocs, omp_threads, nodes, time, partition): those of its job document, key "launch" (set in the
Run tab of the studio), take precedence over those of its state point, key "launch" (launch.* of
the sweep), and both replace those of the project document for that run.
With the Python of canoP studio (<canoP>/.local/canop-studio/venv/bin/python):
python project.py status state of the operations of each run
python project.py submit -o run submit the runs not done yet to Slurm
python project.py run -o metrics compute the metrics of the finished runs
python project.py exec run <job id> run one run here, in the foreground
The campaign is a git repository with its own physics (physics/). canoP runs the physics copied into
the run directory (canoP_physics/, CANOP_PHYSICS_DIR of the launch settings) from the physics commit
of the submission (key "physics" of the launch settings). The studio copies it when it submits; the
operation "run" copies it when it is missing (a submission made without the studio).
Operations:
run canoP in the run directory (done when <prefix>_main.xmf is complete)
metrics scalars of a finished run in job.doc["metrics"]: final time, number
of outputs, Mcell-updates/s, last values of the *.npy diagnostics
"""
import glob
import os
import re
import shlex
from flow import FlowProject
class Campaign(FlowProject):
pass
def _launch(job):
"""Launch settings of the project document, written by the studio at each submission."""
return job.project.doc.get("launch", {})
def _ini(job):
"""Path of the ini of the run, or None."""
inis = sorted(glob.glob(os.path.join(glob.escape(job.path), "*.ini")))
return inis[0] if inis else None
def _ini_get(text, section, key, default=""):
"""Value of section.key in the ini text (the last one if repeated), or `default`."""
current, value = None, default
for line in text.splitlines():
line = line.split("#", 1)[0].strip()
m = re.match(r"^\[(.+)\]$", line)
if m:
current = m.group(1).strip().lower()
elif "=" in line and current == section.lower():
k, v = line.split("=", 1)
if k.strip().lower() == key.lower():
value = v.strip()
return value
def _outputs(job):
"""Return (output prefix, output directory) of the run."""
ini = _ini(job)
text = ""
if ini:
with open(ini, encoding="utf-8", errors="replace") as fd:
text = fd.read()
out_dir = os.path.normpath(os.path.join(job.path, _ini_get(text, "output", "outputDir", "./") or "./"))
# io.output_prefix ("output" by default); output.outputPrefix in runs of earlier canoP versions
names = [n for n in (_ini_get(text, "io", "output_prefix"), _ini_get(text, "output", "outputPrefix"), "output")
if n]
for name in names:
if glob.glob(os.path.join(glob.escape(out_dir), glob.escape(name) + "_*.xmf")):
return name, out_dir
return names[0], out_dir
def has_ini(job):
"""Condition: the run directory holds an ini."""
return _ini(job) is not None
def finished(job):
"""Condition: the file <prefix>_main.xmf of the run is complete (it ends with </Xdmf>)."""
prefix, out = _outputs(job)
main = os.path.join(out, prefix + "_main.xmf")
try:
with open(main, "rb") as fd:
fd.seek(0, os.SEEK_END)
fd.seek(max(0, fd.tell() - 256))
return b"</Xdmf>" in fd.read()
except OSError:
return False
def has_metrics(job):
"""Condition: the metrics of the run are in its job document."""
return "metrics" in job.doc
def _own(job):
"""Execution settings of this run: those of its job document over those of its state point."""
sp = job.sp().get("launch", {})
own = dict(sp) if isinstance(sp, dict) else {}
doc = job.doc.get("launch")
if doc:
own.update({k: v for k, v in doc().items() if v not in (None, "")})
return own
def _setting(job, key, default=None):
"""Setting `key` of this run, else of the project document, else `default`."""
return _own(job).get(key, _launch(job).get(key, default))
def _np(job):
"""Number of MPI processes of the run."""
return int(_setting(job, "nprocs", 1) or 1)
def _threads(job):
"""OpenMP threads per process of the run (0: not set)."""
return int(_setting(job, "omp_threads", 0) or 0)
def _nodes(job):
return _own(job).get("nodes") # else the #SBATCH lines of the studio
def _time(job):
"""Slurm time limit of the run, or None."""
return _own(job).get("time")
def _partition(job):
"""Slurm partition of the run, or None."""
return _own(job).get("partition")
def _gpus(job):
"""GPUs per process (per node with --gres) for a GPU build, else 0."""
return int(_setting(job, "gpus_per_task", 1) or 1) if _launch(job).get("gpu") else 0
@Campaign.pre(has_ini)
@Campaign.post(finished)
# custom directive names: flow rewrites its own "np" (np = 1 with threads becomes the number of threads)
@Campaign.operation(cmd=True, directives={"canop_ntasks": _np, "canop_threads": _threads, "canop_nodes": _nodes,
"canop_time": _time, "canop_partition": _partition, "canop_gpus": _gpus})
def run(job):
"""Shell command of the run: canoP with srun in the run directory, its output in canoP.log."""
launch = _launch(job)
exe = launch.get("executable")
if not exe:
raise RuntimeError("no launch settings in the project document: submit once from canoP studio")
ini = os.path.basename(_ini(job))
cmd = "%s --ini %s %s" % (shlex.quote(exe), shlex.quote(ini), launch.get("extra_args", ""))
threads = _threads(job)
opts = " -c %d" % threads if threads > 0 else ""
if _gpus(job) and launch.get("gpu_request", "gpus-per-task") == "gpus-per-task":
opts += " --gpus-per-task=%d --gpu-bind=closest" % _gpus(job)
cmd = "srun -n %d%s %s" % (_np(job), opts, cmd.strip())
env = "export OMP_NUM_THREADS=%d OMP_PROC_BIND=spread OMP_PLACES=threads && " % threads if threads > 0 else ""
# extract the physics of the submission's commit when the studio has not copied it into the run
physics = ""
if launch.get("physics"):
physics = ("{ test -f canoP_physics/__init__.py || { mkdir -p canoP_physics && git -C %s archive %s physics "
"| tar -x -C canoP_physics --strip-components=1; }; } && " % (
shlex.quote(job.project.path), shlex.quote(launch["physics"])))
return "cd %s && echo ${SLURM_JOB_ID:-} > canoP_job.id && %s%s%s > canoP.log 2>&1" % (
shlex.quote(job.path), physics, env, cmd)
@Campaign.pre(finished)
@Campaign.post(has_metrics)
@Campaign.operation
def metrics(job):
"""Store the scalars of a finished run in job.doc["metrics"]."""
prefix, out = _outputs(job)
steps = sorted(glob.glob(os.path.join(glob.escape(out), glob.escape(prefix) + "_iter*.xmf")))
result = {"n_outputs": len(steps)}
if steps:
with open(steps[-1], "rb") as fd:
m = re.search(rb'<Time[^>]*Value="([^"]+)"', fd.read(4096))
if m:
result["t_final"] = float(m.group(1))
try:
with open(os.path.join(job.path, "canoP.log"), encoding="utf-8", errors="replace") as fd:
log = fd.read()
m = re.findall(r"Mcell-updates/s\s*:\s*([0-9.eE+-]+)", log)
if m:
result["mcups"] = float(m[-1])
except OSError:
pass
try:
import numpy as np
for f in sorted(glob.glob(os.path.join(glob.escape(out), "*.npy"))):
values = np.atleast_1d(np.load(f))
name = os.path.basename(f)[:-4].replace(prefix + "_", "", 1)
result[name] = [float(v) for v in np.ravel(values[-1:] if values.ndim == 1 else values[-1])[:10]]
except Exception:
pass
job.doc["metrics"] = result
if __name__ == "__main__":
Campaign().main()