Skip to content

Commit 95ce4e6

Browse files
authored
Figure.meca: Refactor and add the private _get_focal_convention function (#3827)
1 parent 81fb2e2 commit 95ce4e6

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

pygmt/src/meca.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,21 @@
1010
from pygmt.src._common import _FocalMechanismConvention
1111

1212

13+
def _get_focal_convention(spec, convention, component) -> _FocalMechanismConvention:
14+
"""
15+
Determine the focal mechanism convention from the input data or parameters.
16+
"""
17+
# Determine the convention from dictionary keys or pandas.DataFrame column names.
18+
if hasattr(spec, "keys"): # Dictionary or pandas.DataFrame
19+
return _FocalMechanismConvention.from_params(spec.keys(), component=component)
20+
21+
# Determine the convention from the 'convention' parameter.
22+
if convention is None:
23+
msg = "Parameter 'convention' must be specified."
24+
raise GMTInvalidInput(msg)
25+
return _FocalMechanismConvention(convention=convention, component=component)
26+
27+
1328
@fmt_docstring
1429
@use_alias(
1530
A="offset",
@@ -234,13 +249,11 @@ def meca( # noqa: PLR0912, PLR0913
234249
"""
235250
kwargs = self._preprocess(**kwargs)
236251

252+
# Determine the focal mechanism convention from the input data or parameters.
253+
_convention = _get_focal_convention(spec, convention, component)
254+
237255
# Convert spec to pandas.DataFrame unless it's a file
238256
if isinstance(spec, dict | pd.DataFrame): # spec is a dict or pd.DataFrame
239-
# Determine convention from dict keys or pd.DataFrame column names
240-
_convention = _FocalMechanismConvention.from_params(
241-
spec.keys(), component=component
242-
)
243-
244257
# convert dict to pd.DataFrame so columns can be reordered
245258
if isinstance(spec, dict):
246259
# convert values to ndarray so pandas doesn't complain about "all
@@ -250,14 +263,6 @@ def meca( # noqa: PLR0912, PLR0913
250263
{key: np.atleast_1d(value) for key, value in spec.items()}
251264
)
252265
elif isinstance(spec, np.ndarray): # spec is a numpy array
253-
if convention is None:
254-
msg = "'convention' must be specified for an array input."
255-
raise GMTInvalidInput(msg)
256-
257-
_convention = _FocalMechanismConvention(
258-
convention=convention, component=component
259-
)
260-
261266
# Convert array to pd.DataFrame and assign column names
262267
spec = pd.DataFrame(np.atleast_2d(spec))
263268
colnames = ["longitude", "latitude", "depth", *_convention.params]
@@ -277,10 +282,6 @@ def meca( # noqa: PLR0912, PLR0913
277282
)
278283
raise GMTInvalidInput(msg)
279284
spec.columns = colnames
280-
else:
281-
_convention = _FocalMechanismConvention(
282-
convention=convention, component=component
283-
)
284285

285286
# Now spec is a pd.DataFrame or a file
286287
if isinstance(spec, pd.DataFrame):

0 commit comments

Comments
 (0)