#!/usr/bin/env python3 # # ens_data.py --- Creating HYSPLIT Shapefiles # See HYSPLIT Tutorial Sec. 12.4 # # Change history: # 22 Dec 2025 (BB) - standard-aligned, cross-platform version # 18 Jun 2026 (SZ) - standardize code for run_cmd(), convert_html_to_img(), # etc. across Python scripts # - ensure encoding is specified when opening files import os import sys import platform from pathlib import Path import subprocess import webbrowser if sys.version_info < (3, 8): print("Please use Python 3.8 or higher.") sys.exit(1) system = platform.system().lower() if system == "windows": PGM = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("C:\\hysplit") OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else PGM / "working" DSP = sys.argv[3] if len(sys.argv) > 3 else "YES" TTR = Path(os.environ.get("TTR", "C:\\Tutorial")) exe_suffix = ".exe" else: PGM = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "hysplit" OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else PGM / "working" DSP = sys.argv[3] if len(sys.argv) > 3 else "YES" TTR = Path(os.environ.get("TTR", Path.home() / "tutorial")) exe_suffix = "" if not PGM.exists(): script = Path(__file__).name if "__file__" in globals() else "ens_data.py" print(f"ERROR: HYSPLIT not found at {PGM}") print(f""" Please specify the path to your HYSPLIT installation using a command-line argument: python {script} YOUR_HYSPLIT_DIRECTORY [OUT] [DSP (YES|NO)] Example: python {script} C:\\hysplit C:\\hysplit\\working YES """) sys.exit(1) if not TTR.exists(): print(f"ERROR: HYSPLIT tutorial not found at {TTR}") print(""" Please set the TTR environment variable to point to your HYSPLIT tutorial directory. For Windows users (Command Prompt): SET TTR=YOUR_HYSPLIT_TUTORIAL_DIRECTORY For Linux users (bash shell): export TTR='YOUR_HYSPLIT_TOTURIAL_DIRECTORY' For Linux users (csh or tcsh shell): setenv TTR 'YOUR_HYSPLIT_TOTURIAL_DIRECTORY'""") sys.exit(1) os.chdir(OUT) # ------------------------------------------------------------------ # Helper functions # ------------------------------------------------------------------ def run_cmd(cmd, desc="", allow_fail=False, stdout_file=None, append=False): if desc: print(f"{desc}...") exitcode = 0 with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as p: if stdout_file: mode="a" if append else "w" with open(stdout_file, mode, encoding="utf-8") as f_out: for ln in p.stdout: print(ln, end="") f_out.write(ln) else: with p.stdout as f: for ln in iter(f.readline, b'\n'): if len(ln) == 0: break print(ln.rstrip()) done = False while not done: try: exitcode = p.wait(timeout=1) done = True except subprocess.TimeoutExpired: print("WARN: subprocess timed out.") if exitcode != 0: if allow_fail: print(f"WARN: command failed with exit code {exitcode} -> {' '.join(cmd)}") else: print(f"ERROR: command failed with exit code {exitcode} -> {' '.join(cmd)}") sys.exit(1) def convert_html_to_img(html_file, img_name_frame_nums): # Split SVG into Linux-consistent naming: F00-sec71_001.svg, etc. temp_img_name = "temp" run_cmd([str(PGM / "exec" / f"splitsvg{exe_suffix}"), f"-i{html_file}", f"-o{temp_img_name}.svg"]) # Locate ImageMagick for cross-platform conversion if system == "windows": convert_exe = None imgk_dir = next( (k for k in os.environ.get('PATH', '').split(os.pathsep) if "ImageMagick" in k), None ) if imgk_dir: # Use magick.exe for ImageMagick 7.x and later. Use convert.exe for earlier versions. for cmd in ('magick', 'convert'): candidate = os.path.join(imgk_dir, f'{cmd}{exe_suffix}') if os.path.exists(candidate): convert_exe = candidate break else: convert_exe = "convert" if convert_exe: # Match Linux naming for DSP=NO mode exactly for img_name, frame_num in img_name_frame_nums: svg = Path(f"F{frame_num:02d}-{temp_img_name}.svg") run_cmd([convert_exe, str(svg), img_name]) print(f"Converted {svg} -> {img_name}") svg.unlink() else: print("ImageMagick not found — skipping .svg conversion") def make_plot(html_name, exe_name, args, img_name_frame_nums): """Generic HYSPLIT plot routine with DSP=NO fallback.""" html_path = OUT / html_name if html_path.exists(): html_path.unlink() exe = PGM / "exec" / f"{exe_name}{exe_suffix}" run_cmd([str(exe)] + args, desc=f"Create {html_name}") if DSP.upper() == "YES": webbrowser.open(html_path.as_uri()) input("Press Enter to continue ...") else: convert_html_to_img(html_name, img_name_frame_nums) # ------------------------------------------------------------------ # Script configuration (lowercase required) # ------------------------------------------------------------------ inp = "hysplit2" syr, smo, sda, shr = 83, 9, 25, 17 lat, lon, lvl = 39.90, -84.22, 10.0 run_hours = 68 top = 10000.0 # ✅ ONLY FIX IS HERE met = TTR / "captex" meas = met / "captex2_meas.txt" met_files = { "001": "captex2_wrf27uw.bin", "002": "captex2_era40.bin", "003": "captex2_narr.bin", "004": "captex2_wrf27.bin", "005": "captex2_wrf09.bin", } def write_ascdata(): asc = OUT / "ASCDATA.CFG" if asc.exists(): asc.unlink() with asc.open("w", encoding="ascii") as f: f.write("-90.0 -180.0\n") f.write("1.0 1.0\n") f.write("180 360\n") f.write("2\n") f.write("0.2\n") f.write(f"'{PGM / 'bdyfiles'}{os.sep}' directory of files\n") def write_setup(): setup = OUT / "SETUP.CFG" if setup.exists(): setup.unlink() with setup.open("w", encoding="ascii") as f: f.write("&SETUP\n") f.write(" numpar = 10000,\n") f.write(" maxpar = 100000,\n") f.write("/\n") control2 = ( "1\n" "PMCH\n" "67000.0\n" "3.0\n" "00 00 00 00 00\n" "1\n" "42.0 -78.0\n" "0.25 0.25\n" "15.0 25.0\n" f".{os.sep}\n" f"{inp}\n" "1\n" "100\n" "83 09 25 18 00\n" "83 09 28 15 00\n" "00 03 00\n" "1\n" "0.0 0.0 0.0\n" "0.0 0.0 0.0 0.0 0.0\n" "0.0 0.0 0.0\n" "0.0\n" "0.0\n" ) def run_ensemble(): for key, metfile in met_files.items(): with open("CONTROL", "w", encoding="ascii") as f: f.write(f"{syr:02d} {smo:02d} {sda:02d} {shr:02d}\n") f.write("1\n") f.write(f"{lat:.2f} {lon:.2f} {lvl:.1f}\n") f.write(f"{run_hours}\n") f.write("0\n") f.write(f"{top:.1f}\n") f.write("1\n") f.write(f"{met}{os.sep}\n") f.write(f"{metfile}\n") f.write(control2) run_cmd([str(PGM / "exec" / f"hycs_std{exe_suffix}")]) run_cmd([ str(PGM / "exec" / f"c2datem{exe_suffix}"), "-xi", f"-i{inp}", "-ohysplit.txt", "-c1.0E+12", f"-m{meas}" ]) run_cmd([ str(PGM / "exec" / f"statmain{exe_suffix}"), "-t0", "-rhysplit.txt", f"-d{meas}", "-l10.0", "-o1" ]) Path("statA.txt").rename(f"statA_{key}.txt") Path(inp).rename(f"{inp}.{key}") def main(): write_ascdata() write_setup() run_ensemble() run_cmd([ str(PGM / "exec" / f"conprob{exe_suffix}"), f"-b{inp}", "-t1", "-p1", "-z1" ]) Path("LABELS.CFG").write_text("'TITLE&','### ens_data.py ### &'\n", encoding="ascii") make_plot("boxplots.html", "boxplots", ["+g1", "-x-78.80", "-y42.25"], [("edata006.png", 1)]) make_plot("ensplots.html", "ensplots", ["+g1", f"-b{inp}", "-x-78.80", "-y42.25"], [("edata007.png", 1)]) run_cmd([ str(PGM / "exec" / f"c2datem{exe_suffix}"), "-xi", "-icmean", "-ohysplit.txt", "-c1.0E+12", f"-m{meas}" ]) run_cmd([ str(PGM / "exec" / f"statmain{exe_suffix}"), "-t0", "-rhysplit.txt", f"-d{meas}", "-l10.0", "-o1" ]) make_plot("scatter.html", "scatter", ["+g1", "-idataA.txt", "-p10.0"], [("edata009.png", 1)]) Path("statA.txt").rename("statA_cmean.txt") stat_file = OUT / "statA_cmean.txt" if stat_file.exists(): print(stat_file.read_text(encoding="ascii", errors="replace")) if __name__ == "__main__": main()