diff --git a/.gitignore b/.gitignore index 6573fc43a34..7e18dc2d5bb 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ MANIFEST .pytest_cache/ .ipynb_checkpoints/ .vscode/ +tmp-test-dir-with-unique-name/ build/ dist/ doc/_build diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f4b09da6834..98c1ef166a5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -269,6 +269,17 @@ make check # Runs flake8 and black (in check mode) make lint # Runs pylint, which is a bit slower ``` +#### Docstrings + +**All docstrings** should follow the +[numpy style guide](https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard). +All functions/classes/methods should have docstrings with a full description of all +arguments and return values. + +While the maximum line length for code is automatically set by *Black*, docstrings +must be formatted manually. To play nicely with Jupyter and IPython, **keep docstrings +limited to 79 characters** per line. + ### Testing your code Automated testing helps ensure that our code is as free of bugs as it can be. @@ -360,7 +371,7 @@ Sphinx will create a link to the automatically generated page for that function/class/module. **All docstrings** should follow the -[numpy style guide](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt). +[numpy style guide](https://numpydoc.readthedocs.io/en/latest/format.html). All functions/classes/methods should have docstrings with a full description of all arguments and return values. @@ -379,7 +390,7 @@ Some things that will increase the chance that your pull request is accepted qui *reason* behind non-obvious things. * Include an example of new features in the gallery or tutorials. * Follow the [PEP8](http://pep8.org) style guide for code and the - [numpy guide](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) + [numpy guide](https://numpydoc.readthedocs.io/en/latest/format.html) for documentation. Pull requests will automatically have tests run by TravisCI. diff --git a/pygmt/__init__.py b/pygmt/__init__.py index b886a267acf..2c035e913ef 100644 --- a/pygmt/__init__.py +++ b/pygmt/__init__.py @@ -2,10 +2,10 @@ # # The main API for PyGMT. # -# All of PyGMT is operated on a "modern mode session" (new to GMT6). When you import the -# pygmt library, a new session will be started automatically. The session will be -# closed when the current Python process terminates. Thus, the Python API does not -# expose the `gmt begin` and `gmt end` commands. +# All of PyGMT is operated on a "modern mode session" (new to GMT6). When you +# import the pygmt library, a new session will be started automatically. The +# session will be closed when the current Python process terminates. Thus, the +# Python API does not expose the `gmt begin` and `gmt end` commands. import atexit as _atexit @@ -34,8 +34,8 @@ def print_clib_info(): """ Print information about the GMT shared library that we can find. - Includes the GMT version, default values for parameters, the path to the ``libgmt`` - shared library, and GMT directories. + Includes the GMT version, default values for parameters, the path to the + ``libgmt`` shared library, and GMT directories. """ from .clib import Session diff --git a/pygmt/base_plotting.py b/pygmt/base_plotting.py index 90648e02d6a..575880c43eb 100644 --- a/pygmt/base_plotting.py +++ b/pygmt/base_plotting.py @@ -36,8 +36,8 @@ def _preprocess(self, **kwargs): # pylint: disable=no-self-use insert special arguments into the kwargs or make any actions that are required before ``call_module``. - For example, the :class:`pygmt.Figure` needs this to tell the GMT modules - to plot to a specific figure. + For example, the :class:`pygmt.Figure` needs this to tell the GMT + modules to plot to a specific figure. This is a dummy method that does nothing. @@ -147,63 +147,61 @@ def colorbar(self, **kwargs): """ Plot a gray or color scale-bar on maps. - Both horizontal and vertical scales are supported. For CPTs with gradational - colors (i.e., the lower and upper boundary of an interval have different colors) - we will interpolate to give a continuous scale. Variations in intensity due to - shading/illumination may be displayed by setting the option -I. Colors may be - spaced according to a linear scale, all be equal size, or by providing a file - with individual tile widths. + Both horizontal and vertical scales are supported. For CPTs with + gradational colors (i.e., the lower and upper boundary of an interval + have different colors) we will interpolate to give a continuous scale. + Variations in intensity due to shading/illumination may be displayed by + setting the option -I. Colors may be spaced according to a linear + scale, all be equal size, or by providing a file with individual tile + widths. Full option list at :gmt-docs:`colorbar.html` Parameters ---------- position (D) : str - ``[g|j|J|n|x]refpoint[+wlength[/width]][+e[b|f][length]][+h|v][+jjustify] - [+m[a|c|l|u]][+n[txt]][+odx[/dy]]``. - Defines the reference point on the map for the color scale using one of four - coordinate systems: - (1) Use -Dg for map (user) coordinates, - (2) use -Dj or -DJ for setting refpoint via a 2-char justification code that - refers to the (invisible) map domain rectangle, - (3) use -Dn for normalized (0-1) coordinates, or - (4) use -Dx for plot coordinates (inches, cm, etc.).\ - All but -Dx requires both -R and -J to be specified. - Append +w followed by the length and width of the color bar. - If width is not specified then it is set to 4% of the given length. - Give a negative length to reverse the scale bar. - Append +h to get a horizontal scale [Default is vertical (+v)]. - By default, the anchor point on the scale is assumed to be the bottom left - corner (BL), but this can be changed by appending +j followed by a 2-char - justification code justify. + ``[g|j|J|n|x]refpoint[+wlength[/width]][+e[b|f][length]][+h|v] + [+jjustify][+m[a|c|l|u]][+n[txt]][+odx[/dy]]``. Defines the + reference point on the map for the color scale using one of four + coordinate systems: (1) Use -Dg for map (user) coordinates, (2) use + -Dj or -DJ for setting refpoint via a 2-char justification code + that refers to the (invisible) map domain rectangle, (3) use -Dn + for normalized (0-1) coordinates, or (4) use -Dx for plot + coordinates (inches, cm, etc.). All but -Dx requires both -R and + -J to be specified. Append +w followed by the length and width of + the color bar. If width is not specified then it is set to 4% of + the given length. Give a negative length to reverse the scale bar. + Append +h to get a horizontal scale [Default is vertical (+v)]. By + default, the anchor point on the scale is assumed to be the bottom + left corner (BL), but this can be changed by appending +j followed + by a 2-char justification code justify. box (F) : bool or str - ``[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]][+s[[dx/dy/] - [shade]]]``. - If set to True, draws a rectangular border around the color scale. - Alternatively, specify a different pen with +ppen. - Add +gfill to fill the scale panel [no fill]. + ``[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]] + [+s[[dx/dy/][shade]]]``. If set to True, draws a rectangular + border around the color scale. Alternatively, specify a different + pen with +ppen. Add +gfill to fill the scale panel [no fill]. Append +cclearance where clearance is either gap, xgap/ygap, or - lgap/rgap/bgap/tgap where these items are uniform, separate in x- and - y-direction, or individual side spacings between scale and border. - Append +i to draw a secondary, inner border as well. We use a uniform gap - between borders of 2p and the MAP_DEFAULTS_PEN unless other values are - specified. - Append +r to draw rounded rectangular borders instead, with a 6p corner - radius. You can override this radius by appending another value. - Finally, append +s to draw an offset background shaded region. Here, dx/dy - indicates the shift relative to the foreground frame [4p/-4p] and shade sets - the fill style to use for shading [gray50]. + lgap/rgap/bgap/tgap where these items are uniform, separate in x- + and y-direction, or individual side spacings between scale and + border. Append +i to draw a secondary, inner border as well. We use + a uniform gap between borders of 2p and the MAP_DEFAULTS_PEN unless + other values are specified. Append +r to draw rounded rectangular + borders instead, with a 6p corner radius. You can override this + radius by appending another value. Finally, append +s to draw an + offset background shaded region. Here, dx/dy indicates the shift + relative to the foreground frame [4p/-4p] and shade sets the fill + style to use for shading [gray50]. truncate (G) : list or str - ``zlo/zhi`` - Truncate the incoming CPT so that the lowest and highest z-levels are to zlo - and zhi. If one of these equal NaN then we leave that end of the CPT alone. - The truncation takes place before the plotting. + ``zlo/zhi`` Truncate the incoming CPT so that the lowest and + highest z-levels are to zlo and zhi. If one of these equal NaN then + we leave that end of the CPT alone. The truncation takes place + before the plotting. scale (W) : float - Multiply all z-values in the CPT by the provided scale. By default the CPT - is used as is. + Multiply all z-values in the CPT by the provided scale. By default + the CPT is used as is. {aliases} """ @@ -362,7 +360,8 @@ def plot(self, x=None, y=None, data=None, sizes=None, direction=None, **kwargs): Parameters ---------- x, y : float or 1d arrays - The x and y coordinates, or arrays of x and y coordinates of the data points + The x and y coordinates, or arrays of x and y coordinates of the + data points data : str or 2d array Either a data file name or a 2d numpy array with the tabular data. Use option *columns* (i) to choose which columns are x, y, color, @@ -594,7 +593,8 @@ def image(self, imagefile, **kwargs): """ Place images or EPS files on maps. - Reads an Encapsulated PostScript file or a raster image file and plots it on a map. + Reads an Encapsulated PostScript file or a raster image file and plots + it on a map. Full option list at :gmt-docs:`image.html` @@ -605,12 +605,13 @@ def image(self, imagefile, **kwargs): {J} {R} D: str - ``'[g|j|J|n|x]refpoint+rdpi+w[-]width[/height][+jjustify][+nnx[/ny]][+odx[/dy]]'`` - Sets reference point on the map for the image. + ``'[g|j|J|n|x]refpoint+rdpi+w[-]width[/height][+jjustify] + [+nnx[/ny]][+odx[/dy]]'`` Sets reference point on the map for the + image. F : bool or str - ``'[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]][+s[[dx/dy/][shade]]]'`` - Without further options, draws a rectangular border around the - image using **MAP_FRAME_PEN**. + ``'[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]] + [+s[[dx/dy/][shade]]]'`` Without further options, draws a + rectangular border around the image using **MAP_FRAME_PEN**. M : bool Convert color image to monochrome grayshades using the (television) YIQ-transformation. @@ -627,11 +628,11 @@ def legend(self, spec=None, position="JTR+jTR+o0.2c", box="+gwhite+p1p", **kwarg """ Plot legends on maps. - Makes legends that can be overlaid on maps. Reads specific legend-related - information from an input file, or automatically creates legend entries from - plotted symbols that have labels. Unless otherwise noted, annotations will be - made using the primary annotation font and size in effect - (i.e., FONT_ANNOT_PRIMARY). + Makes legends that can be overlaid on maps. Reads specific + legend-related information from an input file, or automatically creates + legend entries from plotted symbols that have labels. Unless otherwise + noted, annotations will be made using the primary annotation font and + size in effect (i.e., FONT_ANNOT_PRIMARY). Full option list at :gmt-docs:`legend.html` @@ -641,19 +642,21 @@ def legend(self, spec=None, position="JTR+jTR+o0.2c", box="+gwhite+p1p", **kwarg ---------- spec : None or str Either None (default) for using the automatically generated legend - specification file, or a filename pointing to the legend specification file. + specification file, or a filename pointing to the legend + specification file. {J} {R} position (D) : str - ``'[g|j|J|n|x]refpoint+wwidth[/height][+jjustify][+lspacing][+odx[/dy]]'`` - Defines the reference point on the map for the legend. By default, uses - 'JTR+jTR+o0.2c' which places the legend at the top-right corner inside - the map frame, with a 0.2 cm offset. + ``'[g|j|J|n|x]refpoint+wwidth[/height][+jjustify][+lspacing] + [+odx[/dy]]'`` Defines the reference point on the map for the + legend. By default, uses 'JTR+jTR+o0.2c' which places the legend at + the top-right corner inside the map frame, with a 0.2 cm offset. box (F) : bool or str - ``'[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]][+s[[dx/dy/][shade]]]'`` - Without further options, draws a rectangular border around the - legend using **MAP_FRAME_PEN**. By default, uses '+gwhite+p1p' which draws - a box around the legend using a 1 point black pen and adds a white background. + ``'[+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]] + [+s[[dx/dy/][shade]]]'`` Without further options, draws a + rectangular border around the legend using **MAP_FRAME_PEN**. By + default, uses '+gwhite+p1p' which draws a box around the legend + using a 1 point black pen and adds a white background. """ kwargs = self._preprocess(**kwargs) @@ -709,28 +712,30 @@ def text( Parameters ---------- textfiles : str or list - A text data file name, or a list of filenames containing 1 or more records - with (x, y[, font, angle, justify], text). + A text data file name, or a list of filenames containing 1 or more + records with (x, y[, font, angle, justify], text). x, y : float or 1d arrays - The x and y coordinates, or an array of x and y coordinates to plot the text + The x and y coordinates, or an array of x and y coordinates to plot + the text text : str or 1d array The text string, or an array of strings to plot on the figure angle: int/float or bool - Set the angle measured in degrees counter-clockwise from horizontal. E.g. 30 - sets the text at 30 degrees. If no angle is given then the input textfile(s) - must have this as a column. + Set the angle measured in degrees counter-clockwise from + horizontal. E.g. 30 sets the text at 30 degrees. If no angle is + given then the input textfile(s) must have this as a column. font : str or bool - Set the font specification with format "size,font,color" where size is text - size in points, font is the font to use, and color sets the font color. E.g. - "12p,Helvetica-Bold,red" selects a 12p red Helvetica-Bold font. If no font - info is given then the input textfile(s) must have this information in one - of its columns. + Set the font specification with format "size,font,color" where size + is text size in points, font is the font to use, and color sets the + font color. E.g. "12p,Helvetica-Bold,red" selects a 12p red + Helvetica-Bold font. If no font info is given then the input + textfile(s) must have this information in one of its columns. justify: str or bool - Set the alignment which refers to the part of the text string that will be - mapped onto the (x,y) point. Choose a 2 character combination of L, C, R - (for left, center, or right) and T, M, B for top, middle, or bottom. E.g., - BL for lower left. If no justification is given then the input textfile(s) - must have this as a column. + Set the alignment which refers to the part of the text string that + will be mapped onto the (x,y) point. Choose a 2 character + combination of L, C, R (for left, center, or right) and T, M, B for + top, middle, or bottom. E.g., BL for lower left. If no + justification is given then the input textfile(s) must have this as + a column. {J} {R} """ diff --git a/pygmt/clib/__init__.py b/pygmt/clib/__init__.py index 5840e216a17..a6282f84122 100644 --- a/pygmt/clib/__init__.py +++ b/pygmt/clib/__init__.py @@ -2,7 +2,7 @@ # # Low-level wrapper for the GMT C API. # -# The pygmt.clib.Session class wraps the GMT C shared library (libgmt) with a pythonic -# interface. Access to the C library is done through ctypes. +# The pygmt.clib.Session class wraps the GMT C shared library (libgmt) with a +# pythonic interface. Access to the C library is done through ctypes. from .session import Session diff --git a/pygmt/clib/loading.py b/pygmt/clib/loading.py index 2de978534f3..58b33196e85 100644 --- a/pygmt/clib/loading.py +++ b/pygmt/clib/loading.py @@ -1,8 +1,8 @@ """ Utility functions to load libgmt as ctypes.CDLL. -The path to the shared library can be found automatically by ctypes or set through the -GMT_LIBRARY_PATH environment variable. +The path to the shared library can be found automatically by ctypes or set +through the GMT_LIBRARY_PATH environment variable. """ import os import sys @@ -91,8 +91,8 @@ def clib_name(os_name=None, is_64bit=None): The operating system name as given by ``sys.platform`` (the default if None). is_64bit : bool or None - Whether or not the OS is 64bit. Only used if the OS is ``win32``. If None, will - determine automatically. + Whether or not the OS is 64bit. Only used if the OS is ``win32``. If + None, will determine automatically. Returns ------- diff --git a/pygmt/clib/session.py b/pygmt/clib/session.py index f7c396a633a..bb39b57e384 100644 --- a/pygmt/clib/session.py +++ b/pygmt/clib/session.py @@ -1,6 +1,7 @@ """ -Defines the Session class to create and destroy a GMT API session and provides access to -the API functions. Uses ctypes to wrap most of the core functions from the C API. +Defines the Session class to create and destroy a GMT API session and provides +access to the API functions. Uses ctypes to wrap most of the core functions +from the C API. """ import sys import ctypes as ctp @@ -60,29 +61,29 @@ class Session: """ A GMT API session where most operations involving the C API happen. - Works as a context manager (for use in a ``with`` block) to create a GMT C API - session and destroy it in the end to clean up memory. + Works as a context manager (for use in a ``with`` block) to create a GMT C + API session and destroy it in the end to clean up memory. - Functions of the shared library are exposed as methods of this class. Most methods - MUST be used with an open session (inside a ``with`` block). If creating GMT data - structures to communicate data, put that code inside the same ``with`` block as the - API calls that will use the data. + Functions of the shared library are exposed as methods of this class. Most + methods MUST be used with an open session (inside a ``with`` block). If + creating GMT data structures to communicate data, put that code inside the + same ``with`` block as the API calls that will use the data. - By default, will let :mod:`ctypes` try to find the GMT shared library (``libgmt``). - If the environment variable ``GMT_LIBRARY_PATH`` is set, will look for the shared - library in the directory specified by it. + By default, will let :mod:`ctypes` try to find the GMT shared library + (``libgmt``). If the environment variable ``GMT_LIBRARY_PATH`` is set, will + look for the shared library in the directory specified by it. - A ``GMTVersionError`` exception will be raised if the GMT shared library reports a - version < 6.0.0. + A ``GMTVersionError`` exception will be raised if the GMT shared library + reports a version < 6.0.0. - The ``session_pointer`` attribute holds a ctypes pointer to the currently open - session. + The ``session_pointer`` attribute holds a ctypes pointer to the currently + open session. Raises ------ GMTCLibNotFoundError - If there was any problem loading the library (couldn't find it or couldn't - access the functions). + If there was any problem loading the library (couldn't find it or + couldn't access the functions). GMTCLibNoSessionError If you try to call a method outside of a 'with' block. GMTVersionError @@ -96,15 +97,18 @@ class Session: >>> grid = load_earth_relief() >>> type(grid) - >>> # Create a session and destroy it automatically when exiting the "with" block. + >>> # Create a session and destroy it automatically when exiting the "with" + >>> # block. >>> with Session() as ses: ... # Create a virtual file and link to the memory block of the grid. ... with ses.virtualfile_from_grid(grid) as fin: ... # Create a temp file to use as output. ... with GMTTempFile() as fout: - ... # Call the grdinfo module with the virtual file as input and the. - ... # temp file as output. - ... ses.call_module("grdinfo", "{} -C ->{}".format(fin, fout.name)) + ... # Call the grdinfo module with the virtual file as input + ... # and the temp file as output. + ... ses.call_module( + ... "grdinfo", "{} -C ->{}".format(fin, fout.name) + ... ) ... # Read the contents of the temp file before it's deleted. ... print(fout.read().strip()) -180 180 -90 90 -8596 5559 1 1 361 181 @@ -165,13 +169,14 @@ def __enter__(self): Raises ------ GMTVersionError - If the version reported by libgmt is less than ``Session.required_version``. - Will destroy the session before raising the exception. + If the version reported by libgmt is less than + ``Session.required_version``. Will destroy the session before + raising the exception. """ self.create("pygmt-session") - # Need to store the version info because 'get_default' won't work after the - # session is destroyed. + # Need to store the version info because 'get_default' won't work after + # the session is destroyed. version = self.info["version"] if Version(version) < Version(self.required_version): self.destroy() @@ -194,7 +199,8 @@ def __getitem__(self, name): """ Get the value of a GMT constant (C enum) from gmt_resources.h - Used to set configuration values for other API calls. Wraps ``GMT_Get_Enum``. + Used to set configuration values for other API calls. Wraps + ``GMT_Get_Enum``. Parameters ---------- @@ -204,8 +210,8 @@ def __getitem__(self, name): Returns ------- constant : int - Integer value of the constant. Do not rely on this value because it might - change. + Integer value of the constant. Do not rely on this value because it + might change. Raises ------ @@ -217,11 +223,11 @@ def __getitem__(self, name): "GMT_Get_Enum", argtypes=[ctp.c_void_p, ctp.c_char_p], restype=ctp.c_int ) - # The C lib introduced the void API pointer to GMT_Get_Enum so that it's - # consistent with other functions. It doesn't use the pointer so we can pass in - # None (NULL pointer). We can't give it the actual pointer because we need to - # call GMT_Get_Enum when creating a new API session pointer (chicken-and-egg - # type of thing). + # The C lib introduced the void API pointer to GMT_Get_Enum so that + # it's consistent with other functions. It doesn't use the pointer so + # we can pass in None (NULL pointer). We can't give it the actual + # pointer because we need to call GMT_Get_Enum when creating a new API + # session pointer (chicken-and-egg type of thing). session = None value = c_get_enum(session, name.encode()) @@ -279,21 +285,22 @@ def create(self, name): """ Create a new GMT C API session. - This is required before most other methods of :class:`pygmt.clib.Session` can be - called. + This is required before most other methods of + :class:`pygmt.clib.Session` can be called. .. warning:: - Usage of :class:`~gmt.clib.Session` as a context manager in a ``with`` block - is preferred over calling :meth:`~gmt.clib.Session.create` and + Usage of :class:`~gmt.clib.Session` as a context manager in a + ``with`` block is preferred over calling + :meth:`~gmt.clib.Session.create` and :meth:`~gmt.clib.Session.destroy` manually. - Calls ``GMT_Create_Session`` and generates a new ``GMTAPI_CTRL`` struct, which - is a :class:`ctypes.c_void_p` pointer. Sets the ``session_pointer`` attribute to - this pointer. + Calls ``GMT_Create_Session`` and generates a new ``GMTAPI_CTRL`` + struct, which is a :class:`ctypes.c_void_p` pointer. Sets the + ``session_pointer`` attribute to this pointer. - Remember to terminate the current session using :meth:`pygmt.clib.Session.destroy` - before creating a new one. + Remember to terminate the current session using + :meth:`pygmt.clib.Session.destroy` before creating a new one. Parameters ---------- @@ -304,13 +311,14 @@ def create(self, name): try: # Won't raise an exception if there is a currently open session self.session_pointer # pylint: disable=pointless-statement - # In this case, fail to create a new session until the old one is destroyed + # In this case, fail to create a new session until the old one is + # destroyed raise GMTCLibError( "Failed to create a GMT API session: There is a currently open session." " Must destroy it fist." ) - # If the exception is raised, this means that there is no open session and we're - # free to create a new one. + # If the exception is raised, this means that there is no open session + # and we're free to create a new one. except GMTCLibNoSessionError: pass @@ -320,25 +328,26 @@ def create(self, name): restype=ctp.c_void_p, ) - # Capture the output printed by GMT into this list. Will use it later to - # generate error messages for the exceptions raised by API calls. + # Capture the output printed by GMT into this list. Will use it later + # to generate error messages for the exceptions raised by API calls. self._error_log = [] @ctp.CFUNCTYPE(ctp.c_int, ctp.c_void_p, ctp.c_char_p) def print_func(file_pointer, message): # pylint: disable=unused-argument """ - Callback function that the GMT C API will use to print log and error - messages. We'll capture the messages and print them to stderr so that they - will show up on the Jupyter notebook. + Callback function that the GMT C API will use to print log and + error messages. We'll capture the messages and print them to stderr + so that they will show up on the Jupyter notebook. """ message = message.decode().strip() self._error_log.append(message) - # flush to make sure the messages are printed even if we have a crash. + # flush to make sure the messages are printed even if we have a + # crash. print(message, file=sys.stderr, flush=True) return 0 - # Need to store a copy of the function because ctypes doesn't and it will be - # garbage collected otherwise + # Need to store a copy of the function because ctypes doesn't and it + # will be garbage collected otherwise self._print_callback = print_func padding = self["GMT_PAD_DEFAULT"] @@ -371,17 +380,19 @@ def destroy(self): .. warning:: - Usage of :class:`~gmt.clib.Session` as a context manager in a ``with`` block - is preferred over calling :meth:`~gmt.clib.Session.create` and + Usage of :class:`~gmt.clib.Session` as a context manager in a + ``with`` block is preferred over calling + :meth:`~gmt.clib.Session.create` and :meth:`~gmt.clib.Session.destroy` manually. - Calls ``GMT_Destroy_Session`` to terminate and free the memory of a registered - ``GMTAPI_CTRL`` session (the pointer for this struct is stored in the - ``session_pointer`` attribute). + Calls ``GMT_Destroy_Session`` to terminate and free the memory of a + registered ``GMTAPI_CTRL`` session (the pointer for this struct is + stored in the ``session_pointer`` attribute). - Always use this method after you are done using a C API session. The session - needs to be destroyed before creating a new one. Otherwise, some of the - configuration files might be left behind and can influence subsequent API calls. + Always use this method after you are done using a C API session. The + session needs to be destroyed before creating a new one. Otherwise, + some of the configuration files might be left behind and can influence + subsequent API calls. Sets the ``session_pointer`` attribute to ``None``. """ @@ -893,8 +904,8 @@ def open_virtual_file(self, family, geometry, direction, data): GMT uses a virtual file scheme to pass in data to API modules. Use it to pass in your GMT data structure (created using - :meth:`~gmt.clib.Session.create_data`) to a module that expects an input - or output file. + :meth:`~gmt.clib.Session.create_data`) to a module that expects an + input or output file. Use in a ``with`` block. Will automatically close the virtual file when leaving the ``with`` block. Because of this, no wrapper for @@ -999,30 +1010,33 @@ def virtualfile_from_vectors(self, *vectors): """ Store 1d arrays as columns of a table inside a virtual file. - Use the virtual file name to pass in the data in your vectors to a GMT module. + Use the virtual file name to pass in the data in your vectors to a GMT + module. - Context manager (use in a ``with`` block). Yields the virtual file name that you - can pass as an argument to a GMT module call. Closes the virtual file upon exit - of the ``with`` block. + Context manager (use in a ``with`` block). Yields the virtual file name + that you can pass as an argument to a GMT module call. Closes the + virtual file upon exit of the ``with`` block. - Use this instead of creating the data container and virtual file by hand with - :meth:`~gmt.clib.Session.create_data`, :meth:`~gmt.clib.Session.put_vector`, and + Use this instead of creating the data container and virtual file by + hand with :meth:`~gmt.clib.Session.create_data`, + :meth:`~gmt.clib.Session.put_vector`, and :meth:`~gmt.clib.Session.open_virtual_file`. - If the arrays are C contiguous blocks of memory, they will be passed without - copying to GMT. If they are not (e.g., they are columns of a 2D array), they - will need to be copied to a contiguous block. + If the arrays are C contiguous blocks of memory, they will be passed + without copying to GMT. If they are not (e.g., they are columns of a 2D + array), they will need to be copied to a contiguous block. Parameters ---------- vectors : 1d arrays - The vectors that will be included in the array. All must be of the same - size. + The vectors that will be included in the array. All must be of the + same size. Yields ------ fname : str - The name of virtual file. Pass this as a file name argument to a GMT module. + The name of virtual file. Pass this as a file name argument to a + GMT module. Examples -------- @@ -1037,17 +1051,19 @@ def virtualfile_from_vectors(self, *vectors): ... with ses.virtualfile_from_vectors(x, y, z) as fin: ... # Send the output to a file so that we can read it ... with GMTTempFile() as fout: - ... ses.call_module('info', '{} ->{}'.format(fin, fout.name)) + ... ses.call_module( + ... 'info', '{} ->{}'.format(fin, fout.name) + ... ) ... print(fout.read().strip()) : N = 3 <1/3> <4/6> <7/9> """ - # Conversion to a C-contiguous array needs to be done here and not in put_matrix - # because we need to maintain a reference to the copy while it is being used by - # the C API. Otherwise, the array would be garbage collected and the memory - # freed. Creating it in this context manager guarantees that the copy will be - # around until the virtual file is closed. The conversion is implicit in - # vectors_to_arrays. + # Conversion to a C-contiguous array needs to be done here and not in + # put_matrix because we need to maintain a reference to the copy while + # it is being used by the C API. Otherwise, the array would be garbage + # collected and the memory freed. Creating it in this context manager + # guarantees that the copy will be around until the virtual file is + # closed. The conversion is implicit in vectors_to_arrays. arrays = vectors_to_arrays(vectors) columns = len(arrays) @@ -1073,25 +1089,27 @@ def virtualfile_from_matrix(self, matrix): """ Store a 2d array as a table inside a virtual file. - Use the virtual file name to pass in the data in your matrix to a GMT module. + Use the virtual file name to pass in the data in your matrix to a GMT + module. - Context manager (use in a ``with`` block). Yields the virtual file name that you - can pass as an argument to a GMT module call. Closes the virtual file upon exit - of the ``with`` block. + Context manager (use in a ``with`` block). Yields the virtual file name + that you can pass as an argument to a GMT module call. Closes the + virtual file upon exit of the ``with`` block. - The virtual file will contain the array as a ``GMT_MATRIX`` pretending to be a - ``GMT_DATASET``. + The virtual file will contain the array as a ``GMT_MATRIX`` pretending + to be a ``GMT_DATASET``. - **Not meant for creating ``GMT_GRID``**. The grid requires more metadata than - just the data matrix. Use :meth:`~gmt.clib.Session.virtualfile_from_grid` - instead. + **Not meant for creating ``GMT_GRID``**. The grid requires more + metadata than just the data matrix. Use + :meth:`~gmt.clib.Session.virtualfile_from_grid` instead. - Use this instead of creating the data container and virtual file by hand with - :meth:`~gmt.clib.Session.create_data`, :meth:`~gmt.clib.Session.put_matrix`, and + Use this instead of creating the data container and virtual file by + hand with :meth:`~gmt.clib.Session.create_data`, + :meth:`~gmt.clib.Session.put_matrix`, and :meth:`~gmt.clib.Session.open_virtual_file` - The matrix must be C contiguous in memory. If it is not (e.g., it is a slice of - a larger array), the array will be copied to make sure it is. + The matrix must be C contiguous in memory. If it is not (e.g., it is a + slice of a larger array), the array will be copied to make sure it is. Parameters ---------- @@ -1101,7 +1119,8 @@ def virtualfile_from_matrix(self, matrix): Yields ------ fname : str - The name of virtual file. Pass this as a file name argument to a GMT module. + The name of virtual file. Pass this as a file name argument to a + GMT module. Examples -------- @@ -1118,16 +1137,19 @@ def virtualfile_from_matrix(self, matrix): ... with ses.virtualfile_from_matrix(data) as fin: ... # Send the output to a file so that we can read it ... with GMTTempFile() as fout: - ... ses.call_module('info', '{} ->{}'.format(fin, fout.name)) + ... ses.call_module( + ... 'info', '{} ->{}'.format(fin, fout.name) + ... ) ... print(fout.read().strip()) : N = 4 <0/9> <1/10> <2/11> """ - # Conversion to a C-contiguous array needs to be done here and not in put_matrix - # because we need to maintain a reference to the copy while it is being used by - # the C API. Otherwise, the array would be garbage collected and the memory - # freed. Creating it in this context manager guarantees that the copy will be - # around until the virtual file is closed. + # Conversion to a C-contiguous array needs to be done here and not in + # put_matrix because we need to maintain a reference to the copy while + # it is being used by the C API. Otherwise, the array would be garbage + # collected and the memory freed. Creating it in this context manager + # guarantees that the copy will be around until the virtual file is + # closed. matrix = as_c_contiguous(matrix) rows, columns = matrix.shape @@ -1148,21 +1170,24 @@ def virtualfile_from_grid(self, grid): """ Store a grid in a virtual file. - Use the virtual file name to pass in the data in your grid to a GMT module. - Grids must be :class:`xarray.DataArray` instances. + Use the virtual file name to pass in the data in your grid to a GMT + module. Grids must be :class:`xarray.DataArray` instances. - Context manager (use in a ``with`` block). Yields the virtual file name that you - can pass as an argument to a GMT module call. Closes the virtual file upon exit - of the ``with`` block. + Context manager (use in a ``with`` block). Yields the virtual file name + that you can pass as an argument to a GMT module call. Closes the + virtual file upon exit of the ``with`` block. - The virtual file will contain the grid as a ``GMT_MATRIX`` with extra metadata. + The virtual file will contain the grid as a ``GMT_MATRIX`` with extra + metadata. - Use this instead of creating a data container and virtual file by hand with - :meth:`~gmt.clib.Session.create_data`, :meth:`~gmt.clib.Session.put_matrix`, and + Use this instead of creating a data container and virtual file by hand + with :meth:`~gmt.clib.Session.create_data`, + :meth:`~gmt.clib.Session.put_matrix`, and :meth:`~gmt.clib.Session.open_virtual_file` - The grid data matrix must be C contiguous in memory. If it is not (e.g., it is a - slice of a larger array), the array will be copied to make sure it is. + The grid data matrix must be C contiguous in memory. If it is not + (e.g., it is a slice of a larger array), the array will be copied to + make sure it is. Parameters ---------- @@ -1172,7 +1197,8 @@ def virtualfile_from_grid(self, grid): Yields ------ fname : str - The name of virtual file. Pass this as a file name argument to a GMT module. + The name of virtual file. Pass this as a file name argument to a + GMT module. Examples -------- @@ -1199,12 +1225,12 @@ def virtualfile_from_grid(self, grid): >>> # The output is: w e s n z0 z1 dx dy n_columns n_rows """ - # Conversion to a C-contiguous array needs to be done here and not in put_matrix - # because we need to maintain a reference to the copy while it is being used by - # the C API. Otherwise, the array would be garbage collected and the memory - # freed. Creating it in this context manager guarantees that the copy will be - # around until the virtual file is closed. The conversion is implicit in - # dataarray_to_matrix. + # Conversion to a C-contiguous array needs to be done here and not in + # put_matrix because we need to maintain a reference to the copy while + # it is being used by the C API. Otherwise, the array would be garbage + # collected and the memory freed. Creating it in this context manager + # guarantees that the copy will be around until the virtual file is + # closed. The conversion is implicit in dataarray_to_matrix. matrix, region, inc = dataarray_to_matrix(grid) family = "GMT_IS_GRID|GMT_VIA_MATRIX" geometry = "GMT_IS_SURFACE" diff --git a/pygmt/datasets/earth_relief.py b/pygmt/datasets/earth_relief.py index d5dbb1d3c40..aeca5d9c872 100644 --- a/pygmt/datasets/earth_relief.py +++ b/pygmt/datasets/earth_relief.py @@ -43,8 +43,9 @@ def load_earth_relief(resolution="60m"): grid.attrs["units"] = "meters" grid.attrs["vertical_datum"] = "EMG96" grid.attrs["horizontal_datum"] = "WGS84" - # Remove the actual range because it gets outdated when indexing the grid, which - # causes problems when exporting it to netCDF for usage on the command-line. + # Remove the actual range because it gets outdated when indexing the grid, + # which causes problems when exporting it to netCDF for usage on the + # command-line. grid.attrs.pop("actual_range") for coord in grid.coords: grid[coord].attrs.pop("actual_range") diff --git a/pygmt/datasets/tutorial.py b/pygmt/datasets/tutorial.py index bee3c18609d..77f7bbbd12d 100644 --- a/pygmt/datasets/tutorial.py +++ b/pygmt/datasets/tutorial.py @@ -73,8 +73,9 @@ def load_usgs_quakes(): Returns ------- - data : pandas.Dataframe - The data table. Use ``print(data.describe())`` to see the available columns. + data : pandas.Dataframe + The data table. Use ``print(data.describe())`` to see the available + columns. """ fname = which("@usgs_quakes_22.txt", download="c") diff --git a/pygmt/exceptions.py b/pygmt/exceptions.py index 4f74c61716f..d5b2c9584ef 100644 --- a/pygmt/exceptions.py +++ b/pygmt/exceptions.py @@ -1,7 +1,7 @@ # pylint: disable=missing-docstring # -# Custom exception types used throughout the library. All exceptions derive from -# GMTError. +# Custom exception types used throughout the library. All exceptions derive +# from GMTError. class GMTError(Exception): diff --git a/pygmt/figure.py b/pygmt/figure.py index eb00a27e698..3c867137646 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -33,8 +33,8 @@ class Figure(BasePlotting): A GMT figure to handle all plotting. Use the plotting methods of this class to add elements to the figure. You - can preview the figure using :meth:`pygmt.Figure.show` and save the figure to - a file using :meth:`pygmt.Figure.savefig`. + can preview the figure using :meth:`pygmt.Figure.show` and save the figure + to a file using :meth:`pygmt.Figure.savefig`. Unlike traditional GMT figures, no figure file is generated until you call :meth:`pygmt.Figure.savefig` or :meth:`pygmt.Figure.psconvert`. @@ -80,8 +80,8 @@ def _activate_figure(self): Unlike the command-line version (``gmt figure``), this method does not trigger the generation of a figure file. An explicit call to - :meth:`pygmt.Figure.savefig` or :meth:`pygmt.Figure.psconvert` must be made - in order to get a file. + :meth:`pygmt.Figure.savefig` or :meth:`pygmt.Figure.psconvert` must be + made in order to get a file. """ # Passing format '-' tells pygmt.end to not produce any files. fmt = "-" @@ -257,8 +257,8 @@ def show(self, dpi=300, width=500, method="static"): Only if ``method != 'external'``. """ - # Module level variable to know which figures had their show method called. - # Needed for the sphinx-gallery scraper. + # Module level variable to know which figures had their show method + # called. Needed for the sphinx-gallery scraper. SHOWED_FIGURES.append(self) if method not in ["static", "external"]: @@ -288,16 +288,18 @@ def shift_origin(self, xshift=None, yshift=None): """ Shift plot origin in x and/or y directions. - This method shifts plot origin relative to the current origin by (*xshift*,*yshift*) - and optionally append the length unit (**c**, **i**, or **p**). + This method shifts plot origin relative to the current origin by + (*xshift*,*yshift*) and optionally append the length unit (**c**, + **i**, or **p**). - Prepend **a** to shift the origin back to the original position - after plotting, prepend **c** to center the plot on the center of the - paper (optionally add shift), prepend **f** to shift the origin relative - to the fixed lower left corner of the page, or prepend **r** [Default] to + Prepend **a** to shift the origin back to the original position after + plotting, prepend **c** to center the plot on the center of the paper + (optionally add shift), prepend **f** to shift the origin relative to + the fixed lower left corner of the page, or prepend **r** [Default] to move the origin relative to its current location. - Detailed usage at :gmt-docs:`GMT_Docs.html#plot-positioning-and-layout-the-x-y-options` + Detailed usage at + :gmt-docs:`GMT_Docs.html#plot-positioning-and-layout-the-x-y-options` Parameters ---------- diff --git a/pygmt/gridding.py b/pygmt/gridding.py index ed0da5b9c38..c5ad7fac0a3 100644 --- a/pygmt/gridding.py +++ b/pygmt/gridding.py @@ -23,12 +23,13 @@ def surface(x=None, y=None, z=None, data=None, **kwargs): """ Grids table data using adjustable tension continuous curvature splines. - Surface reads randomly-spaced (x,y,z) triples and produces gridded values z(x,y) - by solving: + Surface reads randomly-spaced (x,y,z) triples and produces gridded values + z(x,y) by solving: (1 - T) * L (L (z)) + T * L (z) = 0 - where T is a tension factor between 0 and 1, and L indicates the Laplacian operator. + where T is a tension factor between 0 and 1, and L indicates the Laplacian + operator. Takes a matrix, xyz triples, or a file name as input. diff --git a/pygmt/helpers/decorators.py b/pygmt/helpers/decorators.py index 4465045c489..32c41cf619e 100644 --- a/pygmt/helpers/decorators.py +++ b/pygmt/helpers/decorators.py @@ -221,7 +221,9 @@ def kwargs_to_strings(convert_bools=True, **conversions): Examples -------- - >>> @kwargs_to_strings(R='sequence', i='sequence_comma', files='sequence_space') + >>> @kwargs_to_strings( + ... R='sequence', i='sequence_comma', files='sequence_space' + ... ) ... def module(*args, **kwargs): ... "A module that prints the arguments it received" ... print('{', end='') diff --git a/pygmt/helpers/utils.py b/pygmt/helpers/utils.py index e753223f974..1a98d45682a 100644 --- a/pygmt/helpers/utils.py +++ b/pygmt/helpers/utils.py @@ -50,22 +50,6 @@ def data_kind(data, x=None, y=None, z=None): 'matrix' >>> data_kind(data='my-data-file.txt', x=None, y=None) 'file' - >>> data_kind(data=None, x=None, y=None) - Traceback (most recent call last): - ... - pygmt.exceptions.GMTInvalidInput: No input data provided. - >>> data_kind(data='data.txt', x=np.array([1, 2]), y=np.array([4, 5])) - Traceback (most recent call last): - ... - pygmt.exceptions.GMTInvalidInput: Too much data. Use either data or x and y. - >>> data_kind(data='data.txt', x=np.array([1, 2]), y=None) - Traceback (most recent call last): - ... - pygmt.exceptions.GMTInvalidInput: Too much data. Use either data or x and y. - >>> data_kind(data=None, x=np.array([1, 2]), y=None) - Traceback (most recent call last): - ... - pygmt.exceptions.GMTInvalidInput: Must provided both x and y. """ if data is None and x is None and y is None: diff --git a/pygmt/mathops.py b/pygmt/mathops.py index dab216a0cb0..5649ea1cfcb 100644 --- a/pygmt/mathops.py +++ b/pygmt/mathops.py @@ -18,39 +18,42 @@ def makecpt(**kwargs): Parameters ---------- cmap (C) : str - Selects the master color palette table (CPT) to use in the interpolation. - Full list of built-in color palette tables can be found at - :gmt-docs:`cookbook/cpts.html#built-in-color-palette-tables-cpt`. + Selects the master color palette table (CPT) to use in the + interpolation. Full list of built-in color palette tables can be found + at :gmt-docs:`cookbook/cpts.html#built-in-color-palette-tables-cpt`. series (T) : list or str - ``[min/max/inc[+b|l|n]|file|list]``. - Defines the range of the new CPT by giving the lowest and highest z-value (and - optionally an interval). If this is not given, the existing range in the master - CPT will be used intact. + ``[min/max/inc[+b|l|n]|file|list]``. Defines the range of the new CPT + by giving the lowest and highest z-value (and optionally an interval). + If this is not given, the existing range in the master CPT will be used + intact. truncate (G) : list or str - ``zlo/zhi``. - Truncate the incoming CPT so that the lowest and highest z-levels are to zlo and - zhi. If one of these equal NaN then we leave that end of the CPT alone. The - truncation takes place before any resampling. See also + ``zlo/zhi``. Truncate the incoming CPT so that the lowest and highest + z-levels are to zlo and zhi. If one of these equal NaN then we leave + that end of the CPT alone. The truncation takes place before any + resampling. See also :gmt-docs:`cookbook/features.html#manipulating-cpts`. output (H) : str - Optional. The file name with extension .cpt to store the generated CPT file. - If not given or False (default), saves the CPT as the session current CPT. + Optional. The file name with extension .cpt to store the generated CPT + file. If not given or False (default), saves the CPT as the session + current CPT. reverse (I) : str - Set this to True or c [Default] to reverse the sense of color progression in the - master CPT. Set this to z to reverse the sign of z-values in the color table. - Note that this change of z-direction happens before -G and -T values are used so - the latter must be compatible with the changed z-range. See also + Set this to True or c [Default] to reverse the sense of color + progression in the master CPT. Set this to z to reverse the sign of + z-values in the color table. Note that this change of z-direction + happens before -G and -T values are used so the latter must be + compatible with the changed z-range. See also :gmt-docs:`cookbook/features.html#manipulating-cpts`. continuous (Z) : bool - Creates a continuous CPT [Default is discontinuous, i.e., constant colors for - each interval]. This option has no effect when no -T is used, or when using - -Tz_min/z_max; in the first case the input CPT remains untouched, in the second - case it is only scaled to match the range z_min/z_max. + Creates a continuous CPT [Default is discontinuous, i.e., constant + colors for each interval]. This option has no effect when no -T is + used, or when using -Tz_min/z_max; in the first case the input CPT + remains untouched, in the second case it is only scaled to match the + range z_min/z_max. {aliases} """ diff --git a/pygmt/session_management.py b/pygmt/session_management.py index 82f48a5806e..cafd306e120 100644 --- a/pygmt/session_management.py +++ b/pygmt/session_management.py @@ -11,7 +11,6 @@ def begin(): Used in combination with :func:`pygmt.end`. Only meant to be used once for creating the global session. - """ prefix = "pygmt-session" with Session() as lib: @@ -22,11 +21,10 @@ def end(): """ Terminate GMT modern mode session and optionally produce the figure files. - 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 + 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. - """ with Session() as lib: lib.call_module("end", "") diff --git a/pygmt/sphinx_gallery.py b/pygmt/sphinx_gallery.py index c1252298a2b..3de8300a0bd 100644 --- a/pygmt/sphinx_gallery.py +++ b/pygmt/sphinx_gallery.py @@ -15,13 +15,14 @@ class PyGMTScraper: # pylint: disable=too-few-public-methods Used by sphinx-gallery to generate the plots from the code in the examples. - Pass an instance of this class to ``sphinx_gallery_conf`` in your ``conf.py`` as the - ``"image_scrapers"`` argument. + Pass an instance of this class to ``sphinx_gallery_conf`` in your + ``conf.py`` as the ``"image_scrapers"`` argument. """ def __call__(self, block, block_vars, gallery_conf): """ - Called by sphinx-gallery to save the figures generated after running code. + Called by sphinx-gallery to save the figures generated after running + code. """ image_names = list() image_path_iterator = block_vars["image_path_iterator"] diff --git a/pygmt/tests/test_clib.py b/pygmt/tests/test_clib.py index e02d8ed5fd4..77a26de0a06 100644 --- a/pygmt/tests/test_clib.py +++ b/pygmt/tests/test_clib.py @@ -159,7 +159,7 @@ def test_create_session_fails(): with mock(ses, "GMT_Create_Session", returns=None): with pytest.raises(GMTCLibError): ses.create("test-session-name") - # Should also fail if trying to create a session before destroying the old one. + # Should fail if trying to create a session before destroying the old one. ses.create("test1") with pytest.raises(GMTCLibError): ses.create("test2") @@ -220,7 +220,7 @@ def test_call_module_error_message(): def test_method_no_session(): "Fails when not in a session" - # Create an instance of clib.Session without "with" so no session is created. + # Create an instance of Session without "with" so no session is created. lib = clib.Session() with pytest.raises(GMTCLibNoSessionError): lib.call_module("gmtdefaults", "") @@ -778,7 +778,7 @@ def test_dataarray_to_matrix_works(): def test_dataarray_to_matrix_negative_x_increment(): - "Check that dataarray_to_matrix returns correct output with flipped x dimensions" + "Check if dataarray_to_matrix returns correct output with flipped x" data = np.diag(v=np.arange(3)) x = np.linspace(start=4, stop=0, num=3) y = np.linspace(start=5, stop=9, num=3) @@ -791,7 +791,7 @@ def test_dataarray_to_matrix_negative_x_increment(): def test_dataarray_to_matrix_negative_y_increment(): - "Check that dataarray_to_matrix returns correct output with flipped y dimensions" + "Check that dataarray_to_matrix returns correct output with flipped y" data = np.diag(v=np.arange(3)) x = np.linspace(start=0, stop=4, num=3) y = np.linspace(start=9, stop=5, num=3) @@ -804,7 +804,7 @@ def test_dataarray_to_matrix_negative_y_increment(): def test_dataarray_to_matrix_negative_x_and_y_increment(): - "Check that dataarray_to_matrix returns correct output with flipped x/y dimensions" + "Check that dataarray_to_matrix returns correct output with flipped x/y" data = np.diag(v=np.arange(3)) x = np.linspace(start=4, stop=0, num=3) y = np.linspace(start=9, stop=5, num=3) diff --git a/pygmt/tests/test_colorbar.py b/pygmt/tests/test_colorbar.py index 5fea02100db..eb4f5155170 100644 --- a/pygmt/tests/test_colorbar.py +++ b/pygmt/tests/test_colorbar.py @@ -19,7 +19,7 @@ def test_colorbar_using_paper_coordinates(): @pytest.mark.mpl_image_compare def test_colorbar_using_paper_coordinates_horizontal(): """ - Create colorbar positioned at 0cm,0cm with length 2cm oriented horizontally. + Create colorbar positioned at 0cm,0cm with length 2cm oriented horizontally """ fig = Figure() fig.colorbar(cmap="rainbow", position="x0c/0c+w2c+h") @@ -40,7 +40,7 @@ def test_colorbar_positioned_using_map_coordinates(): @pytest.mark.mpl_image_compare def test_colorbar_positioned_using_justification_code(): """ - Create colorbar positioned at Top Center inside the map frame with length 2cm. + Create colorbar at Top Center inside the map frame with length 2cm. """ fig = Figure() fig.basemap(region=[2, 4, 6, 8], projection="t0/2c", frame=True) @@ -51,7 +51,7 @@ def test_colorbar_positioned_using_justification_code(): @pytest.mark.mpl_image_compare def test_colorbar_positioned_using_normalized_coords(): """ - Create colorbar positioned at normalized coordinates 0.75,0.25 with length 2cm. + Create colorbar at normalized coordinates 0.75,0.25 with length 2cm. """ fig = Figure() fig.basemap(region=[2, 4, 6, 8], projection="t0/2c", frame=True) @@ -92,7 +92,8 @@ def test_colorbar_box_with_fill(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_clearance(): """ - Create colorbar with box that has an x-clearance of 0.8cm and y-clearance of 0.4cm. + Create colorbar with box that has an x-clearance of 0.8cm and y-clearance + of 0.4cm. """ fig = Figure() fig.colorbar(cmap="rainbow", box="+c0.8c/0.4c+porange", position="x0c/0c+w1c/0.5c") @@ -102,8 +103,8 @@ def test_colorbar_box_with_clearance(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_secondary_border(): """ - Create colorbar with box that has a secondary, inner border in addition to the main - primary, outer border. + Create colorbar with box that has a secondary, inner border in addition to + the main primary, outer border. """ fig = Figure() fig.colorbar(cmap="rainbow", box="+porange+imagenta", position="x0c/0c+w1c/0.5c") diff --git a/pygmt/tests/test_helpers.py b/pygmt/tests/test_helpers.py index 3abaf7b456f..66b61456376 100644 --- a/pygmt/tests/test_helpers.py +++ b/pygmt/tests/test_helpers.py @@ -4,11 +4,29 @@ import os import pytest +import numpy as np -from ..helpers import kwargs_to_strings, GMTTempFile, unique_name +from ..helpers import kwargs_to_strings, GMTTempFile, unique_name, data_kind from ..exceptions import GMTInvalidInput +@pytest.mark.parametrize( + "data,x,y", + [ + (None, None, None), + ("data.txt", np.array([1, 2]), np.array([4, 5])), + ("data.txt", np.array([1, 2]), None), + ("data.txt", None, np.array([4, 5])), + (None, np.array([1, 2]), None), + (None, None, np.array([4, 5])), + ], +) +def test_data_kind_fails(data, x, y): + "Make sure data_kind raises exceptions when it should" + with pytest.raises(GMTInvalidInput): + data_kind(data=data, x=x, y=y) + + def test_unique_name(): "Make sure the names are really unique" names = [unique_name() for i in range(100)] diff --git a/pygmt/tests/test_makecpt.py b/pygmt/tests/test_makecpt.py index 7a557a79ace..48013f2b40e 100644 --- a/pygmt/tests/test_makecpt.py +++ b/pygmt/tests/test_makecpt.py @@ -66,7 +66,8 @@ def test_makecpt_to_plot_grid(grid): @pytest.mark.mpl_image_compare def test_makecpt_to_plot_grid_scaled_with_series(grid): """ - Use static color palette table scaled to a min/max series to change color of grid + Use static color palette table scaled to a min/max series to change color + of grid """ fig = Figure() makecpt(cmap="oleron", series="-4500/4500") @@ -157,7 +158,8 @@ def test_makecpt_reverse_zsign_only(grid): @pytest.mark.mpl_image_compare def test_makecpt_reverse_color_and_zsign(grid): """ - Use static color palette table with both its colors and z-value sign reversed + Use static color palette table with both its colors and z-value sign + reversed """ fig = Figure() makecpt(cmap="earth", reverse="cz") @@ -168,8 +170,8 @@ def test_makecpt_reverse_color_and_zsign(grid): @pytest.mark.mpl_image_compare def test_makecpt_continuous(grid): """ - Use static color palette table that is continuous from blue to white and scaled from - -4500 to 4500m. + Use static color palette table that is continuous from blue to white and + scaled from -4500 to 4500m. """ fig = Figure() makecpt(cmap="blue,white", continuous=True, series="-4500,4500") diff --git a/pygmt/tests/test_surface.py b/pygmt/tests/test_surface.py index 9af4f3f5bca..8cba271f7b5 100644 --- a/pygmt/tests/test_surface.py +++ b/pygmt/tests/test_surface.py @@ -99,7 +99,8 @@ def test_surface_with_outfile_param(): def test_surface_short_aliases(): """ - Run surface using short aliases -I for spacing, -R for region, -G for outfile + Run surface using short aliases -I for spacing, -R for region, -G for + outfile """ ship_data = load_sample_bathymetry() data = ship_data.values # convert pandas.DataFrame to numpy.ndarray diff --git a/pygmt/tests/test_text.py b/pygmt/tests/test_text.py index 4eb4c41ed4c..fb3f54d9789 100644 --- a/pygmt/tests/test_text.py +++ b/pygmt/tests/test_text.py @@ -158,8 +158,9 @@ def test_text_justify_bottom_right_and_top_left(region, projection): @pytest.mark.mpl_image_compare def test_text_justify_parsed_from_textfile(): """ - Print text justified based on a column from textfile, using justify=True boolean - operation. Loosely based on "All great-circle paths lead to Rome" gallery example at + Print text justified based on a column from textfile, using justify=True + boolean operation. Loosely based on "All great-circle paths lead to Rome" + gallery example at https://gmt.soest.hawaii.edu/doc/latest/gallery/ex23.html """ fig = Figure() diff --git a/setup.cfg b/setup.cfg index 9abe0a83abe..d607b9e76fd 100644 --- a/setup.cfg +++ b/setup.cfg @@ -8,6 +8,10 @@ tag_prefix = '' [flake8] ignore = E203, E266, E501, W503, F401, E741 max-line-length = 88 +#max-complexity = 10 +max-doc-length = 79 +exclude = + pygmt/_version.py [tool:pytest] markers =