Skip to content

Commit 1e312ee

Browse files
authored
Move Figure.psconvert into a separate file (#3553)
1 parent 68bb695 commit 1e312ee

File tree

3 files changed

+136
-131
lines changed

3 files changed

+136
-131
lines changed

pygmt/figure.py

+5-131
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,7 @@
1818
import numpy as np
1919
from pygmt.clib import Session
2020
from pygmt.exceptions import GMTError, GMTInvalidInput
21-
from pygmt.helpers import (
22-
build_arg_list,
23-
fmt_docstring,
24-
kwargs_to_strings,
25-
launch_external_viewer,
26-
unique_name,
27-
use_alias,
28-
)
21+
from pygmt.helpers import launch_external_viewer, unique_name
2922

3023

3124
def _get_default_display_method() -> Literal["external", "notebook", "none"]:
@@ -142,129 +135,6 @@ def region(self) -> np.ndarray:
142135
wesn = lib.extract_region()
143136
return wesn
144137

145-
@fmt_docstring
146-
@use_alias(
147-
A="crop",
148-
C="gs_option",
149-
E="dpi",
150-
F="prefix",
151-
G="gs_path",
152-
I="resize",
153-
N="bb_style",
154-
T="fmt",
155-
Q="anti_aliasing",
156-
V="verbose",
157-
)
158-
@kwargs_to_strings()
159-
def psconvert(self, **kwargs):
160-
r"""
161-
Convert [E]PS file(s) to other formats.
162-
163-
Converts one or more PostScript files to other formats (BMP, EPS, JPEG,
164-
PDF, PNG, PPM, TIFF) using Ghostscript.
165-
166-
If no input files are given, will convert the current active figure
167-
(see :class:`pygmt.Figure`). In this case, an output name must be given
168-
using parameter ``prefix``.
169-
170-
Full option list at :gmt-docs:`psconvert.html`
171-
172-
{aliases}
173-
174-
Parameters
175-
----------
176-
crop : str or bool
177-
Adjust the BoundingBox and HiResBoundingBox to the minimum
178-
required by the image content. Default is ``True``. Append **+u** to
179-
first remove any GMT-produced time-stamps. Append **+r** to
180-
*round* the HighResBoundingBox instead of using the ``ceil``
181-
function. This is going against Adobe Law but can be useful when
182-
creating very small images where the difference of one pixel
183-
might matter. If ``verbose`` is used we also report the
184-
dimensions of the final illustration.
185-
gs_path : str
186-
Full path to the Ghostscript executable.
187-
gs_option : str
188-
Specify a single, custom option that will be passed on to
189-
Ghostscript as is.
190-
dpi : int
191-
Set raster resolution in dpi. Default is 720 for PDF, 300 for
192-
others.
193-
prefix : str
194-
Force the output file name. By default output names are constructed
195-
using the input names as base, which are appended with an
196-
appropriate extension. Use this option to provide a different name,
197-
but without extension. Extension is still determined automatically.
198-
resize : str
199-
[**+m**\ *margins*][**+s**\ [**m**]\ *width*\
200-
[/\ *height*]][**+S**\ *scale*].
201-
Adjust the BoundingBox and HiResBoundingBox by scaling and/or
202-
adding margins. Append **+m** to specify extra margins to extend
203-
the bounding box. Give either one (uniform), two (x and y) or four
204-
(individual sides) margins; append unit [Default is set by
205-
:gmt-term:`PROJ_LENGTH_UNIT`]. Append **+s**\ *width* to resize the
206-
output image to exactly *width* units. The default unit is set by
207-
:gmt-term:`PROJ_LENGTH_UNIT` but you can append a new unit and/or
208-
impose different width and height (**Note**: This may change the
209-
image aspect ratio). What happens here is that Ghostscript will do
210-
the re-interpolation work and the final image will retain the DPI
211-
resolution set by ``dpi``. Append **+sm** to set a maximum size
212-
and the new *width* is only imposed if the original figure width
213-
exceeds it. Append /\ *height* to also impose a maximum height in
214-
addition to the width. Alternatively, append **+S**\ *scale* to
215-
scale the image by a constant factor.
216-
bb_style : str
217-
Set optional BoundingBox fill color, fading, or draw the outline
218-
of the BoundingBox. Append **+f**\ *fade* to fade the entire plot
219-
towards black (100%) [no fading, 0]. Append **+g**\ *paint* to
220-
paint the BoundingBox behind the illustration and append **+p**\
221-
[*pen*] to draw the BoundingBox outline (append a pen or accept
222-
the default pen of ``"0.25p,black,solid"``). **Note**: If both **+g** and
223-
**+f** are used then we use *paint* as the fade color instead of
224-
black. Append **+i** to enforce gray-shades by using ICC profiles.
225-
anti_aliasing : str
226-
[**g**\|\ **p**\|\ **t**\][**1**\|\ **2**\|\ **4**].
227-
Set the anti-aliasing options for **g**\ raphics or **t**\ ext.
228-
Append the size of the subsample box (1, 2, or 4) [Default is
229-
``"4"``]. [Default is no anti-aliasing (same as bits = 1).]
230-
fmt : str
231-
Set the output format, where **b** means BMP, **e** means EPS,
232-
**E** means EPS with PageSize command, **f** means PDF, **F** means
233-
multi-page PDF, **j** means JPEG, **g** means PNG, **G** means
234-
transparent PNG (untouched regions are transparent), **m** means
235-
PPM, and **t** means TIFF [Default is JPEG]. To
236-
**b**\|\ **j**\|\ **g**\|\ **t**\ , optionally append **+m** in
237-
order to get a monochrome (grayscale) image. The EPS format can be
238-
combined with any of the other formats. For example, **ef** creates
239-
both an EPS and a PDF file. Using **F** creates a multi-page PDF
240-
file from the list of input PS or PDF files. It requires the
241-
``prefix`` parameter.
242-
{verbose}
243-
"""
244-
kwargs = self._preprocess(**kwargs)
245-
# pytest-mpl v0.17.0 added the "metadata" parameter to Figure.savefig, which
246-
# is not recognized. So remove it before calling Figure.psconvert.
247-
kwargs.pop("metadata", None)
248-
# Default cropping the figure to True
249-
if kwargs.get("A") is None:
250-
kwargs["A"] = ""
251-
252-
prefix = kwargs.get("F")
253-
if prefix in {"", None, False, True}:
254-
raise GMTInvalidInput(
255-
"The 'prefix' parameter must be specified with a valid value."
256-
)
257-
258-
# check if the parent directory exists
259-
prefix_path = Path(prefix).parent
260-
if not prefix_path.exists():
261-
raise FileNotFoundError(
262-
f"No such directory: '{prefix_path}', please create it first."
263-
)
264-
265-
with Session() as lib:
266-
lib.call_module(module="psconvert", args=build_arg_list(kwargs))
267-
268138
def savefig( # noqa: PLR0912
269139
self,
270140
fname: str | PurePath,
@@ -374,6 +244,9 @@ def savefig( # noqa: PLR0912
374244
raise GMTInvalidInput(msg)
375245
kwargs["W"] = True
376246

247+
# pytest-mpl v0.17.0 added the "metadata" parameter to Figure.savefig, which
248+
# is not recognized. So remove it before calling Figure.psconvert.
249+
kwargs.pop("metadata", None)
377250
self.psconvert(prefix=prefix, fmt=fmt, crop=crop, **kwargs)
378251

379252
# Remove the .pgw world file if exists.
@@ -543,6 +416,7 @@ def _repr_html_(self):
543416
meca,
544417
plot,
545418
plot3d,
419+
psconvert,
546420
rose,
547421
set_panel,
548422
shift_origin,

pygmt/src/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from pygmt.src.plot import plot
4141
from pygmt.src.plot3d import plot3d
4242
from pygmt.src.project import project
43+
from pygmt.src.psconvert import psconvert
4344
from pygmt.src.rose import rose
4445
from pygmt.src.select import select
4546
from pygmt.src.shift_origin import shift_origin

pygmt/src/psconvert.py

+130
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
"""
2+
psconvert - Convert [E]PS file(s) to other formats.
3+
"""
4+
5+
from pathlib import Path
6+
7+
from pygmt.clib import Session
8+
from pygmt.exceptions import GMTInvalidInput
9+
from pygmt.helpers import build_arg_list, fmt_docstring, kwargs_to_strings, use_alias
10+
11+
12+
@fmt_docstring
13+
@use_alias(
14+
A="crop",
15+
C="gs_option",
16+
E="dpi",
17+
F="prefix",
18+
G="gs_path",
19+
I="resize",
20+
N="bb_style",
21+
T="fmt",
22+
Q="anti_aliasing",
23+
V="verbose",
24+
)
25+
@kwargs_to_strings()
26+
def psconvert(self, **kwargs):
27+
r"""
28+
Convert [E]PS file(s) to other formats.
29+
30+
Converts one or more PostScript files to other formats (BMP, EPS, JPEG,
31+
PDF, PNG, PPM, TIFF) using Ghostscript.
32+
33+
If no input files are given, will convert the current active figure
34+
(see :class:`pygmt.Figure`). In this case, an output name must be given
35+
using parameter ``prefix``.
36+
37+
Full option list at :gmt-docs:`psconvert.html`
38+
39+
{aliases}
40+
41+
Parameters
42+
----------
43+
crop : str or bool
44+
Adjust the BoundingBox and HiResBoundingBox to the minimum
45+
required by the image content. Default is ``True``. Append **+u** to
46+
first remove any GMT-produced time-stamps. Append **+r** to
47+
*round* the HighResBoundingBox instead of using the ``ceil``
48+
function. This is going against Adobe Law but can be useful when
49+
creating very small images where the difference of one pixel
50+
might matter. If ``verbose`` is used we also report the
51+
dimensions of the final illustration.
52+
gs_path : str
53+
Full path to the Ghostscript executable.
54+
gs_option : str
55+
Specify a single, custom option that will be passed on to
56+
Ghostscript as is.
57+
dpi : int
58+
Set raster resolution in dpi. Default is 720 for PDF, 300 for
59+
others.
60+
prefix : str
61+
Force the output file name. By default output names are constructed
62+
using the input names as base, which are appended with an
63+
appropriate extension. Use this option to provide a different name,
64+
but without extension. Extension is still determined automatically.
65+
resize : str
66+
[**+m**\ *margins*][**+s**\ [**m**]\ *width*\
67+
[/\ *height*]][**+S**\ *scale*].
68+
Adjust the BoundingBox and HiResBoundingBox by scaling and/or
69+
adding margins. Append **+m** to specify extra margins to extend
70+
the bounding box. Give either one (uniform), two (x and y) or four
71+
(individual sides) margins; append unit [Default is set by
72+
:gmt-term:`PROJ_LENGTH_UNIT`]. Append **+s**\ *width* to resize the
73+
output image to exactly *width* units. The default unit is set by
74+
:gmt-term:`PROJ_LENGTH_UNIT` but you can append a new unit and/or
75+
impose different width and height (**Note**: This may change the
76+
image aspect ratio). What happens here is that Ghostscript will do
77+
the re-interpolation work and the final image will retain the DPI
78+
resolution set by ``dpi``. Append **+sm** to set a maximum size
79+
and the new *width* is only imposed if the original figure width
80+
exceeds it. Append /\ *height* to also impose a maximum height in
81+
addition to the width. Alternatively, append **+S**\ *scale* to
82+
scale the image by a constant factor.
83+
bb_style : str
84+
Set optional BoundingBox fill color, fading, or draw the outline
85+
of the BoundingBox. Append **+f**\ *fade* to fade the entire plot
86+
towards black (100%) [no fading, 0]. Append **+g**\ *paint* to
87+
paint the BoundingBox behind the illustration and append **+p**\
88+
[*pen*] to draw the BoundingBox outline (append a pen or accept
89+
the default pen of ``"0.25p,black,solid"``). **Note**: If both **+g** and
90+
**+f** are used then we use *paint* as the fade color instead of
91+
black. Append **+i** to enforce gray-shades by using ICC profiles.
92+
anti_aliasing : str
93+
[**g**\|\ **p**\|\ **t**\][**1**\|\ **2**\|\ **4**].
94+
Set the anti-aliasing options for **g**\ raphics or **t**\ ext.
95+
Append the size of the subsample box (1, 2, or 4) [Default is
96+
``"4"``]. [Default is no anti-aliasing (same as bits = 1).]
97+
fmt : str
98+
Set the output format, where **b** means BMP, **e** means EPS,
99+
**E** means EPS with PageSize command, **f** means PDF, **F** means
100+
multi-page PDF, **j** means JPEG, **g** means PNG, **G** means
101+
transparent PNG (untouched regions are transparent), **m** means
102+
PPM, and **t** means TIFF [Default is JPEG]. To
103+
**b**\|\ **j**\|\ **g**\|\ **t**\ , optionally append **+m** in
104+
order to get a monochrome (grayscale) image. The EPS format can be
105+
combined with any of the other formats. For example, **ef** creates
106+
both an EPS and a PDF file. Using **F** creates a multi-page PDF
107+
file from the list of input PS or PDF files. It requires the
108+
``prefix`` parameter.
109+
{verbose}
110+
"""
111+
kwargs = self._preprocess(**kwargs)
112+
# Default cropping the figure to True
113+
if kwargs.get("A") is None:
114+
kwargs["A"] = ""
115+
116+
prefix = kwargs.get("F")
117+
if prefix in {"", None, False, True}:
118+
raise GMTInvalidInput(
119+
"The 'prefix' parameter must be specified with a valid value."
120+
)
121+
122+
# Check if the parent directory exists
123+
prefix_path = Path(prefix).parent
124+
if not prefix_path.exists():
125+
raise FileNotFoundError(
126+
f"No such directory: '{prefix_path}', please create it first."
127+
)
128+
129+
with Session() as lib:
130+
lib.call_module(module="psconvert", args=build_arg_list(kwargs))

0 commit comments

Comments
 (0)