def test_args_in_kwargs(): """ Test that args_in_kwargs function returns correct Boolean responses. """ kwargs = {"A": 1, "B": 2, "C": 3} # Passing list of arguments with passing values in the beginning passing_args_1 = ["B", "C", "D"] assert args_in_kwargs(args=passing_args_1, kwargs=kwargs) # Passing list of arguments that starts with failing arguments passing_args_2 = ["D", "X", "C"] assert args_in_kwargs(args=passing_args_2, kwargs=kwargs) # Failing list of arguments failing_args = ["D", "E", "F"] assert not args_in_kwargs(args=failing_args, kwargs=kwargs)
def basemap(self, **kwargs): r""" Plot base maps and frames for the figure. Creates a basic or fancy basemap with axes, fill, and titles. Several map projections are available, and the user may specify separate tick-mark intervals for boundary annotation, ticking, and [optionally] gridlines. A simple map scale or directional rose may also be plotted. At least one of the parameters ``frame``, ``map_scale``, ``rose`` or ``compass`` must be specified. Full option list at :gmt-docs:`basemap.html` {aliases} Parameters ---------- {J} zscale/zsize : float or str Set z-axis scaling or z-axis size. {R} *Required if this is the first plot command.* {B} map_scale : str [**g**\|\ **j**\|\ **J**\|\ **n**\|\ **x**]\ *refpoint*\ **+w**\ *length*. Draws a simple map scale centered on the reference point specified. rose : str Draws a map directional rose on the map at the location defined by the reference and anchor points. compass : str Draws a map magnetic rose on the map at the location defined by the reference and anchor points {U} {V} {XY} {c} {f} {p} {t} """ kwargs = self._preprocess(**kwargs) # pylint: disable=protected-access if not args_in_kwargs(args=["B", "L", "Td", "Tm", "c"], kwargs=kwargs): raise GMTInvalidInput( "At least one of frame, map_scale, compass, rose, or panel must be specified." ) with Session() as lib: lib.call_module("basemap", build_arg_string(kwargs))
def grdgradient(grid, **kwargs): r""" Compute the directional derivative of the vector gradient of the data. Can accept ``azimuth``, ``direction``, and ``radiance`` input to create the resulting gradient. Full option list at :gmt-docs:`grdgradient.html` {aliases} Parameters ---------- grid : str or xarray.DataArray The file name of the input grid or the grid loaded as a DataArray. outgrid : str or None The name of the output netCDF file with extension .nc to store the grid in. azimuth : int or float or str or list *azim*\ [/*azim2*]. Azimuthal direction for a directional derivative; *azim* is the angle in the x,y plane measured in degrees positive clockwise from north (the +y direction) toward east (the +x direction). The negative of the directional derivative, :math:`-(\frac{{dz}}{{dx}}\sin(\mbox{{azim}}) + \ \frac{{dz}}{{dy}}\cos(\mbox{{azim}}))`, is found; negation yields positive values when the slope of :math:`z(x,y)` is downhill in the *azim* direction, the correct sense for shading the illumination of an image by a light source above the x,y plane shining from the *azim* direction. Optionally, supply two azimuths, *azim*/*azim2*, in which case the gradients in each of these directions are calculated and the one larger in magnitude is retained; this is useful for illuminating data with two directions of lineated structures, e.g., *0*/*270* illuminates from the north (top) and west (left). Finally, if *azim* is a file it must be a grid of the same domain, spacing and registration as *grid* that will update the azimuth at each output node when computing the directional derivatives. direction : str [**a**][**c**][**o**][**n**]. Find the direction of the positive (up-slope) gradient of the data. The following options are supported: - **a** - Find the aspect (i.e., the down-slope direction) - **c** - Use the conventional Cartesian angles measured counterclockwise from the positive x (east) direction. - **o** - Report orientations (0-180) rather than directions (0-360). - **n** - Add 90 degrees to all angles (e.g., to give local strikes of the surface). radiance : str or list [**m**\|\ **s**\|\ **p**]\ *azim/elev*\ [**+a**\ *ambient*][**+d**\ *diffuse*][**+p**\ *specular*][**+s**\ *shine*]. Compute Lambertian radiance appropriate to use with :doc:`pygmt.Figure.grdimage` and :doc:`pygmt.Figure.grdview`. The Lambertian Reflection assumes an ideal surface that reflects all the light that strikes it and the surface appears equally bright from all viewing directions. Here, *azim* and *elev* are the azimuth and elevation of the light vector. Optionally, supply *ambient* [0.55], *diffuse* [0.6], *specular* [0.4], or *shine* [10], which are parameters that control the reflectance properties of the surface. Default values are given in the brackets. Use **s** for a simpler Lambertian algorithm. Note that with this form you only have to provide azimuth and elevation. Alternatively, use **p** for the Peucker piecewise linear approximation (simpler but faster algorithm; in this case *azim* and *elev* are hardwired to 315 and 45 degrees. This means that even if you provide other values they will be ignored.). normalize : str or bool [**e**\|\ **t**][*amp*][**+a**\ *ambient*][**+s**\ *sigma*]\ [**+o**\ *offset*]. The actual gradients :math:`g` are offset and scaled to produce normalized gradients :math:`g_n` with a maximum output magnitude of *amp*. If *amp* is not given, default *amp* = 1. If *offset* is not given, it is set to the average of :math:`g`. The following forms are supported: - **True** - Normalize using :math:`g_n = \mbox{{amp}}\ (\frac{{g - \mbox{{offset}}}}{{max(|g - \mbox{{offset}}|)}})` - **e** - Normalize using a cumulative Laplace distribution yielding: :math:`g_n = \mbox{{amp}}(1 - \ \exp{{(\sqrt{{2}}\frac{{g - \mbox{{offset}}}}{{\sigma}}))}}`, where :math:`\sigma` is estimated using the L1 norm of :math:`(g - \mbox{{offset}})` if it is not given. - **t** - Normalize using a cumulative Cauchy distribution yielding: :math:`g_n = \ \frac{{2(\mbox{{amp}})}}{{\pi}}(\tan^{{-1}}(\frac{{g - \ \mbox{{offset}}}}{{\sigma}}))` where :math:`\sigma` is estimated using the L2 norm of :math:`(g - \mbox{{offset}})` if it is not given. As a final option, you may add **+a**\ *ambient* to add *ambient* to all nodes after gradient calculations are completed. tiles : str **c**\|\ **r**\|\ **R**. Controls how normalization via ``normalize`` is carried out. When multiple grids should be normalized the same way (i.e., with the same *offset* and/or *sigma*), we must pass these values via ``normalize``. However, this is inconvenient if we compute these values from a grid. Use **c** to save the results of *offset* and *sigma* to a statistics file; if grid output is not needed for this run then do not specify ``outgrid``. For subsequent runs, just use **r** to read these values. Using **R** will read then delete the statistics file. {R} slope_file : str Name of output grid file with scalar magnitudes of gradient vectors. Requires ``direction`` but makes ``outgrid`` optional. {V} {f} {n} Returns ------- ret: xarray.DataArray or None Return type depends on whether the ``outgrid`` parameter is set: - :class:`xarray.DataArray` if ``outgrid`` is not set - None if ``outgrid`` is set (grid output will be stored in file set by ``outgrid``) """ with GMTTempFile(suffix=".nc") as tmpfile: if "Q" in kwargs and "N" not in kwargs: raise GMTInvalidInput( """Must specify normalize if tiles is specified.""") if not args_in_kwargs(args=["A", "D", "E"], kwargs=kwargs): raise GMTInvalidInput( """At least one of the following parameters must be specified: azimuth, direction, or radiance""") with Session() as lib: file_context = lib.virtualfile_from_data(check_kind="raster", data=grid) with file_context as infile: if "G" not in kwargs: # if outgrid is unset, output to tempfile kwargs.update({"G": tmpfile.name}) outgrid = kwargs["G"] arg_str = " ".join([infile, build_arg_string(kwargs)]) lib.call_module("grdgradient", arg_str) return load_dataarray(outgrid) if outgrid == tmpfile.name else None
def coast(self, **kwargs): r""" Plot continents, shorelines, rivers, and borders on maps Plots grayshaded, colored, or textured land-masses [or water-masses] on maps and [optionally] draws coastlines, rivers, and political boundaries. Alternatively, it can (1) issue clip paths that will contain all land or all water areas, or (2) dump the data to an ASCII table. The data files come in 5 different resolutions: (**f**)ull, (**h**)igh, (**i**)ntermediate, (**l**)ow, and (**c**)rude. The full resolution files amount to more than 55 Mb of data and provide great detail; for maps of larger geographical extent it is more economical to use one of the other resolutions. If the user selects to paint the land-areas and does not specify fill of water-areas then the latter will be transparent (i.e., earlier graphics drawn in those areas will not be overwritten). Likewise, if the water-areas are painted and no land fill is set then the land-areas will be transparent. A map projection must be supplied. Full option list at :gmt-docs:`coast.html` {aliases} Parameters ---------- {J} {R} area_thresh : int, float, or str *min_area*\ [/*min_level*/*max_level*][**+a**\[**g**\|\ **i**]\ [**s**\|\ **S**][**+l**\|\ **r**][**+p**\ *percent*]. Features with an area smaller than *min_area* in km\ :sup:`2` or of hierarchical level that is lower than *min_level* or higher than *max_level* will not be plotted. {B} lakes : str or list *fill*\ [**+l**\|\ **+r**]. Set the shade, color, or pattern for lakes and river-lakes. The default is the fill chosen for wet areas set by the ``water`` argument. Optionally, specify separate fills by appending **+l** for lakes or **+r** for river-lakes, and passing multiple strings in a list. resolution : str **f**\|\ **h**\|\ **i**\|\ **l**\|\ **c**. Selects the resolution of the data set to: (**f**\ )ull, (**h**\ )igh, (**i**\ )ntermediate, (**l**\ )ow, and (**c**\ )rude. land : str Select filling or clipping of “dry” areas. rivers : int or str or list *river*\ [/*pen*]. Draw rivers. Specify the type of rivers and [optionally] append pen attributes [Default pen is width = default, color = black, style = solid]. Choose from the list of river types below; pass a list to ``rivers`` to use multiple arguments. 0 = Double-lined rivers (river-lakes) 1 = Permanent major rivers 2 = Additional major rivers 3 = Additional rivers 4 = Minor rivers 5 = Intermittent rivers - major 6 = Intermittent rivers - additional 7 = Intermittent rivers - minor 8 = Major canals 9 = Minor canals 10 = Irrigation canals You can also choose from several preconfigured river groups: a = All rivers and canals (0-10) A = All rivers and canals except river-lakes (1-10) r = All permanent rivers (0-4) R = All permanent rivers except river-lakes (1-4) i = All intermittent rivers (5-7) c = All canals (8-10) map_scale : str [**g**\|\ **j**\|\ **J**\|\ **n**\|\ **x**]\ *refpoint*\ **+w**\ *length*. Draws a simple map scale centered on the reference point specified. borders : int or str or list *border*\ [/*pen*]. Draw political boundaries. Specify the type of boundary and [optionally] append pen attributes [Default pen is width = default, color = black, style = solid]. Choose from the list of boundaries below. Pass a list to ``borders`` to use multiple arguments. 1 = National boundaries 2 = State boundaries within the Americas 3 = Marine boundaries a = All boundaries (1-3) water : str Select filling or clipping of “wet” areas. {U} shorelines : int or str or list [*level*\ /]\ *pen*. Draw shorelines [Default is no shorelines]. Append pen attributes [Default is width = default, color = black, style = solid] which apply to all four levels. To set the pen for a single level, pass a string with *level*\ /*pen*\ , where level is 1-4 and represent coastline, lakeshore, island-in-lake shore, and lake-in-island-in-lake shore. Pass a list of *level*\ /*pen* strings to ``shorelines`` to set multiple levels. When specific level pens are set, those not listed will not be drawn. dcw : str or list *code1,code2,…*\ [**+l**\|\ **L**\ ][**+g**\ *fill*\ ] [**+p**\ *pen*\ ][**+z**]. Select painting or dumping country polygons from the `Digital Chart of the World <https://en.wikipedia.org/wiki/Digital_Chart_of_the_World>`__. Append one or more comma-separated countries using the 2-character `ISO 3166-1 alpha-2 convention <https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2>`__. To select a state of a country (if available), append .\ *state*, (e.g, US.TX for Texas). To specify a whole continent, prepend **=** to any of the continent codes (e.g. =EU for Europe). Append **+p**\ *pen* to draw polygon outlines (default is no outline) and **+g**\ *fill* to fill them (default is no fill). Append **+l**\|\ **+L** to =\ *continent* to only list countries in that continent; repeat if more than one continent is requested. {XY} {c} {p} {t} {V} """ kwargs = self._preprocess(**kwargs) # pylint: disable=protected-access if not args_in_kwargs(args=["C", "G", "S", "I", "N", "E", "Q", "W"], kwargs=kwargs): raise GMTInvalidInput( """At least one of the following arguments must be specified: lakes, land, water, rivers, borders, dcw, Q, or shorelines""") with Session() as lib: lib.call_module("coast", build_arg_string(kwargs))
def grdgradient(grid, **kwargs): r""" Compute the directional derivative of the vector gradient of the data. Can accept ``azimuth``, ``direction``, and ``radiance`` input to create the resulting gradient. Full option list at :gmt-docs:`grdgradient.html` {aliases} Parameters ---------- grid : str or xarray.DataArray The file name of the input grid or the grid loaded as a DataArray. outgrid : str or None The name of the output netCDF file with extension .nc to store the grid in. azimuth : int or float or str or list *azim*\ [/*azim2*]. Azimuthal direction for a directional derivative; *azim* is the angle in the x,y plane measured in degrees positive clockwise from north (the +y direction) toward east (the +x direction). The negative of the directional derivative, -[dz/dx\*sin(*azim*) + dz/dy\*cos(\ *azim*)], is found; negation yields positive values when the slope of z(x,y) is downhill in the *azim* direction, the correct sense for shading the illumination of an image by a light source above the x,y plane shining from the *azim* direction. Optionally, supply two azimuths, *azim*/*azim2*, in which case the gradients in each of these directions are calculated and the one larger in magnitude is retained; this is useful for illuminating data with two directions of lineated structures, e.g., *0*/*270* illuminates from the north (top) and west (left). Finally, if *azim* is a file it must be a grid of the same domain, spacing and registration as *grid* that will update the azimuth at each output node when computing the directional derivatives. direction : str [**a**][**c**][**o**][**n**]. Find the direction of the positive (up-slope) gradient of the data. To instead find the aspect (the down-slope direction), use **a**. By default, directions are measured clockwise from north, as *azim* in ``azimuth``. Append **c** to use conventional Cartesian angles measured counterclockwise from the positive x (east) direction. Append **o** to report orientations (0-180) rather than directions (0-360). Append **n** to add 90 degrees to all angles (e.g., to give local strikes of the surface). radiance : str or list [**m**\|\ **s**\|\ **p**]\ *azim/elev*\ [**+a**\ *ambient*][**+d**\ *diffuse*][**+p**\ *specular*][**+s**\ *shine*]. Compute Lambertian radiance appropriate to use with ``grdimage`` and ``grdview``. The Lambertian Reflection assumes an ideal surface that reflects all the light that strikes it and the surface appears equally bright from all viewing directions. Here, *azim* and *elev* are the azimuth and elevation of the light vector. Optionally, supply *ambient* [0.55], *diffuse* [0.6], *specular* [0.4], or *shine* [10], which are parameters that control the reflectance properties of the surface. Default values are given in the brackets. Use **s** for a simpler Lambertian algorithm. Note that with this form you only have to provide azimuth and elevation. Alternatively, use **p** for the Peucker piecewise linear approximation (simpler but faster algorithm; in this case the *azim* and *elev* are hardwired to 315 and 45 degrees. This means that even if you provide other values they will be ignored.) {R} {V} {n} """ with GMTTempFile(suffix=".nc") as tmpfile: if not args_in_kwargs(args=["A", "D", "E"], kwargs=kwargs): raise GMTInvalidInput( """At least one of the following parameters must be specified: azimuth, direction, or radiance""" ) with Session() as lib: file_context = lib.virtualfile_from_data(check_kind="raster", data=grid) with file_context as infile: if "G" not in kwargs.keys(): # if outgrid is unset, output to tempfile kwargs.update({"G": tmpfile.name}) outgrid = kwargs["G"] arg_str = " ".join([infile, build_arg_string(kwargs)]) lib.call_module("grdgradient", arg_str) if outgrid == tmpfile.name: # if user did not set outgrid, return DataArray with xr.open_dataarray(outgrid) as dataarray: result = dataarray.load() _ = result.gmt # load GMTDataArray accessor information else: result = None # if user sets an outgrid, return None return result
def basemap(self, **kwargs): r""" Plot base maps and frames for the figure. Creates a basic or fancy basemap with axes, fill, and titles. Several map projections are available, and the user may specify separate tick-mark intervals for boundary annotation, ticking, and [optionally] gridlines. A simple map scale or directional rose may also be plotted. Full option list at :gmt-docs:`basemap.html` {aliases} Parameters ---------- {J} zscale/zsize : float or str Set z-axis scaling or z-axis size. {R} *Required if this is the first plot command.* {B} map_scale : str [**g**\|\ **j**\|\ **J**\|\ **n**\|\ **x**]\ *refpoint*\ **+w**\ *length*. Draws a simple map scale centered on the reference point specified. box : bool or str [**+c**\ *clearances*][**+g**\ *fill*][**+i**\ [[*gap*/]\ *pen*]]\ [**+p**\ [*pen*]][**+r**\ [*radius*]][**+s**\ [[*dx*/*dy*/][*shade*]]]. If set to ``True``, draws a rectangular border around the map scale or rose. Alternatively, specify a different pen with **+p**\ *pen*. Add **+g**\ *fill* to fill the scale panel [default is no fill]. Append **+c**\ *clearance* 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 :gmt-term:`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 [Default is 4p/-4p] and shade sets the fill style to use for shading [default is gray50]. rose : str Draws a map directional rose on the map at the location defined by the reference and anchor points. compass : str Draws a map magnetic rose on the map at the location defined by the reference and anchor points {U} {V} {XY} {c} {f} {p} {t} """ kwargs = self._preprocess(**kwargs) # pylint: disable=protected-access if not args_in_kwargs(args=["B", "L", "Td", "Tm", "c"], kwargs=kwargs): kwargs["B"] = True # Plotting frames if required arguments not given with Session() as lib: lib.call_module(module="basemap", args=build_arg_string(kwargs))