Coverage for larch/math/gridxyz.py: 28%

36 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-10-16 21:04 +0000

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 

8 

9import warnings 

10import numpy as np 

11 

12# suppress warnings 

13try: 

14 import numexpr 

15except ImportError: 

16 pass 

17 

18from larch.utils.logging import getLogger 

19 

20_logger = getLogger("gridxyz") 

21 

22### GLOBAL VARIABLES ### 

23MODNAME = "_math" 

24 

25 

26def gridxyz(xcol, ycol, zcol, xystep=None, lib="scipy", method="linear"): 

27 """Grid (X, Y, Z) 1D data on a 2D regular mesh 

28 

29 Parameters 

30 ---------- 

31 xcol, ycol, zcol : numpy.ndarray 

32 1D arrays representing the map (z is the signal intensity) 

33 

34 xystep : float or None (optional) 

35 the step size of the XY grid, if None -> 0.1 

36 

37 lib : str, optional ["scipy"] 

38 library used for griddata 

39 - scipy 

40 - matplotlib 

41 

42 method : str, optional ["cubic"] 

43 interpolation method 

44 - nearest 

45 - linear 

46 - cubic 

47 

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 

53 

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 

76 

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 

82 

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 ) 

91 

92 

93 return xgrid, ygrid, zz 

94 

95 

96if __name__ == "__main__": 

97 pass