text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(self, normalization=None, csphase=None, lmax=None): """ Return an SHMagCoeffs class instance with a different normalization convention. Usage ----- clm = x.convert([normalization, csphase, lmax]) Returns ------- clm : SHMagCoeffs class instance Parameters normalization : str, optional, default = x.normalization Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention for the output class: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. Description This method will return a new class instance of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention. A different maximum spherical harmonic degree of the output coefficients can be specified, and if this maximum degree is smaller than the maximum degree of the original class, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the original class, the coefficients of the new class will be zero padded. """
if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax # check argument consistency if type(normalization) != str: raise ValueError('normalization must be a string. ' 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "normalization must be '4pi', 'ortho', 'schmidt', or " "'unnorm'. Provided value was {:s}" .format(repr(normalization))) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase))) if self.errors is not None: coeffs, errors = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHMagCoeffs.from_array( coeffs, r0=self.r0, errors=errors, normalization=normalization.lower(), csphase=csphase, copy=False) else: coeffs = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHMagCoeffs.from_array( coeffs, r0=self.r0, normalization=normalization.lower(), csphase=csphase, copy=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad(self, lmax): """ Return an SHMagCoeffs class where the coefficients are zero padded or truncated to a different lmax. Usage ----- clm = x.pad(lmax) Returns ------- clm : SHMagCoeffs class instance Parameters lmax : int Maximum spherical harmonic degree to output. """
clm = self.copy() if lmax <= self.lmax: clm.coeffs = clm.coeffs[:, :lmax+1, :lmax+1] clm.mask = clm.mask[:, :lmax+1, :lmax+1] if self.errors is not None: clm.errors = clm.errors[:, :lmax+1, :lmax+1] else: clm.coeffs = _np.pad(clm.coeffs, ((0, 0), (0, lmax - self.lmax), (0, lmax - self.lmax)), 'constant') if self.errors is not None: clm.errors = _np.pad( clm.errors, ((0, 0), (0, lmax - self.lmax), (0, lmax - self.lmax)), 'constant') mask = _np.zeros((2, lmax + 1, lmax + 1), dtype=_np.bool) for l in _np.arange(lmax + 1): mask[:, l, :l + 1] = True mask[1, :, 0] = False clm.mask = mask clm.lmax = lmax return clm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_ref(self, r0=None, lmax=None): """ Return a new SHMagCoeffs class instance with a different reference r0. Usage ----- clm = x.change_ref([r0, lmax]) Returns ------- clm : SHMagCoeffs class instance. Parameters r0 : float, optional, default = self.r0 The reference radius of the spherical harmonic coefficients. lmax : int, optional, default = self.lmax Maximum spherical harmonic degree to output. Description This method returns a new class instance of the magnetic potential, but using a difference reference r0. When changing the reference radius r0, the spherical harmonic coefficients will be upward or downward continued under the assumption that the reference radius is exterior to the body. """
if lmax is None: lmax = self.lmax clm = self.pad(lmax) if r0 is not None and r0 != self.r0: for l in _np.arange(lmax+1): clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**(l+2) if self.errors is not None: clm.errors[:, l, :l+1] *= (self.r0 / r0)**(l+2) clm.r0 = r0 return clm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, a=None, f=None, lmax=None, lmax_calc=None, sampling=2): """ Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the magnetic field, the total magnetic intensity, and the magnetic potential, and return as a SHMagGrid class instance. Usage ----- mag = x.expand([a, f, lmax, lmax_calc, sampling]) Returns ------- mag : SHMagGrid class instance. Parameters a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree, which determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description This method will create 2-dimensional cylindrical maps of the three components of the magnetic field, the total field, and the magnetic potential, and return these as an SHMagGrid class instance. Each map is stored as an SHGrid class instance using Driscoll and Healy grids that are either equally sampled (n by n) or equally spaced (n by 2n) in latitude and longitude. All grids use geocentric coordinates, and the units are either in nT (for the magnetic field), or nT m (for the potential), The magnetic potential is given by V = r0 Sum_{l=1}^lmax (r0/r)^{l+1} Sum_{m=-l}^l g_{lm} Y_{lm} and the magnetic field is B = - Grad V. The coefficients are referenced to a radius r0, and the function is computed on a flattened ellipsoid with semi-major axis a (i.e., the mean equatorial radius) and flattening f. """
if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='schmidt', csphase=1) else: coeffs = self.to_array(normalization='schmidt', csphase=1) rad, theta, phi, total, pot = _MakeMagGridDH( coeffs, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHMagGrid(rad, theta, phi, total, pot, a, f, lmax, lmax_calc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tensor(self, a=None, f=None, lmax=None, lmax_calc=None, sampling=2): """ Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the magnetic field tensor in a local north-oriented reference frame, and return an SHMagTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHMagTensor class instance. Parameters a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description This method will create 2-dimensional cylindrical maps for the 9 components of the magnetic field tensor and return an SHMagTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The magnetic potential is defined as V = r0 Sum_{l=0}^lmax (r0/r)^(l+1) Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the vector magnetic field is B = - Grad V. The components of the tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of nT / m. References Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006. """
if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='schmidt', csphase=1) else: coeffs = self.to_array(normalization='schmidt', csphase=1) vxx, vyy, vzz, vxy, vxz, vyz = _MakeMagGradGridDH( coeffs, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHMagTensor(vxx, vyy, vzz, vxy, vxz, vyz, a, f, lmax, lmax_calc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legendre(lmax, z, normalization='4pi', csphase=1, cnorm=0, packed=False): """ Compute all the associated Legendre functions up to a maximum degree and order. Usage ----- plm = legendre (lmax, z, [normalization, csphase, cnorm, packed]) Returns ------- plm : float, dimension (lmax+1, lmax+1) or ((lmax+1)*(lmax+2)/2) An array of associated Legendre functions, plm[l, m], where l and m are the degree and order, respectively. If packed is True, the array is 1-dimensional with the index corresponding to l*(l+1)/2+m. Parameters lmax : integer The maximum degree of the associated Legendre functions to be computed. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. packed : optional, bool, default = False If True, return a 1-dimensional packed array with the index corresponding to l*(l+1)/2+m, where l and m are respectively the degree and order. Description legendre` will calculate all of the associated Legendre functions up to degree lmax for a given argument. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. `normalization` can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. By default, the routine will return a 2-dimensional array, p[l, m]. If the optional parameter `packed` is set to True, the output will instead be a 1-dimensional array where the indices correspond to `l*(l+1)/2+m`. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """
if lmax < 0: raise ValueError( "lmax must be greater or equal to 0. Input value was {:s}." .format(repr(lmax)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if cnorm != 0 and cnorm != 1: raise ValueError( "cnorm must be either 0 or 1. Input value was {:s}." .format(repr(cnorm)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 if normalization == '4pi': p = _PlmBar(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'ortho': p = _PlmON(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'schmidt': p = _PlmSchmidt(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'unnorm': p = _PLegendreA(lmax, z, csphase=csphase, cnorm=cnorm) if packed is True: return p else: plm = _np.zeros((lmax+1, lmax+1)) for l in range(lmax+1): for m in range(l+1): plm[l, m] = p[(l*(l+1))//2+m] return plm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legendre_lm(l, m, z, normalization='4pi', csphase=1, cnorm=0): """ Compute the associated Legendre function for a specific degree and order. Usage ----- plm = legendre_lm (l, m, z, [normalization, csphase, cnorm]) Returns ------- plm : float The associated Legendre functions for degree l and order m. Parameters l : integer The spherical harmonic degree. m : integer The spherical harmonic order. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. Description legendre_lm will calculate the associated Legendre function for a specific degree l and order m. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """
if l < 0: raise ValueError( "The degree l must be greater or equal to 0. Input value was {:s}." .format(repr(l)) ) if m < 0: raise ValueError( "The order m must be greater or equal to 0. Input value was {:s}." .format(repr(m)) ) if m > l: raise ValueError( "The order m must be less than or equal to the degree l. " + "Input values were l={:s} and m={:s}.".format(repr(l), repr(m)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if cnorm != 0 and cnorm != 1: raise ValueError( "cnorm must be either 0 or 1. Input value was {:s}." .format(repr(cnorm)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 if normalization == '4pi': p = _PlmBar(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'ortho': p = _PlmON(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'schmidt': p = _PlmSchmidt(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'unnorm': p = _PLegendreA(l, z, csphase=csphase, cnorm=cnorm) return p[(l*(l+1))//2+m]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iscomment(line): """ Determine if a line is a comment line. A valid line contains at least three words, with the first two being integers. Note that Python 2 and 3 deal with strings differently. """
if line.isspace(): return True elif len(line.split()) >= 3: try: # python 3 str if line.split()[0].isdecimal() and line.split()[1].isdecimal(): return False except: # python 2 str if (line.decode().split()[0].isdecimal() and line.split()[1].decode().isdecimal()): return False return True else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_f2pydoc(f2pydoc): """ this function replace all optional _d0 arguments with their default values in the function signature. These arguments are not intended to be used and signify merely the array dimensions of the associated argument. """
# ---- split f2py document in its parts # 0=Call Signature # 1=Parameters # 2=Other (optional) Parameters (only if present) # 3=Returns docparts = re.split('\n--', f2pydoc) if len(docparts) == 4: doc_has_optionals = True elif len(docparts) == 3: doc_has_optionals = False else: print('-- uninterpretable f2py documentation --') return f2pydoc # ---- replace arguments with _d suffix with empty string in ---- # ---- function signature (remove them): ---- docparts[0] = re.sub('[\[(,]\w+_d\d', '', docparts[0]) # ---- replace _d arguments of the return arrays with their default value: if doc_has_optionals: returnarray_dims = re.findall('[\[(,](\w+_d\d)', docparts[3]) for arg in returnarray_dims: searchpattern = arg + ' : input.*\n.*Default: (.*)\n' match = re.search(searchpattern, docparts[2]) if match: default = match.group(1) docparts[3] = re.sub(arg, default, docparts[3]) docparts[2] = re.sub(searchpattern, '', docparts[2]) # ---- remove all optional _d# from optional argument list: if doc_has_optionals: searchpattern = '\w+_d\d : input.*\n.*Default: (.*)\n' docparts[2] = re.sub(searchpattern, '', docparts[2]) # ---- combine doc parts to a single string processed_signature = '\n--'.join(docparts) return processed_signature
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_cap(cls, theta, lwin, clat=None, clon=None, nwin=None, theta_degrees=True, coord_degrees=True, dj_matrix=None, weights=None): """ Construct spherical cap localization windows. Usage ----- x = SHWindow.from_cap(theta, lwin, [clat, clon, nwin, theta_degrees, coord_degrees, dj_matrix, weights]) Returns ------- x : SHWindow class instance Parameters theta : float Angular radius of the spherical cap localization domain (default in degrees). lwin : int Spherical harmonic bandwidth of the localization windows. clat, clon : float, optional, default = None Latitude and longitude of the center of the rotated spherical cap localization windows (default in degrees). nwin : int, optional, default (lwin+1)**2 Number of localization windows. theta_degrees : bool, optional, default = True True if theta is in degrees. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. weights : ndarray, optional, default = None Taper weights used with the multitaper spectral analyses. """
if theta_degrees: tapers, eigenvalues, taper_order = _shtools.SHReturnTapers( _np.radians(theta), lwin) else: tapers, eigenvalues, taper_order = _shtools.SHReturnTapers( theta, lwin) return SHWindowCap(theta, tapers, eigenvalues, taper_order, clat, clon, nwin, theta_degrees, coord_degrees, dj_matrix, weights, copy=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_mask(cls, dh_mask, lwin, nwin=None, weights=None): """ Construct localization windows that are optimally concentrated within the region specified by a mask. Usage ----- x = SHWindow.from_mask(dh_mask, lwin, [nwin, weights]) Returns ------- x : SHWindow class instance Parameters dh_mask :ndarray, shape (nlat, nlon) A Driscoll and Healy (1994) sampled grid describing the concentration region R. All elements should either be 1 (for inside the concentration region) or 0 (for outside the concentration region). The grid must have dimensions nlon=nlat or nlon=2*nlat, where nlat is even. lwin : int The spherical harmonic bandwidth of the localization windows. nwin : int, optional, default = (lwin+1)**2 The number of best concentrated eigenvalues and eigenfunctions to return. weights ndarray, optional, default = None Taper weights used with the multitaper spectral analyses. """
if nwin is None: nwin = (lwin + 1)**2 else: if nwin > (lwin + 1)**2: raise ValueError('nwin must be less than or equal to ' + '(lwin + 1)**2. lwin = {:d} and nwin = {:d}' .format(lwin, nwin)) if dh_mask.shape[0] % 2 != 0: raise ValueError('The number of latitude bands in dh_mask ' + 'must be even. nlat = {:d}' .format(dh_mask.shape[0])) if dh_mask.shape[1] == dh_mask.shape[0]: _sampling = 1 elif dh_mask.shape[1] == 2 * dh_mask.shape[0]: _sampling = 2 else: raise ValueError('dh_mask must be dimensioned as (n, n) or ' + '(n, 2 * n). Input shape is ({:d}, {:d})' .format(dh_mask.shape[0], dh_mask.shape[1])) mask_lm = _shtools.SHExpandDH(dh_mask, sampling=_sampling, lmax_calc=0) area = mask_lm[0, 0, 0] * 4 * _np.pi tapers, eigenvalues = _shtools.SHReturnTapersMap(dh_mask, lwin, ntapers=nwin) return SHWindowMask(tapers, eigenvalues, weights, area, copy=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_array(self, itaper, normalization='4pi', csphase=1): """ Return the spherical harmonic coefficients of taper i as a numpy array. Usage ----- coeffs = x.to_array(itaper, [normalization, csphase]) Returns ------- coeffs : ndarray, shape (2, lwin+1, lwin+11) 3-D numpy ndarray of the spherical harmonic coefficients of the window. Parameters itaper : int Taper number, where itaper=0 is the best concentrated. normalization : str, optional, default = '4pi' Normalization of the output coefficients: '4pi', 'ortho' or 'schmidt' for geodesy 4pi normalized, orthonormalized, or Schmidt semi-normalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """
if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt'): raise ValueError( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase)) ) return self._to_array( itaper, normalization=normalization.lower(), csphase=csphase)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_shcoeffs(self, itaper, normalization='4pi', csphase=1): """ Return the spherical harmonic coefficients of taper i as a SHCoeffs class instance. Usage ----- clm = x.to_shcoeffs(itaper, [normalization, csphase]) Returns ------- clm : SHCoeffs class instance Parameters itaper : int Taper number, where itaper=0 is the best concentrated. normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho' or 'schmidt' for geodesy 4pi-normalized, orthonormalized, or Schmidt semi-normalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """
if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in set(['4pi', 'ortho', 'schmidt']): raise ValueError( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase)) ) coeffs = self.to_array(itaper, normalization=normalization.lower(), csphase=csphase) return SHCoeffs.from_array(coeffs, normalization=normalization.lower(), csphase=csphase, copy=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_shgrid(self, itaper, grid='DH2', zeros=None): """ Evaluate the coefficients of taper i on a spherical grid and return a SHGrid class instance. Usage ----- f = x.to_shgrid(itaper, [grid, zeros]) Returns ------- f : SHGrid class instance Parameters itaper : int Taper number, where itaper=0 is the best concentrated. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2' for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a Gauss-Legendre quadrature grid. zeros : ndarray, optional, default = None The cos(colatitude) nodes used in the Gauss-Legendre Quadrature grids. Description For more information concerning the spherical harmonic expansions and the properties of the output grids, see the documentation for SHExpandDH and SHExpandGLQ. """
if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() in ('DH', 'DH1'): gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=1, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='DH', copy=False) elif grid.upper() == 'DH2': gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=2, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='DH', copy=False) elif grid.upper() == 'GLQ': if zeros is None: zeros, weights = _shtools.SHGLQ(self.lwin) gridout = _shtools.MakeGridGLQ(self.to_array(itaper), zeros, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='GLQ', copy=False) else: raise ValueError( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}".format(repr(grid)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multitaper_spectrum(self, clm, k, convention='power', unit='per_l', **kwargs): """ Return the multitaper spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_spectrum(clm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper spectrum estimate, where lmax is the spherical-harmonic bandwidth of clm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper spectrum estimate. Parameters clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = clm.lmax The maximum spherical-harmonic degree of clm to use. taper_wt : ndarray, optional, default = None 1-D numpy array of the weights used in calculating the multitaper spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. """
return self._multitaper_spectrum(clm, k, convention=convention, unit=unit, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multitaper_cross_spectrum(self, clm, slm, k, convention='power', unit='per_l', **kwargs): """ Return the multitaper cross-spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper cross-spectrum estimate, where lmax is the smaller of the two spherical-harmonic bandwidths of clm and slm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper cross-spectrum estimate. Parameters clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the first global field to analyze. slm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the second global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = min(clm.lmax, slm.lmax) The maximum spherical-harmonic degree of the input coefficients to use. taper_wt : ndarray, optional, default = None The weights used in calculating the multitaper cross-spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. """
return self._multitaper_cross_spectrum(clm, slm, k, convention=convention, unit=unit, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spectra(self, itaper=None, nwin=None, convention='power', unit='per_l', base=10.): """ Return the spectra of one or more localization windows. Usage ----- spectra = x.spectra([itaper, nwin, convention, unit, base]) Returns ------- spectra : ndarray, shape (lwin+1, nwin) A matrix with each column containing the spectrum of a localization window, and where the windows are arranged with increasing concentration factors. If itaper is set, only a single vector is returned, whereas if nwin is set, the first nwin spectra are returned. Parameters itaper : int, optional, default = None The taper number of the output spectrum, where itaper=0 corresponds to the best concentrated taper. nwin : int, optional, default = 1 The number of best concentrated localization window power spectra to return. convention : str, optional, default = 'power' The type of spectrum to return: 'power' for power spectrum, 'energy' for energy spectrum, and 'l2norm' for the l2 norm spectrum. unit : str, optional, default = 'per_l' If 'per_l', return the total contribution to the spectrum for each spherical harmonic degree l. If 'per_lm', return the average contribution to the spectrum for each coefficient at spherical harmonic degree l. If 'per_dlogl', return the spectrum per log interval dlog_a(l). base : float, optional, default = 10. The logarithm base when calculating the 'per_dlogl' spectrum. Description This function returns either the power spectrum, energy spectrum, or l2-norm spectrum of one or more of the localization windows. Total power is defined as the integral of the function squared over all space, divided by the area the function spans. If the mean of the function is zero, this is equivalent to the variance of the function. The total energy is the integral of the function squared over all space and is 4pi times the total power. The l2-norm is the sum of the magnitude of the coefficients squared. The output spectrum can be expresed using one of three units. 'per_l' returns the contribution to the total spectrum from all angular orders at degree l. 'per_lm' returns the average contribution to the total spectrum from a single coefficient at degree l. The 'per_lm' spectrum is equal to the 'per_l' spectrum divided by (2l+1). 'per_dlogl' returns the contribution to the total spectrum from all angular orders over an infinitessimal logarithmic degree band. The contrubution in the band dlog_a(l) is spectrum(l, 'per_dlogl')*dlog_a(l), where a is the base, and where spectrum(l, 'per_dlogl) is equal to spectrum(l, 'per_l')*l*log(a). """
if itaper is None: if nwin is None: nwin = self.nwin spectra = _np.zeros((self.lwin+1, nwin)) for iwin in range(nwin): coeffs = self.to_array(iwin) spectra[:, iwin] = _spectrum(coeffs, normalization='4pi', convention=convention, unit=unit, base=base) else: coeffs = self.to_array(itaper) spectra = _spectrum(coeffs, normalization='4pi', convention=convention, unit=unit, base=base) return spectra
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coupling_matrix(self, lmax, nwin=None, weights=None, mode='full'): """ Return the coupling matrix of the first nwin tapers. This matrix relates the global power spectrum to the expectation of the localized multitaper spectrum. Usage ----- Mmt = x.coupling_matrix(lmax, [nwin, weights, mode]) Returns ------- Mmt : ndarray, shape (lmax+lwin+1, lmax+1) or (lmax+1, lmax+1) or (lmax-lwin+1, lmax+1) Parameters lmax : int Spherical harmonic bandwidth of the global power spectrum. nwin : int, optional, default = x.nwin Number of tapers used in the mutlitaper spectral analysis. weights : ndarray, optional, default = x.weights Taper weights used with the multitaper spectral analyses. mode : str, opitonal, default = 'full' 'full' returns a biased output spectrum of size lmax+lwin+1. The input spectrum is assumed to be zero for degrees l>lmax. 'same' returns a biased output spectrum with the same size (lmax+1) as the input spectrum. The input spectrum is assumed to be zero for degrees l>lmax. 'valid' returns a biased spectrum with size lmax-lwin+1. This returns only that part of the biased spectrum that is not influenced by the input spectrum beyond degree lmax. """
if weights is not None: if nwin is not None: if len(weights) != nwin: raise ValueError( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}'.format(len(weights), nwin)) else: if len(weights) != self.nwin: raise ValueError( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}'.format(len(weights), self.nwin)) if mode == 'full': return self._coupling_matrix(lmax, nwin=nwin, weights=weights) elif mode == 'same': cmatrix = self._coupling_matrix(lmax, nwin=nwin, weights=weights) return cmatrix[:lmax+1, :] elif mode == 'valid': cmatrix = self._coupling_matrix(lmax, nwin=nwin, weights=weights) return cmatrix[:lmax - self.lwin+1, :] else: raise ValueError("mode has to be 'full', 'same' or 'valid', not " "{}".format(mode))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_coupling_matrix(self, lmax, nwin=None, weights=None, mode='full', axes_labelsize=None, tick_labelsize=None, show=True, ax=None, fname=None): """ Plot the multitaper coupling matrix. This matrix relates the global power spectrum to the expectation of the localized multitaper spectrum. Usage ----- x.plot_coupling_matrix(lmax, [nwin, weights, mode, axes_labelsize, tick_labelsize, show, ax, fname]) Parameters lmax : int Spherical harmonic bandwidth of the global power spectrum. nwin : int, optional, default = x.nwin Number of tapers used in the mutlitaper spectral analysis. weights : ndarray, optional, default = x.weights Taper weights used with the multitaper spectral analyses. mode : str, opitonal, default = 'full' 'full' returns a biased output spectrum of size lmax+lwin+1. The input spectrum is assumed to be zero for degrees l>lmax. 'same' returns a biased output spectrum with the same size (lmax+1) as the input spectrum. The input spectrum is assumed to be zero for degrees l>lmax. 'valid' returns a biased spectrum with size lmax-lwin+1. This returns only that part of the biased spectrum that is not influenced by the input spectrum beyond degree lmax. axes_labelsize : int, optional, default = None The font size for the x and y axes labels. tick_labelsize : int, optional, default = None The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. ax : matplotlib axes object, optional, default = None An array of matplotlib axes objects where the plots will appear. fname : str, optional, default = None If present, save the image to the specified file. """
figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0]) if axes_labelsize is None: axes_labelsize = _mpl.rcParams['axes.labelsize'] if tick_labelsize is None: tick_labelsize = _mpl.rcParams['xtick.labelsize'] if ax is None: fig = _plt.figure(figsize=figsize) axes = fig.add_subplot(111) else: axes = ax axes.imshow(self.coupling_matrix(lmax, nwin=nwin, weights=weights, mode=mode), aspect='auto') axes.set_xlabel('Input power', fontsize=axes_labelsize) axes.set_ylabel('Output power', fontsize=axes_labelsize) axes.tick_params(labelsize=tick_labelsize) axes.minorticks_on() if ax is None: fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _taper2coeffs(self, itaper): """ Return the spherical harmonic coefficients of the unrotated taper i as an array, where i = 0 is the best concentrated. """
taperm = self.orders[itaper] coeffs = _np.zeros((2, self.lwin + 1, self.lwin + 1)) if taperm < 0: coeffs[1, :, abs(taperm)] = self.tapers[:, itaper] else: coeffs[0, :, abs(taperm)] = self.tapers[:, itaper] return coeffs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotate(self, clat, clon, coord_degrees=True, dj_matrix=None, nwinrot=None): """" Rotate the spherical-cap windows centered on the North pole to clat and clon, and save the spherical harmonic coefficients in the attribute coeffs. Usage ----- x.rotate(clat, clon [coord_degrees, dj_matrix, nwinrot]) Parameters clat, clon : float Latitude and longitude of the center of the rotated spherical-cap localization windows (default in degrees). coord_degrees : bool, optional, default = True True if clat and clon are in degrees. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. nwinrot : int, optional, default = (lwin+1)**2 The number of best concentrated windows to rotate, where lwin is the spherical harmonic bandwidth of the localization windows. Description This function will take the spherical-cap localization windows centered at the North pole (and saved in the attributes tapers and orders), rotate each function to the coordinate (clat, clon), and save the spherical harmonic coefficients in the attribute coeffs. Each column of coeffs contains a single window, and the coefficients are ordered according to the convention in SHCilmToVector. """
self.coeffs = _np.zeros(((self.lwin + 1)**2, self.nwin)) self.clat = clat self.clon = clon self.coord_degrees = coord_degrees if nwinrot is not None: self.nwinrot = nwinrot else: self.nwinrot = self.nwin if self.coord_degrees: angles = _np.radians(_np.array([0., -(90. - clat), -clon])) else: angles = _np.array([0., -(_np.pi/2. - clat), -clon]) if dj_matrix is None: if self.dj_matrix is None: self.dj_matrix = _shtools.djpi2(self.lwin + 1) dj_matrix = self.dj_matrix else: dj_matrix = self.dj_matrix if ((coord_degrees is True and clat == 90. and clon == 0.) or (coord_degrees is False and clat == _np.pi/2. and clon == 0.)): for i in range(self.nwinrot): coeffs = self._taper2coeffs(i) self.coeffs[:, i] = _shtools.SHCilmToVector(coeffs) else: coeffs = _shtools.SHRotateTapers(self.tapers, self.orders, self.nwinrot, angles, dj_matrix) self.coeffs = coeffs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vxx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxx component of the tensor. Usage ----- x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = False If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xx}$' Text label for the colorbar.. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vxx_label if ax is None: fig, axes = self.vxx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vyy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyy component of the tensor. Usage ----- x.plot_vyy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vyy_label if ax is None: fig, axes = self.vyy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vzz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzz component of the tensor. Usage ----- x.plot_vzz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vzz_label if ax is None: fig, axes = self.vzz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vxy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxy component of the tensor. Usage ----- x.plot_vxy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vxy_label if ax is None: fig, axes = self.vxy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vyx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyx component of the tensor. Usage ----- x.plot_vyx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yx}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vyx_label if ax is None: fig, axes = self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vxz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxz component of the tensor. Usage ----- x.plot_vxz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vxz_label if ax is None: fig, axes = self.vxz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vzx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzx component of the tensor. Usage ----- x.plot_vzx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zx}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vzx_label if ax is None: fig, axes = self.vzx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vyz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyz component of the tensor. Usage ----- x.plot_vyz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vyz_label if ax is None: fig, axes = self.vyz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vzy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzy component of the tensor. Usage ----- x.plot_vzy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._vzy_label if ax is None: fig, axes = self.vzy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_invar(self, colorbar=True, cb_orientation='horizontal', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the three invariants of the tensor and the derived quantity I. Usage ----- x.plot_invar([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if colorbar is True: if cb_orientation == 'horizontal': scale = 0.8 else: scale = 0.5 else: scale = 0.6 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(2, 2, figsize=figsize) self.plot_i0(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[3], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eig1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first eigenvalue of the tensor. Usage ----- x.plot_eig1([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_1$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._eig1_label if self.eig1 is None: self.compute_eig() if ax is None: fig, axes = self.eig1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eig2(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second eigenvalue of the tensor. Usage ----- x.plot_eig2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_2$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._eig2_label if self.eig2 is None: self.compute_eig() if ax is None: fig, axes = self.eig2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eig3(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the third eigenvalue of the tensor. Usage ----- x.plot_eig3([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_3$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._eig3_label if self.eig3 is None: self.compute_eig() if ax is None: fig, axes = self.eig3.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig3.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eigs(self, colorbar=True, cb_orientation='vertical', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the three eigenvalues of the tensor. Usage ----- x.plot_eigs([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if colorbar is True: if cb_orientation == 'horizontal': scale = 2.3 else: scale = 1.4 else: scale = 1.65 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(3, 1, figsize=figsize) self.plot_eig1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eig2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eig3(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eigh1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh1([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{h1}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._eigh1_label if self.eigh1 is None: self.compute_eigh() if ax is None: fig, axes = self.eigh1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eigh1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eigh2(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{h2}$, Eotvos$^{-1}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._eigh2_label if self.eigh2 is None: self.compute_eigh() if ax is None: fig, axes = self.eigh2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eigh2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eighh(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eighh([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{hh}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if cb_label is None: cb_label = self._eighh_label if self.eighh is None: self.compute_eigh() if ax is None: fig, axes = self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_eigh(self, colorbar=True, cb_orientation='vertical', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the two eigenvalues and maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
if colorbar is True: if cb_orientation == 'horizontal': scale = 2.3 else: scale = 1.4 else: scale = 1.65 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(3, 1, figsize=figsize) self.plot_eigh1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eigh2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eighh(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_version(): """Get version from git and VERSION file. In the case where the version is not tagged in git, this function appends .post0+commit if the version has been released and .dev0+commit if the version has not yet been released. Derived from: https://github.com/Changaco/version.py """
d = os.path.dirname(__file__) # get release number from VERSION with open(os.path.join(d, 'VERSION')) as f: vre = re.compile('.Version: (.+)$', re.M) version = vre.search(f.read()).group(1) if os.path.isdir(os.path.join(d, '.git')): # Get the version using "git describe". cmd = 'git describe --tags' try: git_version = check_output(cmd.split()).decode().strip()[1:] except CalledProcessError: print('Unable to get version number from git tags\n' 'Setting to x.x') git_version = 'x.x' # PEP440 compatibility if '-' in git_version: git_revision = check_output(['git', 'rev-parse', 'HEAD']) git_revision = git_revision.strip().decode('ascii') # add post0 if the version is released # otherwise add dev0 if the version is not yet released if ISRELEASED: version += '.post0+' + git_revision[:7] else: version += '.dev0+' + git_revision[:7] return version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_compiler_flags(): """Set fortran flags depending on the compiler."""
compiler = get_default_fcompiler() if compiler == 'absoft': flags = ['-m64', '-O3', '-YEXT_NAMES=LCS', '-YEXT_SFX=_', '-fpic', '-speed_math=10'] elif compiler == 'gnu95': flags = ['-m64', '-fPIC', '-O3', '-ffast-math'] elif compiler == 'intel': flags = ['-m64', '-fpp', '-free', '-O3', '-Tf'] elif compiler == 'g95': flags = ['-O3', '-fno-second-underscore'] elif compiler == 'pg': flags = ['-fast'] else: flags = ['-m64', '-O3'] return flags
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configuration(parent_package='', top_path=None): """Configure all packages that need to be built."""
config = Configuration('', parent_package, top_path) F95FLAGS = get_compiler_flags() kwargs = { 'libraries': [], 'include_dirs': [], 'library_dirs': [], } kwargs['extra_compile_args'] = F95FLAGS kwargs['f2py_options'] = ['--quiet'] # numpy.distutils.fcompiler.FCompiler doesn't support .F95 extension compiler = FCompiler(get_default_fcompiler()) compiler.src_extensions.append('.F95') compiler.language_map['.F95'] = 'f90' # collect all Fortran sources files = os.listdir('src') exclude_sources = ['PlanetsConstants.f95', 'PythonWrapper.f95'] sources = [os.path.join('src', file) for file in files if file.lower().endswith(('.f95', '.c')) and file not in exclude_sources] # (from http://stackoverflow.com/questions/14320220/ # testing-python-c-libraries-get-build-path)): build_lib_dir = "{dirname}.{platform}-{version[0]}.{version[1]}" dirparams = {'dirname': 'temp', 'platform': sysconfig.get_platform(), 'version': sys.version_info} libdir = os.path.join('build', build_lib_dir.format(**dirparams)) print('searching SHTOOLS in:', libdir) # Fortran compilation config.add_library('SHTOOLS', sources=sources, **kwargs) # SHTOOLS kwargs['libraries'].extend(['SHTOOLS']) kwargs['include_dirs'].extend([libdir]) kwargs['library_dirs'].extend([libdir]) # FFTW info fftw_info = get_info('fftw', notfound_action=2) dict_append(kwargs, **fftw_info) if sys.platform != 'win32': kwargs['libraries'].extend(['m']) # BLAS / Lapack info lapack_info = get_info('lapack_opt', notfound_action=2) blas_info = get_info('blas_opt', notfound_action=2) dict_append(kwargs, **blas_info) dict_append(kwargs, **lapack_info) config.add_extension('pyshtools._SHTOOLS', sources=['src/pyshtools.pyf', 'src/PythonWrapper.f95'], **kwargs) return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _time_variable_part(epoch, ref_epoch, trnd, periodic): """ Return sum of the time-variable part of the coefficients The formula is: G(t) = G(t0) + trnd*(t-t0) + asin1*sin(2pi/p1 * (t-t0)) + acos1*cos(2pi/p1 * (t-t0)) + asin2*sin(2pi/p2 * (t-t0)) + acos2*cos(2pi/p2 * (t-t0)) This function computes all terms after G(t0). """
delta_t = epoch - ref_epoch trend = trnd * delta_t periodic_sum = _np.zeros_like(trnd) for period in periodic: for trifunc in periodic[period]: coeffs = periodic[period][trifunc] if trifunc == 'acos': periodic_sum += coeffs * _np.cos(2 * _np.pi / period * delta_t) elif trifunc == 'asin': periodic_sum += coeffs * _np.sin(2 * _np.pi / period * delta_t) return trend + periodic_sum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_subroutine(subroutine): """loops through variables of a subroutine and modifies them"""
# print('\n----',subroutine['name'],'----') #-- use original function from shtools: subroutine['use'] = {'shtools': {'map': {subroutine['name']: subroutine['name']}, 'only': 1}} #-- loop through variables: for varname, varattribs in subroutine['vars'].items(): #-- prefix function return variables with 'py' if varname == subroutine['name']: subroutine['vars']['py' + varname] = subroutine['vars'].pop(varname) varname = 'py' + varname # print('prefix added:',varname) #-- change assumed to explicit: if has_assumed_shape(varattribs): make_explicit(subroutine, varname, varattribs) # print('assumed shape variable modified to:',varname,varattribs['dimension']) #-- add py prefix to subroutine: subroutine['name'] = 'py' + subroutine['name']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def figstyle(rel_width=0.75, screen_dpi=114, aspect_ratio=4/3, max_width=7.48031): """ Set matplotlib parameters for creating publication quality graphics. Usage ----- figstyle([rel_width, screen_dpi, aspect_ratio, max_width]) Parameters rel_width : float, optional, default = 0.75 The relative width of the plot (from 0 to 1) wih respect to max_width. screen_dpi : int, optional, default = 114 The screen resolution of the display in dpi, which determines the size of the plot on the display. aspect_ratio : float, optional, default = 4/3 The aspect ratio of the plot. max_width : float, optional, default = 7.48031 The maximum width of the usable area of a journal page in inches. Description This function sets a variety of matplotlib parameters for creating publication quality graphics. The default parameters are tailored to AGU/Wiley-Blackwell journals that accept relative widths of 0.5, 0.75, and 1. To reset the maplotlib parameters to their default values, use matplotlib.pyplot.style.use('default') """
width_x = max_width * rel_width width_y = max_width * rel_width / aspect_ratio shtools = { # fonts 'font.size': 10, 'font.family': 'sans-serif', 'font.sans-serif': ['Myriad Pro', 'DejaVu Sans', 'Bitstream Vera Sans', 'Verdana', 'Arial', 'Helvetica'], 'axes.titlesize': 10, 'axes.labelsize': 10, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 9, 'text.usetex': False, 'axes.formatter.limits': (-3, 3), # figure 'figure.dpi': screen_dpi, 'figure.figsize': (width_x, width_y), # line and tick widths 'axes.linewidth': 1, 'lines.linewidth': 1.5, 'xtick.major.width': 0.6, 'ytick.major.width': 0.6, 'xtick.minor.width': 0.6, 'xtick.minor.width': 0.6, 'xtick.top': True, 'ytick.right': True, # grids 'grid.linewidth': 0.3, 'grid.color': 'k', 'grid.linestyle': '-', # legends 'legend.framealpha': 1., 'legend.edgecolor': 'k', # images 'image.lut': 65536, # 16 bit # savefig 'savefig.bbox': 'tight', 'savefig.pad_inches': 0.02, 'savefig.dpi': 600, 'savefig.format': 'pdf' } _plt.style.use([shtools])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_zeros(self, lmax, kind='real', normalization='4pi', csphase=1): """ Initialize class with spherical harmonic coefficients set to zero from degree 0 to lmax. Usage ----- x = SHCoeffs.from_zeros(lmax, [normalization, csphase]) Returns ------- x : SHCoeffs class instance. Parameters lmax : int The highest spherical harmonic degree l of the coefficients. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. kind : str, optional, default = 'real' 'real' or 'complex' spherical harmonic coefficients. """
if kind.lower() not in ('real', 'complex'): raise ValueError( "Kind must be 'real' or 'complex'. " + "Input value was {:s}." .format(repr(kind)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 nl = lmax + 1 if kind.lower() == 'real': coeffs = _np.zeros((2, nl, nl)) else: coeffs = _np.zeros((2, nl, nl), dtype=complex) for cls in self.__subclasses__(): if cls.istype(kind): return cls(coeffs, normalization=normalization.lower(), csphase=csphase)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_file(self, filename, format='shtools', header=None, **kwargs): """ Save raw spherical harmonic coefficients to a file. Usage ----- x.to_file(filename, [format='shtools', header]) x.to_file(filename, [format='npy', **kwargs]) Parameters filename : str Name of the output file. format : str, optional, default = 'shtools' 'shtools' or 'npy'. See method from_file() for more information. header : str, optional, default = None A header string written to an 'shtools'-formatted file directly before the spherical harmonic coefficients. **kwargs : keyword argument list, optional for format = 'npy' Keyword arguments of numpy.save(). Description If format='shtools', the coefficients will be written to an ascii formatted file. The first line of the file is an optional user provided header line, and the spherical harmonic coefficients are then listed, with increasing degree and order, with the format l, m, coeffs[0, l, m], coeffs[1, l, m] where l and m are the spherical harmonic degree and order, respectively. If format='npy', the spherical harmonic coefficients will be saved to a binary numpy 'npy' file using numpy.save(). """
if format is 'shtools': with open(filename, mode='w') as file: if header is not None: file.write(header + '\n') for l in range(self.lmax+1): for m in range(l+1): file.write('{:d}, {:d}, {:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m])) elif format is 'npy': _np.save(filename, self.coeffs, **kwargs) else: raise NotImplementedError( 'format={:s} not implemented'.format(repr(format)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_array(self, normalization=None, csphase=None, lmax=None): """ Return spherical harmonic coefficients as a numpy array. Usage ----- coeffs = x.to_array([normalization, csphase, lmax]) Returns ------- coeffs : ndarry, shape (2, lmax+1, lmax+1) numpy ndarray of the spherical harmonic coefficients. Parameters normalization : str, optional, default = x.normalization Normalization of the output coefficients: '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. If lmax is greater than x.lmax, the array will be zero padded. Description This method will return an array of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention, and a different maximum spherical harmonic degree. If the maximum degree is smaller than the maximum degree of the class instance, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the class instance, the output array will be zero padded. """
if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax coeffs = _convert(self.coeffs, normalization_in=self.normalization, normalization_out=normalization, csphase_in=self.csphase, csphase_out=csphase, lmax=lmax) return coeffs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def volume(self, lmax=None): """ If the function is the real shape of an object, calculate the volume of the body. Usage ----- volume = x.volume([lmax]) Returns ------- volume : float The volume of the object. Parameters lmax : int, optional, default = x.lmax The maximum spherical harmonic degree to use when calculating the volume. Description If the function is the real shape of an object, this method will calculate the volume of the body exactly by integration. This routine raises the function to the nth power, with n from 1 to 3, and calculates the spherical harmonic degree and order 0 term. To avoid aliases, the function is first expand on a grid that can resolve spherical harmonic degrees up to 3*lmax. """
if self.coeffs[0, 0, 0] == 0: raise ValueError('The volume of the object can not be calculated ' 'when the degree and order 0 term is equal to ' 'zero.') if self.kind == 'complex': raise ValueError('The volume of the object can not be calculated ' 'for complex functions.') if lmax is None: lmax = self.lmax r0 = self.coeffs[0, 0, 0] grid = self.expand(lmax=3*lmax) - r0 h200 = (grid**2).expand(lmax_calc=0).coeffs[0, 0, 0] h300 = (grid**3).expand(lmax_calc=0).coeffs[0, 0, 0] volume = 4 * _np.pi / 3 * (h300 + 3 * r0 * h200 + r0**3) return volume
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotate(self, alpha, beta, gamma, degrees=True, convention='y', body=False, dj_matrix=None): """ Rotate either the coordinate system used to express the spherical harmonic coefficients or the physical body, and return a new class instance. Usage ----- x_rotated = x.rotate(alpha, beta, gamma, [degrees, convention, body, dj_matrix]) Returns ------- x_rotated : SHCoeffs class instance Parameters alpha, beta, gamma : float The three Euler rotation angles in degrees. degrees : bool, optional, default = True True if the Euler angles are in degrees, False if they are in radians. convention : str, optional, default = 'y' The convention used for the rotation of the second angle, which can be either 'x' or 'y' for a rotation about the x or y axes, respectively. body : bool, optional, default = False If true, rotate the physical body and not the coordinate system. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. Description This method will take the spherical harmonic coefficients of a function, rotate the coordinate frame by the three Euler anlges, and output the spherical harmonic coefficients of the new function. If the optional parameter body is set to True, then the physical body will be rotated instead of the coordinate system. The rotation of a coordinate system or body can be viewed in two complementary ways involving three successive rotations. Both methods have the same initial and final configurations, and the angles listed in both schemes are the same. Scheme A: (I) Rotation about the z axis by alpha. (II) Rotation about the new y axis by beta. (III) Rotation about the new z axis by gamma. Scheme B: (I) Rotation about the z axis by gamma. (II) Rotation about the initial y axis by beta. (III) Rotation about the initial z axis by alpha. Here, the 'y convention' is employed, where the second rotation is with respect to the y axis. When using the 'x convention', the second rotation is instead with respect to the x axis. The relation between the Euler angles in the x and y conventions is given by alpha_y=alpha_x-pi/2, beta_y=beta_x, and gamma_y=gamma_x+pi/2. To perform the inverse transform associated with the three angles (alpha, beta, gamma), one would perform an additional rotation using the angles (-gamma, -beta, -alpha). The rotations can be viewed either as a rotation of the coordinate system or the physical body. To rotate the physical body without rotation of the coordinate system, set the optional parameter body to True. This rotation is accomplished by performing the inverse rotation using the angles (-gamma, -beta, -alpha). """
if type(convention) != str: raise ValueError('convention must be a string. ' + 'Input type was {:s}' .format(str(type(convention)))) if convention.lower() not in ('x', 'y'): raise ValueError( "convention must be either 'x' or 'y'. " + "Provided value was {:s}".format(repr(convention)) ) if convention is 'y': if body is True: angles = _np.array([-gamma, -beta, -alpha]) else: angles = _np.array([alpha, beta, gamma]) elif convention is 'x': if body is True: angles = _np.array([-gamma - _np.pi/2, -beta, -alpha + _np.pi/2]) else: angles = _np.array([alpha - _np.pi/2, beta, gamma + _np.pi/2]) if degrees: angles = _np.radians(angles) if self.lmax > 1200: _warnings.warn("The rotate() method is accurate only to about" + " spherical harmonic degree 1200. " + "lmax = {:d}".format(self.lmax), category=RuntimeWarning) rot = self._rotate(angles, dj_matrix) return rot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(self, normalization=None, csphase=None, lmax=None, kind=None, check=True): """ Return a SHCoeffs class instance with a different normalization convention. Usage ----- clm = x.convert([normalization, csphase, lmax, kind, check]) Returns ------- clm : SHCoeffs class instance Parameters normalization : str, optional, default = x.normalization Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention for the output class: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. kind : str, optional, default = clm.kind 'real' or 'complex' spherical harmonic coefficients for the output class. check : bool, optional, default = True When converting complex coefficients to real coefficients, if True, check if function is entirely real. Description This method will return a new class instance of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention. The coefficients can be converted between real and complex form, and a different maximum spherical harmonic degree of the output coefficients can be specified. If this maximum degree is smaller than the maximum degree of the original class, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the original class, the coefficients of the new class will be zero padded. """
if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax if kind is None: kind = self.kind # check argument consistency if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Provided value was {:s}" .format(repr(normalization))) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase))) if (kind != self.kind): if (kind == 'complex'): temp = self._make_complex() else: temp = self._make_real(check=check) coeffs = temp.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) else: coeffs = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHCoeffs.from_array(coeffs, normalization=normalization.lower(), csphase=csphase, copy=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, grid='DH', lat=None, colat=None, lon=None, degrees=True, zeros=None, lmax=None, lmax_calc=None): """ Evaluate the spherical harmonic coefficients either on a global grid or for a list of coordinates. Usage ----- f = x.expand([grid, lmax, lmax_calc, zeros]) g = x.expand(lat=lat, lon=lon, [lmax_calc, degrees]) g = x.expand(colat=colat, lon=lon, [lmax_calc, degrees]) Returns ------- f : SHGrid class instance g : float, ndarray, or list Parameters lat : int, float, ndarray, or list, optional, default = None Latitude coordinates where the function is to be evaluated. colat : int, float, ndarray, or list, optional, default = None Colatitude coordinates where the function is to be evaluated. lon : int, float, ndarray, or list, optional, default = None Longitude coordinates where the function is to be evaluated. degrees : bool, optional, default = True True if lat, colat and lon are in degrees, False if in radians. grid : str, optional, default = 'DH' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2' for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a Gauss-Legendre quadrature grid. lmax : int, optional, default = x.lmax The maximum spherical harmonic degree, which determines the grid spacing of the output grid. lmax_calc : int, optional, default = x.lmax The maximum spherical harmonic degree to use when evaluating the function. zeros : ndarray, optional, default = None The cos(colatitude) nodes used in the Gauss-Legendre Quadrature grids. Description This method either (1) evaluates the spherical harmonic coefficients on a global grid and returns an SHGrid class instance, or (2) evaluates the spherical harmonic coefficients for a list of (co)latitude and longitude coordinates. For the first case, the grid type is defined by the optional parameter grid, which can be 'DH', 'DH2' or 'GLQ'.For the second case, the optional parameters lon and either colat or lat must be provided. """
if lat is not None and colat is not None: raise ValueError('lat and colat can not both be specified.') if lat is not None and lon is not None: if lmax_calc is None: lmax_calc = self.lmax values = self._expand_coord(lat=lat, lon=lon, degrees=degrees, lmax_calc=lmax_calc) return values if colat is not None and lon is not None: if lmax_calc is None: lmax_calc = self.lmax if type(colat) is list: lat = list(map(lambda x: 90 - x, colat)) else: lat = 90 - colat values = self._expand_coord(lat=lat, lon=lon, degrees=degrees, lmax_calc=lmax_calc) return values else: if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() in ('DH', 'DH1'): gridout = self._expandDH(sampling=1, lmax=lmax, lmax_calc=lmax_calc) elif grid.upper() == 'DH2': gridout = self._expandDH(sampling=2, lmax=lmax, lmax_calc=lmax_calc) elif grid.upper() == 'GLQ': gridout = self._expandGLQ(zeros=zeros, lmax=lmax, lmax_calc=lmax_calc) else: raise ValueError( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}".format(repr(grid))) return gridout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_complex(self): """Convert the real SHCoeffs class to the complex class."""
rcomplex_coeffs = _shtools.SHrtoc(self.coeffs, convention=1, switchcs=0) # These coefficients are using real floats, and need to be # converted to complex form. complex_coeffs = _np.zeros((2, self.lmax+1, self.lmax+1), dtype='complex') complex_coeffs[0, :, :] = (rcomplex_coeffs[0, :, :] + 1j * rcomplex_coeffs[1, :, :]) complex_coeffs[1, :, :] = complex_coeffs[0, :, :].conjugate() for m in self.degrees(): if m % 2 == 1: complex_coeffs[1, :, m] = - complex_coeffs[1, :, m] # complex_coeffs is initialized in this function and can be # passed as reference return SHCoeffs.from_array(complex_coeffs, normalization=self.normalization, csphase=self.csphase, copy=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expand_coord(self, lat, lon, lmax_calc, degrees): """Evaluate the function at the coordinates lat and lon."""
if self.normalization == '4pi': norm = 1 elif self.normalization == 'schmidt': norm = 2 elif self.normalization == 'unnorm': norm = 3 elif self.normalization == 'ortho': norm = 4 else: raise ValueError( "Normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Input value was {:s}" .format(repr(self.normalization))) if degrees is True: latin = lat lonin = lon else: latin = _np.rad2deg(lat) lonin = _np.rad2deg(lon) if type(lat) is not type(lon): raise ValueError('lat and lon must be of the same type. ' + 'Input types are {:s} and {:s}' .format(repr(type(lat)), repr(type(lon)))) if type(lat) is int or type(lat) is float or type(lat) is _np.float_: return _shtools.MakeGridPoint(self.coeffs, lat=latin, lon=lonin, lmax=lmax_calc, norm=norm, csphase=self.csphase) elif type(lat) is _np.ndarray: values = _np.empty_like(lat, dtype=float) for v, latitude, longitude in _np.nditer([values, latin, lonin], op_flags=['readwrite']): v[...] = _shtools.MakeGridPoint(self.coeffs, lat=latitude, lon=longitude, lmax=lmax_calc, norm=norm, csphase=self.csphase) return values elif type(lat) is list: values = [] for latitude, longitude in zip(latin, lonin): values.append( _shtools.MakeGridPoint(self.coeffs, lat=latitude, lon=longitude, lmax=lmax_calc, norm=norm, csphase=self.csphase)) return values else: raise ValueError('lat and lon must be either an int, float, ' + 'ndarray, or list. ' + 'Input types are {:s} and {:s}' .format(repr(type(lat)), repr(type(lon))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_real(self, check=True): """Convert the complex SHCoeffs class to the real class."""
# Test if the coefficients correspond to a real grid. # This is not very elegant, and the equality condition # is probably not robust to round off errors. if check: for l in self.degrees(): if self.coeffs[0, l, 0] != self.coeffs[0, l, 0].conjugate(): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = 0: {:e}' .format(l, self.coeffs[0, l, 0])) for m in _np.arange(1, l + 1): if m % 2 == 1: if (self.coeffs[0, l, m] != - self.coeffs[1, l, m].conjugate()): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = {:d}: {:e}, {:e}' .format( l, m, self.coeffs[0, l, 0], self.coeffs[1, l, 0])) else: if (self.coeffs[0, l, m] != self.coeffs[1, l, m].conjugate()): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = {:d}: {:e}, {:e}' .format( l, m, self.coeffs[0, l, 0], self.coeffs[1, l, 0])) coeffs_rc = _np.zeros((2, self.lmax + 1, self.lmax + 1)) coeffs_rc[0, :, :] = self.coeffs[0, :, :].real coeffs_rc[1, :, :] = self.coeffs[0, :, :].imag real_coeffs = _shtools.SHctor(coeffs_rc, convention=1, switchcs=0) return SHCoeffs.from_array(real_coeffs, normalization=self.normalization, csphase=self.csphase)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expandGLQ(self, zeros, lmax, lmax_calc): """Evaluate the coefficients on a Gauss-Legendre quadrature grid."""
if self.normalization == '4pi': norm = 1 elif self.normalization == 'schmidt': norm = 2 elif self.normalization == 'unnorm': norm = 3 elif self.normalization == 'ortho': norm = 4 else: raise ValueError( "Normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Input value was {:s}" .format(repr(self.normalization))) if zeros is None: zeros, weights = _shtools.SHGLQ(self.lmax) data = _shtools.MakeGridGLQC(self.coeffs, zeros, norm=norm, csphase=self.csphase, lmax=lmax, lmax_calc=lmax_calc) gridout = SHGrid.from_array(data, grid='GLQ', copy=False) return gridout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_array(self, array, grid='DH', copy=True): """ Initialize the class instance from an input array. Usage ----- x = SHGrid.from_array(array, [grid, copy]) Returns ------- x : SHGrid class instance Parameters array : ndarray, shape (nlat, nlon) 2-D numpy array of the gridded data, where nlat and nlon are the number of latitudinal and longitudinal bands, respectively. grid : str, optional, default = 'DH' 'DH' or 'GLQ' for Driscoll and Healy grids or Gauss Legendre Quadrature grids, respectively. copy : bool, optional, default = True If True (default), make a copy of array when initializing the class instance. If False, initialize the class instance with a reference to array. """
if _np.iscomplexobj(array): kind = 'complex' else: kind = 'real' if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() not in set(['DH', 'GLQ']): raise ValueError( "grid must be 'DH' or 'GLQ'. Input value was {:s}." .format(repr(grid)) ) for cls in self.__subclasses__(): if cls.istype(kind) and cls.isgrid(grid): return cls(array, copy=copy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_file(self, fname, binary=False, **kwargs): """ Initialize the class instance from gridded data in a file. Usage ----- x = SHGrid.from_file(fname, [binary, **kwargs]) Returns ------- x : SHGrid class instance Parameters fname : str The filename containing the gridded data. For text files (default) the file is read using the numpy routine loadtxt(), whereas for binary files, the file is read using numpy.load(). The dimensions of the array must be nlon=nlat or nlon=2*nlat for Driscoll and Healy grids, or nlon=2*nlat-1 for Gauss-Legendre Quadrature grids. binary : bool, optional, default = False If False, read a text file. If True, read a binary 'npy' file. **kwargs : keyword arguments, optional Keyword arguments of numpy.loadtxt() or numpy.load(). """
if binary is False: data = _np.loadtxt(fname, **kwargs) elif binary is True: data = _np.load(fname, **kwargs) else: raise ValueError('binary must be True or False. ' 'Input value is {:s}'.format(binary)) if _np.iscomplexobj(data): kind = 'complex' else: kind = 'real' if (data.shape[1] == data.shape[0]) or (data.shape[1] == 2 * data.shape[0]): grid = 'DH' elif data.shape[1] == 2 * data.shape[0] - 1: grid = 'GLQ' else: raise ValueError('Input grid must be dimensioned as ' + '(nlat, nlon). For DH grids, nlon = nlat or ' + 'nlon = 2 * nlat. For GLQ grids, nlon = ' + '2 * nlat - 1. Input dimensions are nlat = ' + '{:d}, nlon = {:d}'.format(data.shape[0], data.shape[1])) for cls in self.__subclasses__(): if cls.istype(kind) and cls.isgrid(grid): return cls(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_file(self, filename, binary=False, **kwargs): """ Save gridded data to a file. Usage ----- x.to_file(filename, [binary, **kwargs]) Parameters filename : str Name of output file. For text files (default), the file will be saved automatically in gzip compressed format if the filename ends in .gz. binary : bool, optional, default = False If False, save as text using numpy.savetxt(). If True, save as a 'npy' binary file using numpy.save(). **kwargs : keyword arguments, optional Keyword arguments of numpy.savetxt() and numpy.save(). """
if binary is False: _np.savetxt(filename, self.data, **kwargs) elif binary is True: _np.save(filename, self.data, **kwargs) else: raise ValueError('binary must be True or False. ' 'Input value is {:s}'.format(binary))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lats(self, degrees=True): """ Return the latitudes of each row of the gridded data. Usage ----- lats = x.lats([degrees]) Returns ------- lats : ndarray, shape (nlat) 1-D numpy array of size nlat containing the latitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians. """
if degrees is False: return _np.radians(self._lats()) else: return self._lats()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lons(self, degrees=True): """ Return the longitudes of each column of the gridded data. Usage ----- lons = x.get_lon([degrees]) Returns ------- lons : ndarray, shape (nlon) 1-D numpy array of size nlon containing the longitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians. """
if degrees is False: return _np.radians(self._lons()) else: return self._lons()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, normalization='4pi', csphase=1, **kwargs): """ Expand the grid into spherical harmonics. Usage ----- clm = x.expand([normalization, csphase, lmax_calc]) Returns ------- clm : SHCoeffs class instance Parameters normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. lmax_calc : int, optional, default = x.lmax Maximum spherical harmonic degree to return. """
if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) return self._expand(normalization=normalization, csphase=csphase, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expand(self, normalization, csphase, **kwargs): """Expand the grid into real spherical harmonics."""
if normalization.lower() == '4pi': norm = 1 elif normalization.lower() == 'schmidt': norm = 2 elif normalization.lower() == 'unnorm': norm = 3 elif normalization.lower() == 'ortho': norm = 4 else: raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) cilm = _shtools.SHExpandDH(self.data, norm=norm, csphase=csphase, sampling=self.sampling, **kwargs) coeffs = SHCoeffs.from_array(cilm, normalization=normalization.lower(), csphase=csphase, copy=False) return coeffs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot(self, colorbar=True, cb_orientation='vertical', cb_label='geoid, m', show=True, **kwargs): """ Plot the geoid. Usage ----- x.plot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = 'geoid, m' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """
return self.geoid.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=True, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _yyyymmdd_to_year_fraction(date): """Convert YYYMMDD.DD date string or float to YYYY.YYY"""
date = str(date) if '.' in date: date, residual = str(date).split('.') residual = float('0.' + residual) else: residual = 0.0 date = _datetime.datetime.strptime(date, '%Y%m%d') date += _datetime.timedelta(days=residual) year = date.year year_start = _datetime.datetime(year=year, month=1, day=1) next_year_start = _datetime.datetime(year=year + 1, month=1, day=1) year_duration = next_year_start - year_start year_elapsed = date - year_start fraction = year_elapsed / year_duration return year + fraction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example(): """ example that plots the power spectrum of Mars topography data """
# --- input data filename --- infile = os.path.join(os.path.dirname(__file__), '../../ExampleDataFiles/MarsTopo719.shape') coeffs, lmax = shio.shread(infile) # --- plot grid --- grid = expand.MakeGridDH(coeffs, csphase=-1) fig_map = plt.figure() plt.imshow(grid) # ---- compute spectrum ---- ls = np.arange(lmax + 1) pspectrum = spectralanalysis.spectrum(coeffs, unit='per_l') pdensity = spectralanalysis.spectrum(coeffs, unit='per_lm') # ---- plot spectrum ---- fig_spectrum, ax = plt.subplots(1, 1) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('degree l') ax.grid(True, which='both') ax.plot(ls[1:], pspectrum[1:], label='power per degree l') ax.plot(ls[1:], pdensity[1:], label='power per degree l and order m') ax.legend() fig_map.savefig('SHRtopography_mars.png') fig_spectrum.savefig('SHRspectrum_mars.png') print('mars topography and spectrum saved')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_zeros(self, lmax, gm, r0, omega=None, errors=False, normalization='4pi', csphase=1): """ Initialize the class with spherical harmonic coefficients set to zero from degree 1 to lmax, and set the degree 0 term to 1. Usage ----- x = SHGravCoeffs.from_zeros(lmax, gm, r0, [omega, errors, normalization, csphase]) Returns ------- x : SHGravCoeffs class instance. Parameters lmax : int The maximum spherical harmonic degree l of the coefficients. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. r0 : float The reference radius of the spherical harmonic coefficients. omega : float, optional, default = None The angular rotation rate of the body. errors : bool, optional, default = False If True, initialize the attribute errors with zeros. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " "are stable only for degrees less than or equal " "to 85. lmax for the coefficients will be set to " "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 coeffs = _np.zeros((2, lmax + 1, lmax + 1)) coeffs[0, 0, 0] = 1.0 if errors is False: clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega, normalization=normalization.lower(), csphase=csphase) else: clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega, errors=_np.zeros((2, lmax + 1, lmax + 1)), normalization=normalization.lower(), csphase=csphase) return clm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_shape(self, shape, rho, gm, nmax=7, lmax=None, lmax_grid=None, lmax_calc=None, omega=None): """ Initialize a class of gravitational potential spherical harmonic coefficients by calculuting the gravitational potential associatiated with relief along an interface. Usage ----- x = SHGravCoeffs.from_shape(shape, rho, gm, [nmax, lmax, lmax_grid, lmax_calc, omega]) Returns ------- x : SHGravCoeffs class instance. Parameters shape : SHGrid or SHCoeffs class instance The shape of the interface, either as an SHGrid or SHCoeffs class instance. If the input is an SHCoeffs class instance, this will be expaned on a grid using the optional parameters lmax_grid and lmax_calc. rho : int, float, or ndarray, or an SHGrid or SHCoeffs class instance The density contrast associated with the interface in kg / m3. If the input is a scalar, the density contrast is constant. If the input is an SHCoeffs or SHGrid class instance, the density contrast will vary laterally. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. nmax : integer, optional, default = 7 The maximum order used in the Taylor-series expansion when calculating the potential coefficients. lmax : int, optional, shape.lmax The maximum spherical harmonic degree of the output spherical harmonic coefficients. lmax_grid : int, optional, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that is resolvable when expanded onto a grid. lmax_calc : optional, integer, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that will be used when expanded onto a grid. omega : float, optional, default = None The angular rotation rate of the body. Description Initialize an SHGravCoeffs class instance by calculating the spherical harmonic coefficients of the gravitational potential associated with the shape of a density interface. The potential is calculated using the finite-amplitude technique of Wieczorek and Phillips (1998) for a constant density contrast and Wieczorek (2007) for a density contrast that varies laterally. The output coefficients are referenced to the mean radius of shape, and the potential is strictly valid only when it is evaluated at a radius greater than the maximum radius of shape. The input shape (and density contrast rho for variable density) can be either an SHGrid or SHCoeffs class instance. The routine makes direct use of gridded versions of these quantities, so if the input is of type SHCoeffs, it will first be expanded onto a grid. This exansion will be performed on a grid that can resolve degrees up to lmax_grid, with only the first lmax_calc coefficients being used. The input shape must correspond to absolute radii as the degree 0 term determines the reference radius of the coefficients. As an intermediate step, this routine calculates the spherical harmonic coefficients of the interface raised to the nth power, i.e., (shape-r0)**n, where r0 is the mean radius of shape. If the input shape is bandlimited to degree L, the resulting function will thus be bandlimited to degree L*nmax. This subroutine assumes implicitly that the maximum spherical harmonic degree of the input shape (when SHCoeffs) or maximum resolvable spherical harmonic degree of shape (when SHGrid) is greater or equal to this value. If this is not the case, aliasing will occur. In practice, for accurate results, the effective bandwidth needs only to be about three times the size of L, though this should be verified for each application. The effective bandwidth of shape (when SHCoeffs) can be increased by preprocessing with the method pad(), or by increaesing the value of lmax_grid (when SHGrid). """
mass = gm / _G.value if type(shape) is not _SHRealCoeffs and type(shape) is not _DHRealGrid: raise ValueError('shape must be of type SHRealCoeffs ' 'or DHRealGrid. Input type is {:s}' .format(repr(type(shape)))) if (not issubclass(type(rho), float) and type(rho) is not int and type(rho) is not _np.ndarray and type(rho) is not _SHRealCoeffs and type(rho is not _DHRealGrid)): raise ValueError('rho must be of type float, int, ndarray, ' 'SHRealCoeffs or DHRealGrid. Input type is {:s}' .format(repr(type(rho)))) if type(shape) is _SHRealCoeffs: shape = shape.expand(lmax=lmax_grid, lmax_calc=lmax_calc) if type(rho) is _SHRealCoeffs: rho = rho.expand(lmax=lmax_grid, lmax_calc=lmax_calc) if type(rho) is _DHRealGrid: if shape.lmax != rho.lmax: raise ValueError('The grids for shape and rho must have the ' 'same size. ' 'lmax of shape = {:d}, lmax of rho = {:d}' .format(shape.lmax, rho.lmax)) cilm, d = _CilmPlusRhoHDH(shape.data, nmax, mass, rho.data, lmax=lmax) else: cilm, d = _CilmPlusDH(shape.data, nmax, mass, rho, lmax=lmax) clm = SHGravRealCoeffs(cilm, gm=gm, r0=d, omega=omega, normalization='4pi', csphase=1) return clm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_file(self, filename, format='shtools', header=None, errors=False, **kwargs): """ Save spherical harmonic coefficients to a file. Usage ----- x.to_file(filename, [format='shtools', header, errors]) x.to_file(filename, [format='npy', **kwargs]) Parameters filename : str Name of the output file. format : str, optional, default = 'shtools' 'shtools' or 'npy'. See method from_file() for more information. header : str, optional, default = None A header string written to an 'shtools'-formatted file directly before the spherical harmonic coefficients. errors : bool, optional, default = False If True, save the errors in the file (for 'shtools' formatted files only). **kwargs : keyword argument list, optional for format = 'npy' Keyword arguments of numpy.save(). Description If format='shtools', the coefficients and meta-data will be written to an ascii formatted file. The first line is an optional user provided header line, and the following line provides the attributes r0, gm, omega, and lmax. The spherical harmonic coefficients are then listed, with increasing degree and order, with the format l, m, coeffs[0, l, m], coeffs[1, l, m] where l and m are the spherical harmonic degree and order, respectively. If the errors are to be saved, the format of each line will be l, m, coeffs[0, l, m], coeffs[1, l, m], error[0, l, m], error[1, l, m] If format='npy', the spherical harmonic coefficients (but not the meta-data nor errors) will be saved to a binary numpy 'npy' file using numpy.save(). """
if format is 'shtools': if errors is True and self.errors is None: raise ValueError('Can not save errors when then have not been ' 'initialized.') if self.omega is None: omega = 0. else: omega = self.omega with open(filename, mode='w') as file: if header is not None: file.write(header + '\n') file.write('{:.16e}, {:.16e}, {:.16e}, {:d}\n'.format( self.r0, self.gm, omega, self.lmax)) for l in range(self.lmax+1): for m in range(l+1): if errors is True: file.write('{:d}, {:d}, {:.16e}, {:.16e}, ' '{:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m], self.errors[0, l, m], self.errors[1, l, m])) else: file.write('{:d}, {:d}, {:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m])) elif format is 'npy': _np.save(filename, self.coeffs, **kwargs) else: raise NotImplementedError( 'format={:s} not implemented'.format(repr(format)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_ref(self, gm=None, r0=None, lmax=None): """ Return a new SHGravCoeffs class instance with a different reference gm or r0. Usage ----- clm = x.change_ref([gm, r0, lmax]) Returns ------- clm : SHGravCoeffs class instance. Parameters gm : float, optional, default = self.gm The gravitational constant time the mass that is associated with the gravitational potential coefficients. r0 : float, optional, default = self.r0 The reference radius of the spherical harmonic coefficients. lmax : int, optional, default = self.lmax Maximum spherical harmonic degree to output. Description This method returns a new class instance of the gravitational potential, but using a difference reference gm or r0. When changing the reference radius r0, the spherical harmonic coefficients will be upward or downward continued under the assumption that the reference radius is exterior to the body. """
if lmax is None: lmax = self.lmax clm = self.pad(lmax) if gm is not None and gm != self.gm: clm.coeffs *= self.gm / gm clm.gm = gm if self.errors is not None: clm.errors *= self.gm / gm if r0 is not None and r0 != self.r0: for l in _np.arange(lmax+1): clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**l if self.errors is not None: clm.errors[:, l, :l+1] *= (self.r0 / r0)**l clm.r0 = r0 return clm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, a=None, f=None, lmax=None, lmax_calc=None, normal_gravity=True, sampling=2): """ Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the gravity field, the gravity disturbance, and the gravitational potential, and return as a SHGravGrid class instance. Usage ----- grav = x.expand([a, f, lmax, lmax_calc, normal_gravity, sampling]) Returns ------- grav : SHGravGrid class instance. Parameters a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree, which determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. normal_gravity : optional, bool, default = True If True, the normal gravity (the gravitational acceleration on the ellipsoid) will be subtracted from the total gravity, yielding the "gravity disturbance." This is done using Somigliana's formula (after converting geocentric to geodetic coordinates). sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description This method will create 2-dimensional cylindrical maps of the three components of the gravity field, the total field, and the gravitational potential, and return these as an SHGravGrid class instance. Each map is stored as an SHGrid class instance using Driscoll and Healy grids that are either equally sampled (n by n) or equally spaced (n by 2n) in latitude and longitude. All grids use geocentric coordinates, the output is in SI units, and the sign of the radial components is positive when directed upwards. If the optional angular rotation rate omega is specified in the SHGravCoeffs instance, the potential and radial gravitational acceleration will be calculated in a body-fixed rotating reference frame. If normal_gravity is set to True, the normal gravity will be removed from the total field, yielding the gravity disturbance. The gravitational potential is given by V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, and the gravitational acceleration is B = Grad V. The coefficients are referenced to the radius r0, and the function is computed on a flattened ellipsoid with semi-major axis a (i.e., the mean equatorial radius) and flattening f. To convert m/s^2 to mGals, multiply the gravity grids by 10^5. """
if a is None: a = self.r0 if f is None: f = 0. if normal_gravity is True: ng = 1 else: ng = 0 if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) rad, theta, phi, total, pot = _MakeGravGridDH( coeffs, self.gm, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling, omega=self.omega, normal_gravity=ng) return _SHGravGrid(rad, theta, phi, total, pot, self.gm, a, f, self.omega, normal_gravity, lmax, lmax_calc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tensor(self, a=None, f=None, lmax=None, lmax_calc=None, degree0=False, sampling=2): """ Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the gravity "gradient" tensor in a local north-oriented reference frame, and return an SHGravTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHGravTensor class instance. Parameters a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. degree0 : optional, default = False If True, include the degree-0 term when calculating the tensor. If False, set the degree-0 term to zero. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description This method will create 2-dimensional cylindrical maps for the 9 components of the gravity 'gradient' tensor and return an SHGravTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The gravitational potential is defined as V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the gravitational acceleration is B = Grad V. The components of the gravity tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of Eotvos (10^-9 s^-2). References Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006. """
if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) if degree0 is False: coeffs[0, 0, 0] = 0. vxx, vyy, vzz, vxy, vxz, vyz = _MakeGravGradGridDH( coeffs, self.gm, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHGravTensor(1.e9*vxx, 1.e9*vyy, 1.e9*vzz, 1.e9*vxy, 1.e9*vxz, 1.e9*vyz, self.gm, a, f, lmax, lmax_calc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geoid(self, potref, a=None, f=None, r=None, omega=None, order=2, lmax=None, lmax_calc=None, grid='DH2'): """ Create a global map of the height of the geoid and return an SHGeoid class instance. Usage ----- geoid = x.geoid(potref, [a, f, r, omega, order, lmax, lmax_calc, grid]) Returns ------- geoid : SHGeoid class instance. Parameters potref : float The value of the potential on the chosen geoid, in m2 / s2. a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. r : optional, float, default = self.r0 The radius of the reference sphere that the Taylor expansion of the potential is calculated on. order : optional, integer, default = 2 The order of the Taylor series expansion of the potential about the reference radius r. This can be either 1, 2, or 3. omega : optional, float, default = self.omega The angular rotation rate of the planet. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grid, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, or 'DH2' for an equidistant lat/lon grid with nlon=2*nlat. Description This method will create a global map of the geoid height, accurate to either first, second, or third order, using the method described in Wieczorek (2007; equation 19-20). The algorithm expands the potential in a Taylor series on a spherical interface of radius r, and computes the height above this interface to the potential potref exactly from the linear, quadratic, or cubic equation at each grid point. If the optional parameters a and f are specified, the geoid height will be referenced to a flattened ellipsoid with semi-major axis a and flattening f. The pseudo-rotational potential is explicitly accounted for by using the angular rotation rate omega of the planet in the SHGravCoeffs class instance. If omega is explicitly specified for this method, it will override the value present in the class instance. Reference Wieczorek, M. A. Gravity and topography of the terrestrial planets, Treatise on Geophysics, 10, 165-206, 2007. """
if a is None: a = self.r0 if f is None: f = 0. if r is None: r = self.r0 if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if grid.upper() in ('DH', 'DH1'): sampling = 1 elif grid.upper() == 'DH2': sampling = 2 else: raise ValueError( "grid must be 'DH', 'DH1', or 'DH2'. " "Input value was {:s}".format(repr(grid))) if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) if omega is None: omega = self.omega geoid = _MakeGeoidGridDH(coeffs, self.r0, self.gm, potref, lmax=lmax, omega=omega, r=r, order=order, lmax_calc=lmax_calc, a=a, f=f, sampling=sampling) return _SHGeoid(geoid, self.gm, potref, a, f, omega, r, order, lmax, lmax_calc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def node_application(self, application_id): """ An application resource contains information about a particular application that was run or is running on this NodeManager. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/node/apps/{appid}'.format(appid=application_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def node_container(self, container_id): """ A container resource contains information about a particular container that is running on this NodeManager. :param str container_id: The container id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/node/containers/{containerid}'.format( containerid=container_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_application_statistics(self, state_list=None, application_type_list=None): """ With the Application Statistics API, you can obtain a collection of triples, each of which contains the application type, the application state and the number of applications of this type and this state in ResourceManager context. This method work in Hadoop > 2.0.0 :param list state_list: states of the applications, specified as a comma-separated list. If states is not provided, the API will enumerate all application states and return the counts of them. :param list application_type_list: types of the applications, specified as a comma-separated list. If application_types is not provided, the API will count the applications of any application type. In this case, the response shows * to indicate any application type. Note that we only support at most one applicationType temporarily. Otherwise, users will expect an BadRequestException. :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/cluster/appstatistics' # TODO: validate state argument states = ','.join(state_list) if state_list is not None else None if application_type_list is not None: application_types = ','.join(application_type_list) else: application_types = None loc_args = ( ('states', states), ('applicationTypes', application_types)) params = self.construct_parameters(loc_args) return self.request(path, **params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_application(self, application_id): """ An application resource contains information about a particular application that was submitted to a cluster. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_application_attempts(self, application_id): """ With the application attempts API, you can obtain a collection of resources that represent an application attempt. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format( appid=application_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_application_attempt_info(self, application_id, attempt_id): """ With the application attempts API, you can obtain an extended info about an application attempt. :param str application_id: The application id :param str attempt_id: The attempt id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format( appid=application_id, attemptid=attempt_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_application_state(self, application_id): """ With the application state API, you can obtain the current state of an application. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/cluster/apps/{appid}/state'.format( appid=application_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_application_kill(self, application_id): """ With the application kill API, you can kill an application that is not in FINISHED or FAILED state. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
data = '{"state": "KILLED"}' path = '/ws/v1/cluster/apps/{appid}/state'.format( appid=application_id) return self.update(path, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_nodes(self, state=None, healthy=None): """ With the Nodes API, you can obtain a collection of resources, each of which represents a node. :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` :raises yarn_api_client.errors.IllegalArgumentError: if `healthy` incorrect """
path = '/ws/v1/cluster/nodes' # TODO: validate state argument legal_healthy = ['true', 'false'] if healthy is not None and healthy not in legal_healthy: msg = 'Valid Healthy arguments are true, false' raise IllegalArgumentError(msg) loc_args = ( ('state', state), ('healthy', healthy), ) params = self.construct_parameters(loc_args) return self.request(path, **params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_node(self, node_id): """ A node resource contains information about a node in the cluster. :param str node_id: The node id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def application_information(self, application_id): """ The MapReduce application master information resource provides overall information about that mapreduce application master. This includes application id, time it was started, user, name, etc. :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/proxy/{appid}/ws/v1/mapreduce/info'.format( appid=application_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jobs(self, application_id): """ The jobs resource provides a list of the jobs running on this application master. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/proxy/{appid}/ws/v1/mapreduce/jobs'.format( appid=application_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job(self, application_id, job_id): """ A job resource contains information about a particular job that was started by this application master. Certain fields are only accessible if user has permissions - depends on acl settings. :param str application_id: The application id :param str job_id: The job id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}'.format( appid=application_id, jobid=job_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job_task(self, application_id, job_id, task_id): """ A Task resource contains information about a particular task within a job. :param str application_id: The application id :param str job_id: The job id :param str task_id: The task id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}'.format( appid=application_id, jobid=job_id, taskid=task_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jobs(self, state=None, user=None, queue=None, limit=None, started_time_begin=None, started_time_end=None, finished_time_begin=None, finished_time_end=None): """ The jobs resource provides a list of the MapReduce jobs that have finished. It does not currently return a full list of parameters. :param str user: user name :param str state: the job state :param str queue: queue name :param str limit: total number of app objects to be returned :param str started_time_begin: jobs with start time beginning with this time, specified in ms since epoch :param str started_time_end: jobs with start time ending with this time, specified in ms since epoch :param str finished_time_begin: jobs with finish time beginning with this time, specified in ms since epoch :param str finished_time_end: jobs with finish time ending with this time, specified in ms since epoch :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` :raises yarn_api_client.errors.IllegalArgumentError: if `state` incorrect """
path = '/ws/v1/history/mapreduce/jobs' legal_states = set([s for s, _ in JobStateInternal]) if state is not None and state not in legal_states: msg = 'Job Internal State %s is illegal' % (state,) raise IllegalArgumentError(msg) loc_args = ( ('state', state), ('user', user), ('queue', queue), ('limit', limit), ('startedTimeBegin', started_time_begin), ('startedTimeEnd', started_time_end), ('finishedTimeBegin', finished_time_begin), ('finishedTimeEnd', finished_time_end)) params = self.construct_parameters(loc_args) return self.request(path, **params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job(self, job_id): """ A Job resource contains information about a particular job identified by jobid. :param str job_id: The job id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job_attempts(self, job_id): """ With the job attempts API, you can obtain a collection of resources that represent a job attempt. """
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format( jobid=job_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job_counters(self, job_id): """ With the job counters API, you can object a collection of resources that represent al the counters for that job. :param str job_id: The job id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format( jobid=job_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job_conf(self, job_id): """ A job configuration resource contains information about the job configuration for this job. :param str job_id: The job id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job_tasks(self, job_id, type=None): """ With the tasks API, you can obtain a collection of resources that represent a task within a job. :param str job_id: The job id :param str type: type of task, valid values are m or r. m for map task or r for reduce task :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format( jobid=job_id) # m - for map # r - for reduce valid_types = ['m', 'r'] if type is not None and type not in valid_types: msg = 'Job type %s is illegal' % (type,) raise IllegalArgumentError(msg) params = {} if type is not None: params['type'] = type return self.request(path, **params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def task_attempt(self, job_id, task_id, attempt_id): """ A Task Attempt resource contains information about a particular task attempt within a job. :param str job_id: The job id :param str task_id: The task id :param str attempt_id: The attempt id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format( jobid=job_id, taskid=task_id, attemptid=attempt_id) return self.request(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def q_mentioned_fields(q, model): """Returns list of field names mentioned in Q object. Q(a__isnull=True, b=F('c')) -> ['a', 'b', 'c'] """
query = Query(model) where = query._add_q(q, used_aliases=set(), allow_joins=False)[0] return list(sorted(set(expression_mentioned_fields(where))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_name_with_model(self, model): """Sets an unique generated name for the index. """
table_name = model._meta.db_table column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders] column_names_with_order = [ (('-%s' if order else '%s') % column_name) for column_name, (field_name, order) in zip(column_names, self.fields_orders) ] # The length of the parts of the name is based on the default max # length of 30 characters. hash_data = [table_name] + column_names_with_order + [self.suffix] + self.name_hash_extra_data() self.name = '%s_%s_%s' % ( table_name[:11], column_names[0][:7], '%s_%s' % (self._hash_generator(*hash_data), self.suffix), ) assert len(self.name) <= self.max_name_length, ( 'Index too long for multiple database support. Is self.suffix ' 'longer than 3 characters?' ) self.check_name()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_partial_unique(self): """Check partial unique constraints on the model and raise ValidationError if any failed. We want to check if another instance already exists with the fields mentioned in idx.fields, but only if idx.where matches. But can't just check for the fields in idx.fields - idx.where may refer to other fields on the current (or other) models. Also can't check for all fields on the current model - should not include irrelevant fields which may hide duplicates. To find potential conflicts, we need to build a queryset which: 1. Filters by idx.fields with their current values on this instance, 2. Filters on idx.where 3. Filters by fields mentioned in idx.where, with their current values on this instance, 4. Excludes current object if it does not match the where condition. Note that step 2 ensures the lookup only looks for conflicts among rows covered by the PartialIndes, and steps 2+3 ensures that the QuerySet is empty if the PartialIndex does not cover the current object. """
# Find PartialIndexes with unique=True defined on model. unique_idxs = [idx for idx in self._meta.indexes if isinstance(idx, PartialIndex) and idx.unique] if unique_idxs: model_fields = set(f.name for f in self._meta.get_fields(include_parents=True, include_hidden=True)) for idx in unique_idxs: where = idx.where if not isinstance(where, Q): raise ImproperlyConfigured( 'ValidatePartialUniqueMixin is not supported for PartialIndexes with a text-based where condition. ' + 'Please upgrade to Q-object based where conditions.' ) mentioned_fields = set(idx.fields) | set(query.q_mentioned_fields(where, self.__class__)) missing_fields = mentioned_fields - model_fields if missing_fields: raise RuntimeError('Unable to use ValidatePartialUniqueMixin: expecting to find fields %s on model. ' + 'This is a bug in the PartialIndex definition or the django-partial-index library itself.') values = {field_name: getattr(self, field_name) for field_name in mentioned_fields} conflict = self.__class__.objects.filter(**values) # Step 1 and 3 conflict = conflict.filter(where) # Step 2 if self.pk: conflict = conflict.exclude(pk=self.pk) # Step 4 if conflict.exists(): raise PartialUniqueValidationError('%s with the same values for %s already exists.' % ( self.__class__.__name__, ', '.join(sorted(idx.fields)), ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extracts( self, page: 'WikipediaPage', **kwargs ) -> str: """ Returns summary of the page with respect to parameters Parameter `exsectionformat` is taken from `Wikipedia` constructor. API Calls for parameters: - https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bextracts - https://www.mediawiki.org/wiki/Extension:TextExtracts#API Example:: import wikipediaapi wiki = wikipediaapi.Wikipedia('en') page = wiki.page('Python_(programming_language)') print(wiki.extracts(page, exsentences=1)) print(wiki.extracts(page, exsentences=2)) :param page: :class:`WikipediaPage` :param kwargs: parameters used in API call :return: summary of the page """
params = { 'action': 'query', 'prop': 'extracts', 'titles': page.title } # type: Dict[str, Any] if self.extract_format == ExtractFormat.HTML: # we do nothing, when format is HTML pass elif self.extract_format == ExtractFormat.WIKI: params['explaintext'] = 1 params['exsectionformat'] = 'wiki' # elif self.extract_format == ExtractFormat.PLAIN: # params['explaintext'] = 1 # params['exsectionformat'] = 'plain' used_params = kwargs used_params.update(params) raw = self._query( page, used_params ) self._common_attributes(raw['query'], page) pages = raw['query']['pages'] for k, v in pages.items(): if k == '-1': page._attributes['pageid'] = -1 return '' else: return self._build_extracts(v, page) return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def langlinks( self, page: 'WikipediaPage', **kwargs ) -> PagesDict: """ Returns langlinks of the page with respect to parameters API Calls for parameters: - https://www.mediawiki.org/w/api.php?action=help&modules=query%2Blanglinks - https://www.mediawiki.org/wiki/API:Langlinks :param page: :class:`WikipediaPage` :param kwargs: parameters used in API call :return: links to pages in other languages """
params = { 'action': 'query', 'prop': 'langlinks', 'titles': page.title, 'lllimit': 500, 'llprop': 'url', } used_params = kwargs used_params.update(params) raw = self._query( page, used_params ) self._common_attributes(raw['query'], page) pages = raw['query']['pages'] for k, v in pages.items(): if k == '-1': page._attributes['pageid'] = -1 return {} else: return self._build_langlinks(v, page) return {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def links( self, page: 'WikipediaPage', **kwargs ) -> PagesDict: """ Returns links to other pages with respect to parameters API Calls for parameters: - https://www.mediawiki.org/w/api.php?action=help&modules=query%2Blinks - https://www.mediawiki.org/wiki/API:Links :param page: :class:`WikipediaPage` :param kwargs: parameters used in API call :return: links to linked pages """
params = { 'action': 'query', 'prop': 'links', 'titles': page.title, 'pllimit': 500, } used_params = kwargs used_params.update(params) raw = self._query( page, used_params ) self._common_attributes(raw['query'], page) pages = raw['query']['pages'] for k, v in pages.items(): if k == '-1': page._attributes['pageid'] = -1 return {} else: while 'continue' in raw: params['plcontinue'] = raw['continue']['plcontinue'] raw = self._query( page, params ) v['links'] += raw['query']['pages'][k]['links'] return self._build_links(v, page) return {}