code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
# no Test case for these
# elif isinstance(t, typedesc.Argument):
# elif isinstance(t, typedesc.CvQualifiedType):
# elif isinstance(t, typedesc.Variable):
# return "%s" % self.type_name(t.typ, generate)
# elif isinstance(t, typedesc.Enumeration):
# return t.name
if isinstance(t, typedesc.FundamentalType):
return self.FundamentalType(t)
elif isinstance(t, typedesc.ArrayType):
return "%s * %s" % (self.type_name(t.typ, generate), t.size)
elif isinstance(t, typedesc.PointerType):
self.enable_pointer_type()
return "POINTER_T(%s)" % (self.type_name(t.typ, generate))
elif isinstance(t, typedesc.FunctionType):
args = [
self.type_name(
x,
generate) for x in [
t.returns] +
list(
t.iterArgTypes())]
if "__stdcall__" in t.attributes:
return "ctypes.WINFUNCTYPE(%s)" % ", ".join(args)
else:
return "ctypes.CFUNCTYPE(%s)" % ", ".join(args)
# elif isinstance(t, typedesc.Structure):
# elif isinstance(t, typedesc.Typedef):
# elif isinstance(t, typedesc.Union):
return t.name | def type_name(self, t, generate=True) | Returns a string containing an expression that can be used to
refer to the type. Assumes the 'from ctypes import *'
namespace is available. | 2.982191 | 2.920622 | 1.021081 |
# FIXME
if self.generate_comments:
self.print_comment(alias)
print("%s = %s # alias" % (alias.name, alias.alias), file=self.stream)
self._aliases += 1
return | def Alias(self, alias) | Handles Aliases. No test cases yet | 7.401573 | 7.226116 | 1.024281 |
if macro.location is None:
log.info('Ignoring %s with no location', macro.name)
return
if self.generate_locations:
print("# %s:%s" % (macro.location), file=self.stream)
if self.generate_comments:
self.print_comment(macro)
print("%s = %s # macro" % (macro.name, macro.body), file=self.stream)
self.macros += 1
self.names.add(macro.name)
return | def Macro(self, macro) | Handles macro. No test cases else that #defines. | 4.218747 | 4.064962 | 1.037832 |
if item in self.done:
return None
if isinstance(item, typedesc.FundamentalType):
return None
if isinstance(item, typedesc.PointerType):
return self.get_undeclared_type(item.typ)
if isinstance(item, typedesc.ArrayType):
return self.get_undeclared_type(item.typ)
# else its an undeclared structure.
return item | def get_undeclared_type(self, item) | Checks if a typed has already been declared in the python output
or is a builtin python type. | 3.383924 | 3.169788 | 1.067555 |
log.debug('HERE in FundamentalType for %s %s', _type, _type.name)
if _type.name in ["None", "c_long_double_t", "c_uint128", "c_int128"]:
self.enable_fundamental_type_wrappers()
return _type.name
return "ctypes.%s" % (_type.name) | def FundamentalType(self, _type) | Returns the proper ctypes class name for a fundamental type
1) activates generation of appropriate headers for
## int128_t
## c_long_double_t
2) return appropriate name for type | 6.302347 | 4.665782 | 1.350759 |
if item in self.done:
return
# verbose output with location.
if self.generate_locations and item.location:
print("# %s:%d" % item.location, file=self.stream)
if self.generate_comments:
self.print_comment(item)
log.debug("generate %s, %s", item.__class__.__name__, item.name)
#
#log.debug('generate: %s( %s )', type(item).__name__, name)
#if name in self.known_symbols:
# log.debug('item is in known_symbols %s'% name )
# mod = self.known_symbols[name]
# print >> self.imports, "from %s import %s" % (mod, name)
# self.done.add(item)
# if isinstance(item, typedesc.Structure):
# self.done.add(item.get_head())
# self.done.add(item.get_body())
# return
#
# to avoid infinite recursion, we have to mark it as done
# before actually generating the code.
self.done.add(item)
# go to specific treatment
mth = getattr(self, type(item).__name__)
mth(item, *args)
return | def _generate(self, item, *args) | wraps execution of specific methods. | 4.4408 | 4.32977 | 1.025643 |
ldata = 200
degrees = np.arange(ldata+1, dtype=float)
degrees[0] = np.inf
power = degrees**(-1)
clm1 = pyshtools.SHCoeffs.from_random(power, exact_power=False)
clm2 = pyshtools.SHCoeffs.from_random(power, exact_power=True)
fig, ax = plt.subplots()
ax.plot(clm1.spectrum(unit='per_l'), label='Normal distributed power')
ax.plot(clm2.spectrum(unit='per_l'), label='Exact power')
ax.set(xscale='log', yscale='log', xlabel='degree l',
ylabel='power per degree l')
ax.grid(which='both')
ax.legend()
plt.show() | def example() | Plot random phase and Gaussian random variable spectra. | 3.644089 | 3.421985 | 1.064905 |
if ax is None:
fig, axes = self.rad.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.rad.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_rad(self, colorbar=True, cb_orientation='vertical',
cb_label='$g_r$, m s$^{-2}$', ax=None, show=True, fname=None,
**kwargs) | Plot the radial component of the gravity field.
Usage
-----
x.plot_rad([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 = '$g_r$, m s$^{-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. | 1.73666 | 2.046936 | 0.848419 |
if ax is None:
fig, axes = self.theta.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.theta.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_theta(self, colorbar=True, cb_orientation='vertical',
cb_label='$g_\\theta$, m s$^{-2}$', ax=None, show=True,
fname=None, **kwargs) | Plot the theta component of the gravity field.
Usage
-----
x.plot_theta([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 = '$g_\\theta$, m s$^{-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. | 1.713806 | 1.998569 | 0.857517 |
if ax is None:
fig, axes = self.phi.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.phi.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_phi(self, colorbar=True, cb_orientation='vertical',
cb_label='$g_\phi$, m s$^{-2}$', ax=None, show=True,
fname=None, **kwargs) | Plot the phi component of the gravity field.
Usage
-----
x.plot_phi([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 = '$g_\phi$, m s$^{-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. | 1.761052 | 2.096796 | 0.839878 |
if self.normal_gravity is True:
if cb_label is None:
cb_label = 'Gravity disturbance, mGal'
else:
if cb_label is None:
cb_label = 'Gravity disturbance, m s$^{-2}$'
if ax is None:
if self.normal_gravity is True:
fig, axes = (self.total*1.e5).plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, show=False, **kwargs)
else:
fig, axes = self.total.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:
if self.normal_gravity is True:
(self.total*1.e5).plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs)
else:
self.total.plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_total(self, colorbar=True, cb_orientation='vertical',
cb_label=None, ax=None, show=True, fname=None, **kwargs) | Plot the total gravity disturbance.
Usage
-----
x.plot_total([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 = 'gravity disturbance'
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.
Notes
-----
If the normal gravity is removed from the total gravitational
acceleration, the output will be displayed in mGals. | 1.79297 | 1.736164 | 1.032719 |
if ax is None:
fig, axes = self.pot.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.pot.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_pot(self, colorbar=True, cb_orientation='vertical',
cb_label='Potential, m$^2$ s$^{-2}$', ax=None, show=True,
fname=None, **kwargs) | Plot the gravitational potential.
Usage
-----
x.plot_pot([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 = 'potential, m s$^{-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. | 1.706247 | 2.034143 | 0.838804 |
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_rad(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_theta(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_phi(colorbar=colorbar, cb_orientation=cb_orientation,
ax=ax.flat[2], tick_interval=tick_interval,
xlabel=xlabel, ylabel=ylabel,
axes_labelsize=axes_labelsize,
minor_tick_interval=minor_tick_interval,
tick_labelsize=tick_labelsize,**kwargs)
self.plot_total(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 | def plot(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 vector components of the gravity field and the gravity
disturbance.
Usage
-----
x.plot([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. | 1.477131 | 1.558381 | 0.947863 |
if type(grid) != str:
raise ValueError('grid must be a string. ' +
'Input type was {:s}'
.format(str(type(grid))))
if nmax is None:
nmax = self.nmax
if self.galpha.kind == 'cap':
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.coeffs, nmax)
else:
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.tapers, nmax)
if grid.upper() in ('DH', 'DH1'):
gridout = _shtools.MakeGridDH(shcoeffs, sampling=1,
norm=1, csphase=1)
return SHGrid.from_array(gridout, grid='DH', copy=False)
elif grid.upper() == 'DH2':
gridout = _shtools.MakeGridDH(shcoeffs, 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.galpha.lmax)
gridout = _shtools.MakeGridGLQ(shcoeffs, 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))) | def expand(self, nmax=None, grid='DH2', zeros=None) | Expand the function on a grid using the first n Slepian coefficients.
Usage
-----
f = x.expand([nmax, grid, zeros])
Returns
-------
f : SHGrid class instance
Parameters
----------
nmax : int, optional, default = x.nmax
The number of expansion coefficients to use when calculating the
spherical harmonic coefficients.
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. | 2.636478 | 2.569355 | 1.026125 |
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))
)
if nmax is None:
nmax = self.nmax
if self.galpha.kind == 'cap':
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.coeffs, nmax)
else:
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.tapers, nmax)
temp = SHCoeffs.from_array(shcoeffs, normalization='4pi', csphase=1)
if normalization != '4pi' or csphase != 1:
return temp.convert(normalization=normalization, csphase=csphase)
else:
return temp | def to_shcoeffs(self, nmax=None, normalization='4pi', csphase=1) | Return the spherical harmonic coefficients using the first n Slepian
coefficients.
Usage
-----
s = x.to_shcoeffs([nmax])
Returns
-------
s : SHCoeffs class instance
The spherical harmonic coefficients obtained from using the first
n Slepian expansion coefficients.
Parameters
----------
nmax : int, optional, default = x.nmax
The maximum number of expansion coefficients to use when
calculating the spherical harmonic coefficients.
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. | 2.430209 | 2.405719 | 1.01018 |
'''
Determine error message to print when a SHTOOLS Fortran 95 routine exits
improperly.
'''
if (status == 1):
errmsg = 'Improper dimensions of input array.'
elif (status == 2):
errmsg = 'Improper bounds for input variable.'
elif (status == 3):
errmsg = 'Error allocating memory.'
elif (status == 4):
errmsg = 'File IO error.'
else:
errmsg = 'Unhandled Fortran 95 error.'
return errmsg | def _shtools_status_message(status) | Determine error message to print when a SHTOOLS Fortran 95 routine exits
improperly. | 4.836959 | 2.881132 | 1.67884 |
if theta_degrees:
tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(
_np.radians(theta), lmax)
else:
tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(
theta, lmax)
return SlepianCap(theta, tapers, eigenvalues, taper_order, clat, clon,
nmax, theta_degrees, coord_degrees, dj_matrix,
copy=False) | def from_cap(cls, theta, lmax, clat=None, clon=None, nmax=None,
theta_degrees=True, coord_degrees=True, dj_matrix=None) | Construct spherical cap Slepian functions.
Usage
-----
x = Slepian.from_cap(theta, lmax, [clat, clon, nmax, theta_degrees,
coord_degrees, dj_matrix])
Returns
-------
x : Slepian class instance
Parameters
----------
theta : float
Angular radius of the spherical-cap localization domain (default
in degrees).
lmax : int
Spherical harmonic bandwidth of the Slepian functions.
clat, clon : float, optional, default = None
Latitude and longitude of the center of the rotated spherical-cap
Slepian functions (default in degrees).
nmax : int, optional, default (lmax+1)**2
Number of Slepian functions to compute.
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. | 3.593344 | 4.116504 | 0.872912 |
if nmax is None:
nmax = (lmax + 1)**2
else:
if nmax > (lmax + 1)**2:
raise ValueError('nmax must be less than or equal to ' +
'(lmax + 1)**2. lmax = {:d} and nmax = {:d}'
.format(lmax, nmax))
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, lmax,
ntapers=nmax)
return SlepianMask(tapers, eigenvalues, area, copy=False) | def from_mask(cls, dh_mask, lmax, nmax=None) | Construct Slepian functions that are optimally concentrated within
the region specified by a mask.
Usage
-----
x = Slepian.from_mask(dh_mask, lmax, [nmax])
Returns
-------
x : Slepian 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.
lmax : int
The spherical harmonic bandwidth of the Slepian functions.
nmax : int, optional, default = (lmax+1)**2
The number of best-concentrated eigenvalues and eigenfunctions to
return. | 2.963971 | 2.83879 | 1.044097 |
if nmax is None:
nmax = (self.lmax+1)**2
elif nmax is not None and nmax > (self.lmax+1)**2:
raise ValueError(
"nmax must be less than or equal to (lmax+1)**2 " +
"where lmax is {:s}. Input value is {:s}"
.format(repr(self.lmax), repr(nmax))
)
coeffsin = flm.to_array(normalization='4pi', csphase=1, lmax=self.lmax)
return self._expand(coeffsin, nmax) | def expand(self, flm, nmax=None) | Return the Slepian expansion coefficients of the input function.
Usage
-----
s = x.expand(flm, [nmax])
Returns
-------
s : SlepianCoeff class instance
The Slepian expansion coefficients of the input function.
Parameters
----------
flm : SHCoeffs class instance
The input function to expand in Slepian functions.
nmax : int, optional, default = (x.lmax+1)**2
The number of Slepian expansion coefficients to compute.
Description
-----------
The global function f is input using its spherical harmonic
expansion coefficients flm. The expansion coefficients of the function
f using Slepian functions g is given by
f_alpha = sum_{lm}^{lmax} f_lm g(alpha)_lm | 3.337901 | 3.275884 | 1.018931 |
if alpha is None:
if nmax is None:
nmax = self.nmax
spectra = _np.zeros((self.lmax+1, nmax))
for iwin in range(nmax):
coeffs = self.to_array(iwin)
spectra[:, iwin] = _spectrum(coeffs, normalization='4pi',
convention=convention, unit=unit,
base=base)
else:
coeffs = self.to_array(alpha)
spectra = _spectrum(coeffs, normalization='4pi',
convention=convention, unit=unit, base=base)
return spectra | def spectra(self, alpha=None, nmax=None, convention='power', unit='per_l',
base=10.) | Return the spectra of one or more Slepian functions.
Usage
-----
spectra = x.spectra([alpha, nmax, convention, unit, base])
Returns
-------
spectra : ndarray, shape (lmax+1, nmax)
A matrix with each column containing the spectrum of a Slepian
function, and where the functions are arranged with increasing
concentration factors. If alpha is set, only a single vector is
returned, whereas if nmax is set, the first nmax spectra are
returned.
Parameters
----------
alpha : int, optional, default = None
The function number of the output spectrum, where alpha=0
corresponds to the best concentrated Slepian function.
nmax : int, optional, default = 1
The number of best concentrated Slepian function 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 Slepian funtions. 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). | 2.673187 | 2.767267 | 0.966002 |
if self.coeffs is None:
self.rotate(clat=90., clon=0., nrot=nmax)
falpha = _shtools.SlepianCoeffs(self.coeffs, coeffsin, self.nrot)
else:
falpha = _shtools.SlepianCoeffs(self.coeffs, coeffsin, self.nrot)
return SlepianCoeffs(falpha, self) | def _expand(self, coeffsin, nmax) | Determine the Slepian expansion coefficients of a function. | 5.011766 | 4.501101 | 1.113453 |
taperm = self.orders[alpha]
coeffs = _np.zeros((2, self.lmax + 1, self.lmax + 1))
if taperm < 0:
coeffs[1, :, abs(taperm)] = self.tapers[:, alpha]
else:
coeffs[0, :, abs(taperm)] = self.tapers[:, alpha]
return coeffs | def _taper2coeffs(self, alpha) | Return the spherical harmonic coefficients of the unrotated Slepian
function i as an array, where i = 0 is the best concentrated function. | 3.938465 | 3.9328 | 1.001441 |
if self.coeffs is None:
coeffs = _np.copy(self._taper2coeffs(alpha))
else:
if alpha > self.nrot - 1:
raise ValueError('alpha must be less than or equal to ' +
'nrot - 1. alpha = {:d}, nrot = {:d}'
.format(alpha, self.nrot))
coeffs = _shtools.SHVectorToCilm(self.coeffs[:, alpha])
if normalization == 'schmidt':
for l in range(self.lmax + 1):
coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
elif normalization == 'ortho':
coeffs *= _np.sqrt(4.0 * _np.pi)
if csphase == -1:
for m in range(self.lmax + 1):
if m % 2 == 1:
coeffs[:, :, m] = - coeffs[:, :, m]
return coeffs | def _to_array(self, alpha, normalization='4pi', csphase=1) | Return the spherical harmonic coefficients of Slepian function i as an
array, where i = 0 is the best concentrated function. | 3.279573 | 3.184323 | 1.029912 |
falpha = _shtools.SlepianCoeffs(self.tapers, coeffsin, nmax)
return SlepianCoeffs(falpha, self) | def _expand(self, coeffsin, nmax) | Determine the Slepian expansion coefficients of a function. | 10.318316 | 7.798131 | 1.323178 |
coeffs = _shtools.SHVectorToCilm(self.tapers[:, alpha])
if normalization == 'schmidt':
for l in range(self.lmax + 1):
coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
elif normalization == 'ortho':
coeffs *= _np.sqrt(4.0 * _np.pi)
if csphase == -1:
for m in range(self.lmax + 1):
if m % 2 == 1:
coeffs[:, :, m] = - coeffs[:, :, m]
return coeffs | def _to_array(self, alpha, normalization='4pi', csphase=1) | Return the spherical harmonic coefficients of Slepian function i as an
array, where i=0 is the best concentrated function. | 3.433356 | 3.399576 | 1.009936 |
if ax is None:
fig, axes = self.total.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.total.plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_total(self, colorbar=True, cb_orientation='vertical',
cb_label='$|B|$, nT', ax=None, show=True, fname=None,
**kwargs) | Plot the total magnetic intensity.
Usage
-----
x.plot_total([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 = '$|B|$, nT'
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. | 1.715566 | 2.058744 | 0.833307 |
if _np.iscomplexobj(coeffs):
raise TypeError('The input array must be real.')
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))
)
if errors is not None:
if coeffs.shape != errors.shape:
raise ValueError(
"The shape of coeffs and errors must be the same."
"Shape of coeffs = {:s}, shape of errors = {:s}"
.format(repr(coeffs.shape), repr(coeffs.errors))
)
lmaxin = coeffs.shape[1] - 1
if lmax is None:
lmax = lmaxin
else:
if lmax > lmaxin:
lmax = lmaxin
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 errors is not None:
clm = SHMagRealCoeffs(coeffs[:, 0:lmax+1, 0:lmax+1], r0=r0,
errors=errors[:, 0:lmax+1, 0:lmax+1],
normalization=normalization.lower(),
csphase=csphase, copy=copy)
else:
clm = SHMagRealCoeffs(coeffs[:, 0:lmax+1, 0:lmax+1], r0=r0,
normalization=normalization.lower(),
csphase=csphase, copy=copy)
return clm | def from_array(self, coeffs, r0, errors=None, normalization='schmidt',
csphase=1, lmax=None, copy=True) | Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHMagCoeffs.from_array(array, r0, [errors, normalization, csphase,
lmax, copy])
Returns
-------
x : SHMagCoeffs class instance.
Parameters
----------
array : ndarray, shape (2, lmaxin+1, lmaxin+1).
The input spherical harmonic coefficients.
r0 : float
The reference radius of the spherical harmonic coefficients.
errors : ndarray, optional, default = None
The uncertainties of the spherical harmonic coefficients.
normalization : str, optional, default = 'schmidt'
'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 : int, optional, default = None
The maximum spherical harmonic degree to include in the returned
class instance. This must be less than or equal to lmaxin.
copy : bool, optional, default = True
If True, make a copy of array when initializing the class instance.
If False, initialize the class instance with a reference to array.
Notes
-----
The coefficients in the input array are assumed to have units of nT. | 2.029154 | 1.843296 | 1.100829 |
# Ensure that the type is correct
values = _np.array(values)
ls = _np.array(ls)
ms = _np.array(ms)
mneg_mask = (ms < 0).astype(_np.int)
self.coeffs[mneg_mask, ls, _np.abs(ms)] = values | def set_coeffs(self, values, ls, ms) | Set spherical harmonic coefficients in-place to specified values.
Usage
-----
x.set_coeffs(values, ls, ms)
Parameters
----------
values : float (list)
The value(s) of the spherical harmonic coefficient(s).
ls : int (list)
The degree(s) of the coefficient(s) that should be set.
ms : int (list)
The order(s) of the coefficient(s) that should be set. Positive
and negative values correspond to the cosine and sine
components, respectively.
Examples
--------
x.set_coeffs(10., 1, 1) # x.coeffs[0, 1, 1] = 10.
x.set_coeffs(5., 1, -1) # x.coeffs[1, 1, 1] = 5.
x.set_coeffs([1., 2], [1, 2], [0, -2]) # x.coeffs[0, 1, 0] = 1.
# x.coeffs[1, 2, 2] = 2. | 4.069285 | 4.255247 | 0.956298 |
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)
if self.errors is not None:
errors = _convert(self.errors, normalization_in=self.normalization,
normalization_out=normalization,
csphase_in=self.csphase, csphase_out=csphase,
lmax=lmax)
return coeffs, errors
else:
return coeffs | def to_array(self, normalization=None, csphase=None, lmax=None) | Return spherical harmonic coefficients (and errors) as a numpy array.
Usage
-----
coeffs, [errors] = x.to_array([normalization, csphase, lmax])
Returns
-------
coeffs : ndarry, shape (2, lmax+1, lmax+1)
numpy ndarray of the spherical harmonic coefficients.
errors : ndarry, shape (2, lmax+1, lmax+1)
numpy ndarray of the errors of the spherical harmonic coefficients
if they are not None.
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 the errors of the coefficients are set, they will be
output as a separate array. | 1.57257 | 1.599988 | 0.982864 |
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) | 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. | 1.819914 | 1.698618 | 1.071408 |
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 | 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. | 1.786165 | 1.832826 | 0.974541 |
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 | 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. | 2.857186 | 2.89627 | 0.986505 |
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) | 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. | 3.104939 | 2.567515 | 1.209317 |
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 | 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. | 3.248134 | 2.876065 | 1.129367 |
# ---- 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 | 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. | 4.543833 | 4.115574 | 1.104058 |
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) | 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. | 3.622627 | 3.680443 | 0.984291 |
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) | 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. | 3.098976 | 2.832755 | 1.093979 |
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) | 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. | 2.031988 | 2.130975 | 0.953549 |
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) | 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. | 1.996986 | 2.057261 | 0.970702 |
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))) | 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. | 2.314469 | 2.214828 | 1.044988 |
return self._multitaper_spectrum(clm, k, convention=convention,
unit=unit, **kwargs) | 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. | 2.410269 | 5.533176 | 0.435603 |
return self._multitaper_cross_spectrum(clm, slm, k,
convention=convention,
unit=unit, **kwargs) | 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. | 2.28215 | 4.49076 | 0.508188 |
return self._biased_spectrum(power, k, convention=convention,
unit=unit, **kwargs) | def biased_spectrum(self, power, k, convention='power', unit='per_l',
**kwargs) | Calculate the multitaper (cross-)spectrum expectation of a
localized function.
Usage
-----
outspectrum = x.biased_spectrum(spectrum, k, [unit, power, taper_wt,
save_cg, ldata])
Returns
-------
outspectrum : ndarray, shape (ldata+lwin+1)
The expectation of the windowed spectrum, where ldata is the
spherical-harmonic bandwidth of the input spectrum, and lwin is the
spherical-harmonic bandwidth of the localization windows.
Parameters
----------
spectrum : ndarray, shape (ldata+1)
The global spectrum.
k : int
The number of best-concentrated localization windows to use in
constructing the windowed spectrum.
convention : str, optional, default = 'power'
The type of input global and output biased spectra: 'power' for
power spectra, and 'energy' for energy spectra.
unit : str, optional, default = 'per_l'
The units of the input global and output biased 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.
taper_wt : ndarray, optional, default = None
The weights used in calculating the multitaper spectral estimates
and standard error.
save_cg : int, optional, default = 0
If 1, the Clebsch-Gordon coefficients will be precomputed and saved
for future use. If 0, the Clebsch-Gordon coefficients will be
recomputed for each call.
ldata : int, optional, default = len(power)-1
The maximum degree of the global unwindowed spectrum. | 2.634682 | 6.345843 | 0.415182 |
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 | 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). | 2.518591 | 2.397177 | 1.050649 |
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)) | 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. | 1.841015 | 1.787617 | 1.029871 |
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 | 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. | 1.603733 | 1.770346 | 0.905887 |
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 | def _taper2coeffs(self, itaper) | Return the spherical harmonic coefficients of the unrotated taper i
as an array, where i = 0 is the best concentrated. | 4.114479 | 3.992618 | 1.030522 |
if self.coeffs is None:
coeffs = _np.copy(self._taper2coeffs(itaper))
else:
if itaper > self.nwinrot - 1:
raise ValueError('itaper must be less than or equal to ' +
'nwinrot - 1. itaper = {:d}, nwinrot = {:d}'
.format(itaper, self.nwinrot))
coeffs = _shtools.SHVectorToCilm(self.coeffs[:, itaper])
if normalization == 'schmidt':
for l in range(self.lwin + 1):
coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
elif normalization == 'ortho':
coeffs *= _np.sqrt(4.0 * _np.pi)
if csphase == -1:
for m in range(self.lwin + 1):
if m % 2 == 1:
coeffs[:, :, m] = - coeffs[:, :, m]
return coeffs | def _to_array(self, itaper, normalization='4pi', csphase=1) | Return the spherical harmonic coefficients of taper i as an
array, where i = 0 is the best concentrated. | 3.349682 | 3.210892 | 1.043224 |
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 | 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. | 2.795526 | 2.263902 | 1.234826 |
if nwin is None:
nwin = self.nwin
if weights is None:
weights = self.weights
if weights is None:
return _shtools.SHMTCouplingMatrix(lmax, self.tapers**2, k=nwin)
else:
return _shtools.SHMTCouplingMatrix(lmax, self.tapers**2, k=nwin,
taper_wt=self.weights) | def _coupling_matrix(self, lmax, nwin=None, weights=None) | Return the coupling matrix of the first nwin tapers. | 3.385814 | 3.065946 | 1.104329 |
if lmax is None:
lmax = clm.lmax
if (clat is not None and clon is not None and clat == self.clat and
clon == self.clon and coord_degrees is self.coord_degrees and
k <= self.nwinrot):
# use the already stored coeffs
pass
elif (clat is None and clon is None) and \
(self.clat is not None and self.clon is not None and
k <= self.nwinrot):
# use the already stored coeffs
pass
else:
if clat is None:
clat = self.clat
if clon is None:
clon = self.clon
if (clat is None and clon is not None) or \
(clat is not None and clon is None):
raise ValueError('clat and clon must both be input. ' +
'clat = {:s}, clon = {:s}'
.format(repr(clat), repr(clon)))
if clat is None and clon is None:
self.rotate(clat=90., clon=0., coord_degrees=True, nwinrot=k)
else:
self.rotate(clat=clat, clon=clon, coord_degrees=coord_degrees,
nwinrot=k)
sh = clm.to_array(normalization='4pi', csphase=1, lmax=lmax)
if taper_wt is None:
mtse, sd = _shtools.SHMultiTaperMaskSE(sh, self.coeffs,
lmax=lmax, k=k)
else:
mtse, sd = _shtools.SHMultiTaperMaskSE(sh, self.coeffs, lmax=lmax,
k=k, taper_wt=taper_wt)
if (unit == 'per_l'):
pass
elif (unit == 'per_lm'):
degree_l = _np.arange(len(mtse))
mtse /= (2.0 * degree_l + 1.0)
sd /= (2.0 * degree_l + 1.0)
else:
raise ValueError(
"unit must be 'per_l' or 'per_lm'." +
"Input value was {:s}".format(repr(unit)))
if (convention == 'power'):
return mtse, sd
elif (convention == 'energy'):
return mtse * 4.0 * _np.pi, sd * 4.0 * _np.pi
else:
raise ValueError(
"convention must be 'power' or 'energy'." +
"Input value was {:s}".format(repr(convention))) | def _multitaper_spectrum(self, clm, k, convention='power', unit='per_l',
clat=None, clon=None, coord_degrees=True,
lmax=None, taper_wt=None) | Return the multitaper spectrum estimate and standard error for an
input SHCoeffs class instance. | 2.328032 | 2.252114 | 1.03371 |
if lmax is None:
lmax = min(clm.lmax, slm.lmax)
if (clat is not None and clon is not None and clat == self.clat and
clon == self.clon and coord_degrees is self.coord_degrees and
k <= self.nwinrot):
# use the already stored coeffs
pass
elif (clat is None and clon is None) and \
(self.clat is not None and self.clon is not None and
k <= self.nwinrot):
# use the already stored coeffs
pass
else:
if clat is None:
clat = self.clat
if clon is None:
clon = self.clon
if (clat is None and clon is not None) or \
(clat is not None and clon is None):
raise ValueError('clat and clon must both be input. ' +
'clat = {:s}, clon = {:s}'
.format(repr(clat), repr(clon)))
if clat is None and clon is None:
self.rotate(clat=90., clon=0., coord_degrees=True, nwinrot=k)
else:
self.rotate(clat=clat, clon=clon, coord_degrees=coord_degrees,
nwinrot=k)
sh1 = clm.to_array(normalization='4pi', csphase=1, lmax=lmax)
sh2 = slm.to_array(normalization='4pi', csphase=1, lmax=lmax)
if taper_wt is None:
mtse, sd = _shtools.SHMultiTaperMaskCSE(sh1, sh2, self.coeffs,
lmax1=lmax, lmax2=lmax,
k=k)
else:
mtse, sd = _shtools.SHMultiTaperMaskCSE(sh1, sh2, self.coeffs,
lmax1=lmax, lmax2=lmax,
k=k, taper_wt=taper_wt)
if (unit == 'per_l'):
pass
elif (unit == 'per_lm'):
degree_l = _np.arange(len(mtse))
mtse /= (2.0 * degree_l + 1.0)
sd /= (2.0 * degree_l + 1.0)
else:
raise ValueError(
"unit must be 'per_l' or 'per_lm'." +
"Input value was {:s}".format(repr(unit)))
if (convention == 'power'):
return mtse, sd
elif (convention == 'energy'):
return mtse * 4.0 * _np.pi, sd * 4.0 * _np.pi
else:
raise ValueError(
"convention must be 'power' or 'energy'." +
"Input value was {:s}".format(repr(convention))) | def _multitaper_cross_spectrum(self, clm, slm, k, convention='power',
unit='per_l', clat=None, clon=None,
coord_degrees=True, lmax=None,
taper_wt=None) | Return the multitaper cross-spectrum estimate and standard error for
two input SHCoeffs class instances. | 2.228705 | 2.166496 | 1.028714 |
coeffs = _shtools.SHVectorToCilm(self.tapers[:, itaper])
if normalization == 'schmidt':
for l in range(self.lwin + 1):
coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
elif normalization == 'ortho':
coeffs *= _np.sqrt(4.0 * _np.pi)
if csphase == -1:
for m in range(self.lwin + 1):
if m % 2 == 1:
coeffs[:, :, m] = - coeffs[:, :, m]
return coeffs | def _to_array(self, itaper, normalization='4pi', csphase=1) | Return the spherical harmonic coefficients of taper i as an
array, where i=0 is the best concentrated. | 3.741787 | 3.465992 | 1.079572 |
if nwin is None:
nwin = self.nwin
if weights is None:
weights = self.weights
tapers_power = _np.zeros((self.lwin+1, nwin))
for i in range(nwin):
tapers_power[:, i] = _spectrum(self.to_array(i),
normalization='4pi',
convention='power', unit='per_l')
if weights is None:
return _shtools.SHMTCouplingMatrix(lmax, tapers_power, k=nwin)
else:
return _shtools.SHMTCouplingMatrix(lmax, tapers_power, k=nwin,
taper_wt=self.weights) | def _coupling_matrix(self, lmax, nwin=None, weights=None) | Return the coupling matrix of the first nwin tapers. | 4.22186 | 4.00645 | 1.053766 |
if lmax is None:
lmax = clm.lmax
sh = clm.to_array(normalization='4pi', csphase=1, lmax=lmax)
if taper_wt is None:
mtse, sd = _shtools.SHMultiTaperMaskSE(sh, self.tapers, lmax=lmax,
k=k)
else:
mtse, sd = _shtools.SHMultiTaperMaskSE(sh, self.tapers, lmax=lmax,
k=k, taper_wt=taper_wt)
if (unit == 'per_l'):
pass
elif (unit == 'per_lm'):
degree_l = _np.arange(len(mtse))
mtse /= (2.0 * degree_l + 1.0)
sd /= (2.0 * degree_l + 1.0)
else:
raise ValueError(
"unit must be 'per_l' or 'per_lm'." +
"Input value was {:s}".format(repr(unit)))
if (convention == 'power'):
return mtse, sd
elif (convention == 'energy'):
return mtse * 4.0 * _np.pi, sd * 4.0 * _np.pi
else:
raise ValueError(
"convention must be 'power' or 'energy'." +
"Input value was {:s}".format(repr(convention))) | def _multitaper_spectrum(self, clm, k, convention='power', unit='per_l',
lmax=None, taper_wt=None) | Return the multitaper spectrum estimate and standard error for an
input SHCoeffs class instance. | 2.48546 | 2.354989 | 1.055402 |
if lmax is None:
lmax = min(clm.lmax, slm.lmax)
sh1 = clm.to_array(normalization='4pi', csphase=1, lmax=lmax)
sh2 = slm.to_array(normalization='4pi', csphase=1, lmax=lmax)
if taper_wt is None:
mtse, sd = _shtools.SHMultiTaperMaskCSE(sh1, sh2, self.tapers,
lmax=lmax, k=k)
else:
mtse, sd = _shtools.SHMultiTaperMaskCSE(sh1, sh2, self.tapers,
lmax=lmax, k=k,
taper_wt=taper_wt)
if (unit == 'per_l'):
pass
elif (unit == 'per_lm'):
degree_l = _np.arange(len(mtse))
mtse /= (2.0 * degree_l + 1.0)
sd /= (2.0 * degree_l + 1.0)
else:
raise ValueError(
"unit must be 'per_l' or 'per_lm'." +
"Input value was {:s}".format(repr(unit)))
if (convention == 'power'):
return mtse, sd
elif (convention == 'energy'):
return mtse * 4.0 * _np.pi, sd * 4.0 * _np.pi
else:
raise ValueError(
"convention must be 'power' or 'energy'." +
"Input value was {:s}".format(repr(convention))) | def _multitaper_cross_spectrum(self, clm, slm, k, convention='power',
unit='per_l', lmax=None, taper_wt=None) | Return the multitaper cross-spectrum estimate and standard error for
two input SHCoeffs class instances. | 2.302921 | 2.186738 | 1.053131 |
# The equation is not modified if the in- and out- spectra are power
# or energy. However, the convention can not be l2norm, which depends
# upon the normalization of the coefficients.
if (convention != 'power' and convention != 'energy'):
raise ValueError(
"convention must be 'power' or 'energy'." +
"Input value was {:s}".format(repr(convention)))
if (unit == 'per_l'):
outspectrum = _shtools.SHBiasKMask(self.tapers, spectrum, k=k,
**kwargs)
elif (unit == 'per_lm'):
degree_l = _np.arange(len(spectrum))
temp = spectrum * (2.0 * degree_l + 1.0)
outspectrum = _shtools.SHBiasKMask(self.tapers, temp, k=k,
**kwargs)
outspectrum /= (2.0 * degree_l + 1.0)
else:
raise ValueError(
"unit must be 'per_l' or 'per_lm'." +
"Input value was {:s}".format(repr(unit)))
return outspectrum | def _biased_spectrum(self, spectrum, k, convention='power', unit='per_l',
**kwargs) | Calculate the multitaper (cross-) spectrum expectation of a function
localized by arbitary windows. | 3.929859 | 3.944344 | 0.996328 |
self.i0 = self.vxx + self.vyy + self.vzz
self.i1 = (self.vxx*self.vyy + self.vyy*self.vzz + self.vxx*self.vzz -
self.vxy**2 - self.vyz**2 - self.vxz**2)
self.i2 = (self.vxx*(self.vyy*self.vzz - self.vyz**2) +
self.vxy*(self.vyz*self.vxz - self.vxy*self.vzz) +
self.vxz*(self.vxy*self.vyz - self.vxz*self.vyy))
self.i = (-1.) * (self.i2 / 2.)**2
self.i.data[1:, :] /= (self.i1.data[1:, :] / 3.)**3 | def compute_invar(self) | Compute the three invariants (I0, I1, I2) of the tensor, as well as
the quantity I = -(I2/2)**2 / (I1/3)**3. | 2.395625 | 2.021655 | 1.184982 |
self.eig1 = _SHGrid.from_array(_np.zeros_like(self.vxx.data),
grid='DH')
self.eig2 = _SHGrid.from_array(_np.zeros_like(self.vxx.data),
grid='DH')
self.eig3 = _SHGrid.from_array(_np.zeros_like(self.vxx.data),
grid='DH')
for i in range(self.nlat):
for j in range(self.nlon):
a = _np.array([[self.vxx.data[i, j],
self.vxy.data[i, j],
self.vxz.data[i, j]],
[self.vyx.data[i, j],
self.vyy.data[i, j],
self.vyz.data[i, j]],
[self.vzx.data[i, j],
self.vzy.data[i, j],
self.vzz.data[i, j]]])
eigs = _eigvalsh(a)
self.eig1.data[i, j] = eigs[2]
self.eig2.data[i, j] = eigs[1]
self.eig3.data[i, j] = eigs[0] | def compute_eig(self) | Compute the three eigenvalues of the tensor: eig1, eig2, ei3. | 1.758176 | 1.67733 | 1.048199 |
self.eigh1 = _SHGrid.from_array(_np.zeros_like(self.vxx.data),
grid='DH')
self.eigh2 = _SHGrid.from_array(_np.zeros_like(self.vxx.data),
grid='DH')
self.eighh = _SHGrid.from_array(_np.zeros_like(self.vxx.data),
grid='DH')
for i in range(self.nlat):
for j in range(self.nlon):
a = _np.array([[self.vxx.data[i, j],
self.vxy.data[i, j]],
[self.vyx.data[i, j],
self.vyy.data[i, j]]])
eigs = _eigvalsh(a)
self.eigh1.data[i, j] = eigs[1]
self.eigh2.data[i, j] = eigs[0]
if abs(eigs[0]) >= abs(eigs[1]):
self.eighh.data[i, j] = eigs[0]
else:
self.eighh.data[i, j] = eigs[1] | def compute_eigh(self) | Compute the two horizontal eigenvalues of the tensor (eigh1, and
eigh2), as well as the combined maximum absolute value of the two
(eighh). | 1.946044 | 1.784612 | 1.090458 |
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) | 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. | 1.737735 | 2.025666 | 0.857858 |
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) | 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. | 1.73791 | 2.036034 | 0.853576 |
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) | 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. | 1.745698 | 2.047911 | 0.852429 |
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) | 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. | 1.756477 | 2.017079 | 0.870802 |
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) | 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. | 1.78252 | 2.087936 | 0.853724 |
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) | 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. | 1.753365 | 2.041861 | 0.858709 |
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) | 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. | 1.742828 | 2.024994 | 0.860658 |
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) | 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. | 1.772613 | 2.108889 | 0.840543 |
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) | 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. | 1.731398 | 2.032582 | 0.851822 |
if cb_label is None:
cb_label = self._i0_label
if self.i0 is None:
self.compute_invar()
if ax is None:
fig, axes = self.i0.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.i0.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_i0(self, colorbar=True, cb_orientation='vertical',
cb_label=None, ax=None, show=True, fname=None, **kwargs) | Plot the first invariant I0 (the trace) of the tensor
I0 = vxx + vyy + vzz
which should be identically zero.
Usage
-----
x.plot_i0([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 = 'Tr $V_{ij}$'
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. | 1.980922 | 2.275219 | 0.870651 |
if cb_label is None:
cb_label = self._i1_label
if self.i1 is None:
self.compute_invar()
if ax is None:
fig, axes = self.i1.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.i1.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_i1(self, colorbar=True, cb_orientation='vertical',
cb_label=None, ax=None, show=True, fname=None, **kwargs) | Plot the second invariant I1 of the tensor:
I1 = vxx*vyy + vyy*vzz + vxx*vzz - vxy**2 - vyz**2 - vxz**2
Usage
-----
x.plot_i1([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 = '$I_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. | 1.969382 | 2.223373 | 0.885763 |
if cb_label is None:
cb_label = self._i2_label
if self.i2 is None:
self.compute_invar()
if ax is None:
fig, axes = self.i2.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.i2.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_i2(self, colorbar=True, cb_orientation='vertical',
cb_label=None, ax=None, show=True, fname=None, **kwargs) | Plot the third invariant I2 (the determinant) of the tensor:
I2 = vxx*(vyy*vzz - vyz**2) + vxy*(vyz*vxz - vxy*vzz)
+ vxz*(vxy*vyz - vxz*vyy)
Usage
-----
x.plot_i2([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 = 'det $V_{ij}$'
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. | 1.972461 | 2.224842 | 0.886562 |
if cb_label is None:
cb_label = self._i_label
if self.i is None:
self.compute_invar()
if ax is None:
fig, axes = self.i.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.i.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) | def plot_i(self, colorbar=True, cb_orientation='vertical',
cb_label=None, ax=None, show=True, fname=None, **kwargs) | Plot the dimensionless quantity I of Pedersen and Rasmussen (1990)
I = -(I2/2)**2 / (I1/3)**3
that is bounded by 0 and 1.
Usage
-----
x.plot_i([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 = '$-(I_2/2)^{2} / (I_1/3)^{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. | 1.986243 | 2.260373 | 0.878724 |
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 | 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. | 1.430316 | 1.488696 | 0.960785 |
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) | 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. | 1.777364 | 2.094292 | 0.848671 |
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) | 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. | 1.789871 | 2.113045 | 0.847058 |
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) | 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. | 1.785359 | 2.106384 | 0.847594 |
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 | 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. | 1.512364 | 1.597049 | 0.946974 |
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) | 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. | 1.747223 | 1.98045 | 0.882235 |
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) | 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. | 1.758707 | 1.9854 | 0.88582 |
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) | 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. | 1.749699 | 1.986944 | 0.880598 |
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 | 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. | 1.600249 | 1.697888 | 0.942494 |
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 | 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 | 3.36836 | 3.021211 | 1.114904 |
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 | def get_compiler_flags() | Set fortran flags depending on the compiler. | 5.475964 | 5.153579 | 1.062555 |
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 | def configuration(parent_package='', top_path=None) | Configure all packages that need to be built. | 3.568209 | 3.572069 | 0.998919 |
print('---- BUILDING ----')
_build.run(self)
# build documentation
print('---- BUILDING DOCS ----')
docdir = os.path.join(self.build_lib, 'pyshtools', 'doc')
self.mkpath(docdir)
doc_builder = os.path.join(self.build_lib, 'pyshtools', 'make_docs.py')
doc_source = '.'
check_call([sys.executable, doc_builder, doc_source, self.build_lib])
print('---- ALL DONE ----') | def run(self) | Build the Fortran library, all python extensions and the docs. | 3.474157 | 3.065601 | 1.133271 |
print('---- CUSTOM DEVELOP ----')
_develop.run(self)
# build documentation
print('---- BUILDING DOCS ----')
docdir = os.path.join(self.setup_path, 'pyshtools', 'doc')
self.mkpath(docdir)
doc_builder = os.path.join(self.setup_path, 'pyshtools',
'make_docs.py')
doc_source = '.'
check_call([sys.executable, doc_builder, doc_source, self.setup_path])
print('---- ALL DONE ----') | def run(self) | Build the Fortran library, all python extensions and the docs. | 4.631189 | 4.124975 | 1.122719 |
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 | 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). | 2.795751 | 2.757543 | 1.013856 |
# 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'] | def modify_subroutine(subroutine) | loops through variables of a subroutine and modifies them | 6.842419 | 6.820755 | 1.003176 |
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]) | 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') | 2.056563 | 2.177752 | 0.944351 |
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) | 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. | 2.117582 | 2.07353 | 1.021245 |
if _np.iscomplexobj(coeffs):
kind = 'complex'
else:
kind = 'real'
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))
)
lmaxin = coeffs.shape[1] - 1
if lmax is None:
lmax = lmaxin
else:
if lmax > lmaxin:
lmax = lmaxin
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
for cls in self.__subclasses__():
if cls.istype(kind):
return cls(coeffs[:, 0:lmax+1, 0:lmax+1],
normalization=normalization.lower(),
csphase=csphase, copy=copy) | def from_array(self, coeffs, normalization='4pi', csphase=1, lmax=None,
copy=True) | Initialize the class with spherical harmonic coefficients from an input
array.
Usage
-----
x = SHCoeffs.from_array(array, [normalization, csphase, lmax, copy])
Returns
-------
x : SHCoeffs class instance.
Parameters
----------
array : ndarray, shape (2, lmaxin+1, lmaxin+1).
The input spherical harmonic 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.
lmax : int, optional, default = None
The maximum spherical harmonic degree to include in the returned
class instance. This must be less than or equal to lmaxin.
copy : bool, optional, default = True
If True, make a copy of array when initializing the class instance.
If False, initialize the class instance with a reference to array. | 2.131299 | 2.077052 | 1.026117 |
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))) | 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(). | 2.373002 | 2.10193 | 1.128963 |
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 | 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. | 1.897792 | 2.146807 | 0.884007 |
return _spectrum(self.coeffs, normalization=self.normalization,
convention=convention, unit=unit, base=base,
lmax=lmax) | def spectrum(self, lmax=None, convention='power', unit='per_l', base=10.) | Return the spectrum as a function of spherical harmonic degree.
Usage
-----
spectrum = x.spectrum([lmax, convention, unit, base])
Returns
-------
power : ndarray, shape (lmax+1)
1-D numpy ndarray of the spectrum, where lmax is the maximum
spherical harmonic degree.
Parameters
----------
lmax : int, optional, default = x.lmax
Maximum spherical harmonic degree of the spectrum to output.
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 method returns either the power spectrum, energy spectrum, or
l2-norm spectrum. 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. For
normalized coefficients ('4pi', 'ortho', or 'schmidt'), 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, which 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). | 3.867964 | 5.565147 | 0.695034 |
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 | 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. | 3.662796 | 3.199164 | 1.144923 |
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 | 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). | 2.574278 | 2.432061 | 1.058476 |
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) | 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. | 1.921493 | 1.811929 | 1.060468 |
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 | 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. | 1.859308 | 1.845897 | 1.007265 |
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) | def _make_complex(self) | Convert the real SHCoeffs class to the complex class. | 4.270547 | 3.781253 | 1.1294 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.