Skip to content

Commit

Permalink
return empty Dataset on error rather than ValueError
Browse files Browse the repository at this point in the history
  • Loading branch information
scivision committed Dec 19, 2024
1 parent 54ac9c1 commit 6828e8e
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 83 deletions.
3 changes: 0 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ plot = [
"pymap3d"
]

[project.scripts]
msise00 = "msise00.__main__:cli"


[tool.black]
line-length = 100
Expand Down
2 changes: 1 addition & 1 deletion src/msise00/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .base import run, rungtd1d
from .timeutils import todatetime, todt64

__version__ = "1.10.1"
__version__ = "1.11.0"
113 changes: 56 additions & 57 deletions src/msise00/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,64 +16,63 @@
from .worldgrid import latlonworldgrid


def cli():
p = ArgumentParser(description="calls MSISE-00 from Python, save to NetCDF4 and/or plot")
p.add_argument("-t", "--time", help="time or times", nargs="+", required=True)
p.add_argument(
"-a",
"--altkm",
help="altitude (km). scalar, or (start,stop,step) or list of alts.",
type=float,
nargs="+",
required=True,
)
p.add_argument(
"-c",
"--latlon",
help="geodetic latitude/longitude (deg)",
metavar=("lat", "lon"),
type=float,
nargs=2,
)
p.add_argument("-o", "--odir", help="directory to write plots to")
p.add_argument("-w", help="NetCDF4 .nc filename to write")
p.add_argument(
"-gs", help="geographic grid spacing (lat, lon)", nargs=2, type=float, default=(10, 10)
)
p.add_argument("-q", "--quiet", help="disable plotting", action="store_true")
P = p.parse_args()
p = ArgumentParser(description="calls MSISE-00 from Python, save to NetCDF4 and/or plot")
p.add_argument("-t", "--time", help="time or times", nargs="+", required=True)
p.add_argument(
"-a",
"--altkm",
help="altitude (km). scalar, or (start,stop,step) or list of alts.",
type=float,
nargs="+",
required=True,
)
p.add_argument(
"-c",
"--latlon",
help="geodetic latitude/longitude (deg)",
metavar=("lat", "lon"),
type=float,
nargs=2,
)
p.add_argument("-o", "--odir", help="directory to write plots to")
p.add_argument("-w", help="NetCDF4 .nc filename to write")
p.add_argument(
"-gs", help="geographic grid spacing (lat, lon)", nargs=2, type=float, default=(10, 10)
)
p.add_argument("-q", "--quiet", help="disable plotting", action="store_true")
P = p.parse_args()

# %% altitude
if len(P.altkm) == 1:
altkm = P.altkm[0]
elif len(P.altkm) == 3:
altkm = np.arange(*P.altkm)
else:
altkm = P.altkm
# %% latlon
if P.latlon is not None:
glat, glon = P.latlon
else:
glat, glon = latlonworldgrid(*P.gs)
# %% run
atmos = run(P.time, altkm, glat, glon)
# %% save
if P.w:
ncfn = Path(P.w).expanduser()
print("saving", ncfn)
# NOTE: .squeeze() avoids ValueError: unsupported dtype for netCDF4 variable: datetime64[ns]
atmos.squeeze().to_netcdf(ncfn)
# %% plot
if not P.quiet:
try:
from matplotlib.pyplot import show
from .plots import plotgtd
# %% altitude
if len(P.altkm) == 1:
altkm = P.altkm[0]
elif len(P.altkm) == 3:
altkm = np.arange(*P.altkm)
else:
altkm = P.altkm
# %% latlon
if P.latlon is not None:
glat, glon = P.latlon
else:
glat, glon = latlonworldgrid(*P.gs)
# %% run
atmos = run(P.time, altkm, glat, glon)

plotgtd(atmos, P.odir)
show()
except ImportError:
print("skipped plotting")
if not atmos:
raise ValueError(f"no/bad data for {P.time} alt: {altkm} km coord:{glat} {glon}")

