Coverage for /Users/Newville/Codes/xraylarch/larch/math/gridxyz.py: 30%
37 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-09 10:08 -0600
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-09 10:08 -0600
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""
4Utilities to work with 2D grids and interpolation
5=================================================
6"""
7from __future__ import division, print_function
9import warnings
10import numpy as np
12# suppress warnings
13try:
14 import numexpr
15except ImportError:
16 pass
18from larch.utils.logging import getLogger
20_logger = getLogger("gridxyz")
22### GLOBAL VARIABLES ###
23MODNAME = "_math"
26def gridxyz(xcol, ycol, zcol, xystep=None, lib="scipy", method="linear"):
27 """Grid (X, Y, Z) 1D data on a 2D regular mesh
29 Parameters
30 ----------
31 xcol, ycol, zcol : numpy.ndarray
32 1D arrays representing the map (z is the signal intensity)
34 xystep : float or None (optional)
35 the step size of the XY grid, if None -> 0.1
37 lib : str, optional ["scipy"]
38 library used for griddata
39 - scipy
40 - matplotlib
42 method : str, optional ["cubic"]
43 interpolation method
44 - nearest
45 - linear
46 - cubic
48 Returns
49 -------
50 xgrid, ygrid, zz : numpy.ndarray
51 xgrid, ygrid : 1D arrays giving abscissa and ordinate of the map
52 zz : 2D array with the gridded intensity map
54 See also
55 --------
56 - MultipleScanToMeshPlugin in PyMca
57 """
58 if xystep is None:
59 xystep = 0.1
60 _logger.warning(
61 "'xystep' not given: using a default value of {0}".format(xystep)
62 )
63 assert type(xystep) is float, "xystep should be float"
64 # create the XY meshgrid and interpolate the Z on the grid
65 nxpoints = int((xcol.max() - xcol.min()) / xystep)
66 nypoints = int((ycol.max() - ycol.min()) / xystep)
67 xgrid = np.linspace(xcol.min(), xcol.max(), num=nxpoints)
68 ygrid = np.linspace(ycol.min(), ycol.max(), num=nypoints)
69 xx, yy = np.meshgrid(xgrid, ygrid)
70 if "matplotlib" in lib.lower():
71 _logger.warning("matplotlib deprecated -> using scipy")
72 lib = "scipy"
73 if not "scipy" in lib.lower():
74 _logger.error("lib should be scipy")
75 return np.nan, np.nan, np.nan
77 try:
78 from scipy.interpolate import griddata
79 except ImportError:
80 _logger.error("Cannot load griddata from Scipy")
81 return np.nan, np.nan, np.nan
83 _logger.info("Gridding data with {0}/{1}...".format(lib, method))
84 zz = griddata(
85 (xcol, ycol),
86 zcol,
87 (xgrid[None, :], ygrid[:, None]),
88 method=method,
89 fill_value=np.nan,
90 )
93 return xgrid, ygrid, zz
96if __name__ == "__main__":
97 pass