1
Fork 0
internship/swash/processing/swash.py

67 lines
1.8 KiB
Python
Raw Normal View History

2022-03-03 11:49:59 +01:00
import logging
2022-03-03 12:59:49 +01:00
import os
2022-03-03 11:49:59 +01:00
import sys
import argparse
2022-03-02 14:41:27 +01:00
import pathlib
import subprocess
import configparser
import shutil
import tempfile
2022-03-03 11:49:59 +01:00
parser = argparse.ArgumentParser(description="Run swash model")
parser.add_argument("-v", "--verbose", action="count", default=0)
args = parser.parse_args()
logging.basicConfig(level=max((10, 20 - 10 * args.verbose)))
log = logging.getLogger("swash")
log.info("Starting swash model")
2022-03-02 14:41:27 +01:00
config = configparser.ConfigParser()
config.read("config.ini")
inp = pathlib.Path(config.get("swash", "input"))
out = pathlib.Path(config.get("swash", "out"))
2022-03-03 11:49:59 +01:00
if out.exists():
log.error(f"Swash output '{out}' already exists")
sys.exit(1)
2022-03-02 14:41:27 +01:00
with tempfile.TemporaryDirectory(prefix="swash_", dir=".") as tmp_raw:
2022-03-02 14:41:27 +01:00
tmpdir = pathlib.Path(tmp_raw)
2022-03-03 11:49:59 +01:00
log.info(f"Copying files to '{tmpdir}'")
2022-03-02 14:41:27 +01:00
shutil.copy2(inp, tmpdir)
2022-03-03 12:59:49 +01:00
shutil.copytree(
pathlib.Path(config.get("data", "out")), tmpdir, dirs_exist_ok=True
)
2022-03-03 12:18:46 +01:00
if config.has_option("swash", "mpi"):
mpi = ("-mpi", config.get("swash", "mpi"))
log.info(f"Using mpi with {mpi}")
else:
mpi = ()
2022-03-03 11:49:59 +01:00
with open(tmpdir.joinpath("sws.log"), "w") as logfile:
log.info(f"Runing swash in '{tmpdir}'")
2022-03-03 12:54:56 +01:00
path = pathlib.Path(config.get("swash", "path"))
2022-03-03 12:18:46 +01:00
2022-03-03 12:55:41 +01:00
cmd = (path.joinpath("swashrun"), "-input", inp.name, *mpi)
2022-03-03 12:18:46 +01:00
log.info(f"Running {cmd}")
2022-03-03 12:28:29 +01:00
swash_run = subprocess.Popen(
2022-03-03 12:59:49 +01:00
cmd,
cwd=tmpdir,
stdout=logfile,
stderr=logfile,
env={"PATH": f"{path}:{os.environ['PATH']}"},
2022-03-03 11:49:59 +01:00
)
2022-03-02 14:41:27 +01:00
2022-03-03 12:28:29 +01:00
code = swash_run.wait()
2022-03-03 12:35:29 +01:00
if code != 0:
2022-03-03 12:27:47 +01:00
log.error(f"Swash returned error code {code}")
2022-03-03 11:49:59 +01:00
log.info(f"Moving swash output to '{out}'")
shutil.move(tmpdir, out)
2022-03-03 11:49:59 +01:00
log.info(f"Swash model finished successfully")