# %% save
if P.w:
ncfn = Path(P.w).expanduser()
print("saving", ncfn)
# NOTE: .squeeze() avoids ValueError: unsupported dtype for netCDF4 variable: datetime64[ns]
atmos.squeeze().to_netcdf(ncfn)
# %% plot
if not P.quiet:
try:
from matplotlib.pyplot import show
from .plots import plotgtd

if __name__ == "__main__":
cli()
plotgtd(atmos, P.odir)
show()
except ImportError:
print("skipped plotting")
24 changes: 5 additions & 19 deletions src/msise00/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,28 +140,11 @@ def rungtd1d(
if os.name == "nt":
exe_name += ".exe"

# check inputs for error, especially unavailable indices
if not np.isfinite(glat).all():
raise ValueError("glat is not finite.")

if not np.isfinite(glon).all():
raise ValueError("glon is not finite.")

f107s = indices["f107s"]
if not np.isfinite(f107s):
raise ValueError("f107s is not finite.")

f107s = indices["f107s"]
if not np.isfinite(f107s):
raise ValueError("f107s is not finite.")

f107 = indices["f107"]
if not np.isfinite(f107):
raise ValueError("f107 is not finite.")

Ap = indices["Ap"]
if not np.isfinite(Ap):
raise ValueError("Ap is not finite.")

exe = importlib.resources.files(__package__) / exe_name
if not exe.is_file():
Expand All @@ -184,10 +167,13 @@ def rungtd1d(

logging.info(" ".join(cmd))

ret = subprocess.check_output(cmd, text=True)
ret = subprocess.run(cmd, capture_output=True, text=True)
if ret.returncode != 0:
logging.error(ret.stderr)
return xarray.Dataset()

# different compilers throw in extra \n
raw = list(map(float, ret.split()))
raw = list(map(float, ret.stdout.split()))
if not len(raw) == 9 + 2:
raise ValueError(ret)
dens[i, :] = raw[:9]
Expand Down
3 changes: 2 additions & 1 deletion src/msise00/tests/test_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import subprocess
import pytest
import sys
import xarray
import xarray.testing
import importlib.resources
Expand Down Expand Up @@ -39,7 +40,7 @@ def test_script(tmp_path):
ref = xarray.open_dataset(fn)

fn = tmp_path / "test.nc"
cmd = ["msise00", "-q", "-w", str(fn), "-a", str(altkm), "-t", time, "-gs", "30", "60"]
cmd = [sys.executable, "-m", "msise00", "-q", "-w", str(fn), "-a", str(altkm), "-t", time, "-gs", "30", "60"]
print(" ".join(cmd))
subprocess.check_call(cmd)

Expand Down
3 changes: 2 additions & 1 deletion src/msise00/tests/test_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import importlib.resources
import subprocess
import pytest
import sys
import xarray
import xarray.testing
import msise00
Expand Down Expand Up @@ -40,7 +41,7 @@ def test_script(altkm, reffn, tmp_path):
ref = xarray.open_dataset(fn)

fn = tmp_path / "test.nc"
cmd = ["msise00", "-q", "-w", str(fn), "-a", str(altkm), "-t", time, "-c", str(lat), str(lon)]
cmd = [sys.executable, "-m", "msise00", "-q", "-w", str(fn), "-a", str(altkm), "-t", time, "-c", str(lat), str(lon)]
print(" ".join(cmd))
subprocess.check_call(cmd)

Expand Down
3 changes: 2 additions & 1 deletion src/msise00/tests/test_time_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import importlib.resources
import subprocess
import pytest
import sys
import xarray
import xarray.testing
import msise00
Expand Down Expand Up @@ -38,7 +39,7 @@ def test_script(tmp_path):
ref = xarray.open_dataset(fn)

fn = tmp_path / "test.nc"
cmd = ["msise00", "-q", "-w", str(fn), "-gs", "90", "90", "-a", str(altkm), "-t"] + time
cmd = [sys.executable, "-m", "msise00", "-q", "-w", str(fn), "-gs", "90", "90", "-a", str(altkm), "-t"] + time
print(" ".join(cmd))
subprocess.check_call(cmd)

Expand Down

0 comments on commit 6828e8e

Please sign in to comment.