Skip to content

Commit

Permalink
Merge branch 'main' into to_numpy/pandas_numeric
Browse files Browse the repository at this point in the history
  • Loading branch information
seisman authored Nov 30, 2024
2 parents bb1cb07 + dff8e77 commit 949274d
Show file tree
Hide file tree
Showing 44 changed files with 157 additions and 112 deletions.
2 changes: 1 addition & 1 deletion environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ dependencies:
# Dev dependencies (style checks)
- codespell
- pre-commit
- ruff>=0.3.0
- ruff>=0.8.0
# Dev dependencies (unit testing)
- matplotlib-base
- pytest>=6.0
Expand Down
6 changes: 4 additions & 2 deletions pygmt/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,11 @@ def registration(self):
@registration.setter
def registration(self, value):
if value not in {0, 1}:
raise GMTInvalidInput(
msg = (
f"Invalid grid registration value: {value}, should be either "
"0 for Gridline registration or 1 for Pixel registration."
)
raise GMTInvalidInput(msg)
self._registration = value

@property
Expand All @@ -154,8 +155,9 @@ def gtype(self):
@gtype.setter
def gtype(self, value):
if value not in {0, 1}:
raise GMTInvalidInput(
msg = (
f"Invalid coordinate system type: {value}, should be "
"either 0 for Cartesian or 1 for Geographic."
)
raise GMTInvalidInput(msg)
self._gtype = value
3 changes: 2 additions & 1 deletion pygmt/clib/loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ def clib_names(os_name: str) -> list[str]:
case "win32": # Windows
libnames = ["gmt.dll", "gmt_w64.dll", "gmt_w32.dll"]
case _:
raise GMTOSError(f"Operating system '{os_name}' is not supported.")
msg = f"Operating system '{os_name}' is not supported."
raise GMTOSError(msg)
return libnames


Expand Down
26 changes: 16 additions & 10 deletions pygmt/clib/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ def session_pointer(self) -> ctp.c_void_p:
the context manager).
"""
if getattr(self, "_session_pointer", None) is None:
raise GMTCLibNoSessionError("No currently open GMT API session.")
msg = "No currently open GMT API session."
raise GMTCLibNoSessionError(msg)
return self._session_pointer

@session_pointer.setter
Expand Down Expand Up @@ -276,7 +277,8 @@ def get_enum(self, name: str) -> int:
session = None
value = c_get_enum(session, name.encode())
if value is None or value == -99999:
raise GMTCLibError(f"Constant '{name}' doesn't exist in libgmt.")
msg = f"Constant '{name}' doesn't exist in libgmt."
raise GMTCLibError(msg)
return value

def get_libgmt_func(
Expand Down Expand Up @@ -558,7 +560,8 @@ def get_common(self, option: str) -> bool | int | float | np.ndarray:
pygmt.exceptions.GMTInvalidInput: Unknown GMT common option flag 'A'.
"""
if option not in "BIJRUVXYabfghinoprst:":
raise GMTInvalidInput(f"Unknown GMT common option flag '{option}'.")
msg = f"Unknown GMT common option flag '{option}'."
raise GMTInvalidInput(msg)

c_get_common = self.get_libgmt_func(
"GMT_Get_Common",
Expand Down Expand Up @@ -1194,7 +1197,8 @@ def read_data(
data,
)
if data_ptr is None:
raise GMTCLibError(f"Failed to read dataset from '{infile}'.")
msg = f"Failed to read dataset from '{infile}'."
raise GMTCLibError(msg)
return ctp.cast(data_ptr, ctp.POINTER(dtype))

def write_data(self, family, geometry, mode, wesn, output, data):
Expand Down Expand Up @@ -1264,7 +1268,8 @@ def write_data(self, family, geometry, mode, wesn, output, data):
data,
)
if status != 0:
raise GMTCLibError(f"Failed to write dataset to '{output}'")
msg = f"Failed to write dataset to '{output}'."
raise GMTCLibError(msg)

@contextlib.contextmanager
def open_virtualfile(
Expand Down Expand Up @@ -1856,9 +1861,8 @@ def virtualfile_in(
elif check_kind == "vector":
valid_kinds += ("empty", "matrix", "vectors", "geojson")
if kind not in valid_kinds:
raise GMTInvalidInput(
f"Unrecognized data type for {check_kind}: {type(data)}"
)
msg = f"Unrecognized data type for {check_kind}: {type(data)}."
raise GMTInvalidInput(msg)

# Decide which virtualfile_from_ function to use
_virtualfile_from = {
Expand Down Expand Up @@ -2110,7 +2114,8 @@ def read_virtualfile(
if kind is None: # Return the ctypes void pointer
return pointer
if kind == "cube":
raise NotImplementedError(f"kind={kind} is not supported yet.")
msg = f"kind={kind} is not supported yet."
raise NotImplementedError(msg)
dtype = {"dataset": _GMT_DATASET, "grid": _GMT_GRID, "image": _GMT_IMAGE}[kind]
return ctp.cast(pointer, ctp.POINTER(dtype))

Expand Down Expand Up @@ -2378,5 +2383,6 @@ def extract_region(self) -> np.ndarray:
region.ctypes.data_as(ctp.POINTER(ctp.c_double)),
)
if status != 0:
raise GMTCLibError("Failed to extract region from current figure.")
msg = "Failed to extract region from current figure."
raise GMTCLibError(msg)
return region
3 changes: 2 additions & 1 deletion pygmt/datasets/earth_magnetic_anomaly.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,11 @@ def load_earth_magnetic_anomaly(
"wdmam": "earth_wdmam",
}.get(data_source)
if prefix is None:
raise GMTInvalidInput(
msg = (
f"Invalid earth magnetic anomaly data source '{data_source}'. "
"Valid values are 'emag2', 'emag2_4km', and 'wdmam'."
)
raise GMTInvalidInput(msg)
grid = _load_remote_dataset(
name="earth_wdmam" if data_source == "wdmam" else "earth_mag",
prefix=prefix,
Expand Down
10 changes: 6 additions & 4 deletions pygmt/datasets/earth_relief.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,17 +155,19 @@ def load_earth_relief(
"synbath": "earth_synbath",
}.get(data_source)
if prefix is None:
raise GMTInvalidInput(
msg = (
f"Invalid earth relief data source '{data_source}'. "
"Valid values are 'igpp', 'gebco', 'gebcosi', and 'synbath'."
)
raise GMTInvalidInput(msg)
# Use SRTM or not.
if use_srtm and resolution in land_only_srtm_resolutions:
if data_source != "igpp":
raise GMTInvalidInput(
f"Option 'use_srtm=True' doesn't work with data source '{data_source}'."
" Please set 'data_source' to 'igpp'."
msg = (
f"Option 'use_srtm=True' doesn't work with data source '{data_source}'. "
"Please set 'data_source' to 'igpp'."
)
raise GMTInvalidInput(msg)
prefix = "srtm_relief"
# Choose earth relief dataset
match data_source:
Expand Down
3 changes: 2 additions & 1 deletion pygmt/datasets/samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,5 +347,6 @@ def load_sample_data(
>>> data = load_sample_data("bathymetry")
""" # noqa: W505
if name not in datasets:
raise GMTInvalidInput(f"Invalid dataset name '{name}'.")
msg = f"Invalid dataset name '{name}'."
raise GMTInvalidInput(msg)
return datasets[name].func()
13 changes: 6 additions & 7 deletions pygmt/helpers/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,10 +569,11 @@ def new_module(*args, **kwargs):
"""
for short_param, long_alias in aliases.items():
if long_alias in kwargs and short_param in kwargs:
raise GMTInvalidInput(
msg = (
f"Parameters in short-form ({short_param}) and "
f"long-form ({long_alias}) can't coexist."
)
raise GMTInvalidInput(msg)
if long_alias in kwargs:
kwargs[short_param] = kwargs.pop(long_alias)
elif short_param in kwargs:
Expand Down Expand Up @@ -721,9 +722,8 @@ def kwargs_to_strings(**conversions):

for arg, fmt in conversions.items():
if fmt not in separators:
raise GMTInvalidInput(
f"Invalid conversion type '{fmt}' for argument '{arg}'."
)
msg = f"Invalid conversion type '{fmt}' for argument '{arg}'."
raise GMTInvalidInput(msg)

# Make the actual decorator function
def converter(module_func):
Expand Down Expand Up @@ -837,9 +837,8 @@ def new_module(*args, **kwargs):
"""
if oldname in kwargs:
if newname in kwargs:
raise GMTInvalidInput(
f"Can't provide both '{newname}' and '{oldname}'."
)
msg = f"Can't provide both '{newname}' and '{oldname}'."
raise GMTInvalidInput(msg)
msg = (
f"The '{oldname}' parameter has been deprecated since {deprecate_version}"
f" and will be removed in {remove_version}."
Expand Down
5 changes: 3 additions & 2 deletions pygmt/helpers/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,11 @@ def tempfile_from_image(image):
try:
image.rio.to_raster(raster_path=tmpfile.name)
except AttributeError as e: # object has no attribute 'rio'
raise ImportError(
msg = (
"Package `rioxarray` is required to be installed to use this function. "
"Please use `python -m pip install rioxarray` or "
"`mamba install -c conda-forge rioxarray` "
"to install the package."
) from e
)
raise ImportError(msg) from e
yield tmpfile.name
3 changes: 2 additions & 1 deletion pygmt/helpers/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,12 @@ def wrapper(*args, ext="png", request=None, **kwargs):
else: # Images are not the same
for key in ["actual", "expected", "diff"]:
err[key] = Path(err[key]).relative_to(".")
raise GMTImageComparisonFailure(
msg = (
f"images not close (RMS {err['rms']:.3f}):\n"
f"\t{err['actual']}\n"
f"\t{err['expected']}"
)
raise GMTImageComparisonFailure(msg)
finally:
del fig_ref
del fig_test
Expand Down
6 changes: 4 additions & 2 deletions pygmt/helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,8 @@ def build_arg_list( # noqa: PLR0912
gmt_args = []
for key, value in kwdict.items():
if len(key) > 2: # Raise an exception for unrecognized options
raise GMTInvalidInput(f"Unrecognized parameter '{key}'.")
msg = f"Unrecognized parameter '{key}'."
raise GMTInvalidInput(msg)
if value is None or value is False: # Exclude arguments that are None or False
pass
elif value is True:
Expand Down Expand Up @@ -509,7 +510,8 @@ def build_arg_list( # noqa: PLR0912
or str(outfile) in {"", ".", ".."}
or str(outfile).endswith(("/", "\\"))
):
raise GMTInvalidInput(f"Invalid output file name '{outfile}'.")
msg = f"Invalid output file name '{outfile}'."
raise GMTInvalidInput(msg)
gmt_args.append(f"->{outfile}")
return gmt_args

Expand Down
8 changes: 4 additions & 4 deletions pygmt/helpers/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ def validate_output_table_type(
'file'
"""
if output_type not in {"file", "numpy", "pandas"}:
raise GMTInvalidInput(
"Must specify 'output_type' either as 'file', 'numpy', or 'pandas'."
)
msg = "Must specify 'output_type' either as 'file', 'numpy', or 'pandas'."
raise GMTInvalidInput(msg)
if output_type == "file" and outfile is None:
raise GMTInvalidInput("Must specify 'outfile' for output_type='file'.")
msg = "Must specify 'outfile' for output_type='file'."
raise GMTInvalidInput(msg)
if output_type != "file" and outfile is not None:
msg = (
f"Changing 'output_type' from '{output_type}' to 'file' "
Expand Down
3 changes: 2 additions & 1 deletion pygmt/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ def load_dataarray(filename_or_obj, **kwargs):
xarray.open_dataarray
"""
if "cache" in kwargs:
raise TypeError("cache has no effect in this context")
msg = "'cache' has no effect in this context."
raise TypeError(msg)

with xr.open_dataarray(filename_or_obj, **kwargs) as dataarray:
result = dataarray.load()
Expand Down
12 changes: 5 additions & 7 deletions pygmt/session_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,23 @@ def begin():
Only meant to be used once for creating the global session.
"""
# On Windows, need to set GMT_SESSION_NAME to a unique value
# On Windows, need to set GMT_SESSION_NAME to a unique value.
if sys.platform == "win32":
os.environ["GMT_SESSION_NAME"] = unique_name()

prefix = "pygmt-session"
with Session() as lib:
lib.call_module(module="begin", args=[prefix])
# pygmt relies on GMT modern mode with GMT_COMPATIBILITY at version 6
# PyGMT relies on GMT modern mode with GMT_COMPATIBILITY at version 6.
lib.call_module(module="set", args=["GMT_COMPATIBILITY=6"])


def end():
"""
Terminate GMT modern mode session and optionally produce the figure files.
Terminate the GMT modern mode session created by :func:`pygmt.begin`.
Called after :func:`pygmt.begin` and all commands that you want included in
a session. Will finalize any PostScript plots that were made in the
background, convert them to the desired format (specified in
``pygmt.begin``), and bring the figures to the working directory.
Called after :func:`pygmt.begin` and all commands that you want included in a
session. Will clean up the session directory completely.
"""
with Session() as lib:
lib.call_module(module="end", args=[])
7 changes: 4 additions & 3 deletions pygmt/src/coast.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,10 @@ def coast(self, **kwargs):
"""
kwargs = self._preprocess(**kwargs)
if not args_in_kwargs(args=["C", "G", "S", "I", "N", "E", "Q", "W"], kwargs=kwargs):
raise GMTInvalidInput(
"""At least one of the following parameters must be specified:
lakes, land, water, rivers, borders, dcw, Q, or shorelines"""
msg = (
"At least one of the following parameters must be specified: "
"lakes, land, water, rivers, borders, dcw, Q, or shorelines."
)
raise GMTInvalidInput(msg)
with Session() as lib:
lib.call_module(module="coast", args=build_arg_list(kwargs))
8 changes: 4 additions & 4 deletions pygmt/src/dimfilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,11 @@ def dimfilter(grid, outgrid: str | None = None, **kwargs) -> xr.DataArray | None
... )
"""
if not all(arg in kwargs for arg in ["D", "F", "N"]) and "Q" not in kwargs:
raise GMTInvalidInput(
"""At least one of the following parameters must be specified:
distance, filters, or sectors."""
msg = (
"At least one of the following parameters must be specified: "
"distance, filters, or sectors."
)

raise GMTInvalidInput(msg)
with Session() as lib:
with (
lib.virtualfile_in(check_kind="raster", data=grid) as vingrd,
Expand Down
3 changes: 2 additions & 1 deletion pygmt/src/filter1d.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ def filter1d(
(depends on ``output_type``)
"""
if kwargs.get("F") is None:
raise GMTInvalidInput("Pass a required argument to 'filter_type'.")
msg = "Pass a required argument to 'filter_type'."
raise GMTInvalidInput(msg)

output_type = validate_output_table_type(output_type, outfile=outfile)

Expand Down
3 changes: 2 additions & 1 deletion pygmt/src/grd2cpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ def grd2cpt(grid, **kwargs):
>>> fig.show()
"""
if kwargs.get("W") is not None and kwargs.get("Ww") is not None:
raise GMTInvalidInput("Set only categorical or cyclic to True, not both.")
msg = "Set only 'categorical' or 'cyclic' to True, not both."
raise GMTInvalidInput(msg)

if (output := kwargs.pop("H", None)) is not None:
kwargs["H"] = True
Expand Down
8 changes: 4 additions & 4 deletions pygmt/src/grd2xyz.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,12 @@ def grd2xyz(
output_type = validate_output_table_type(output_type, outfile=outfile)

if kwargs.get("o") is not None and output_type == "pandas":
raise GMTInvalidInput(
"If 'outcols' is specified, 'output_type' must be either 'numpy'"
msg = (
"If 'outcols' is specified, 'output_type' must be either 'numpy' "
"or 'file'."
)

# Set the default column names for the pandas dataframe header.
raise GMTInvalidInput(msg)
# Set the default column names for the pandas DataFrame header.
column_names: list[str] = ["x", "y", "z"]
# Let output pandas column names match input DataArray dimension names
if output_type == "pandas" and isinstance(grid, xr.DataArray):
Expand Down
3 changes: 2 additions & 1 deletion pygmt/src/grdfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ def grdfill(grid, outgrid: str | None = None, **kwargs) -> xr.DataArray | None:
>>> filled_grid = pygmt.grdfill(grid=earth_relief_holes, mode="c20")
"""
if kwargs.get("A") is None and kwargs.get("L") is None:
raise GMTInvalidInput("At least parameter 'mode' or 'L' must be specified.")
msg = "At least parameter 'mode' or 'L' must be specified."
raise GMTInvalidInput(msg)

with Session() as lib:
with (
Expand Down
Loading

0 comments on commit 949274d

Please sign in to comment.