repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
trolldbois/ctypeslib
ctypeslib/codegen/codegenerator.py
Generator.enable_fundamental_type_wrappers
def enable_fundamental_type_wrappers(self): """ If a type is a int128, a long_double_t or a void, some placeholders need to be in the generated code to be valid. """ # 2015-01 reactivating header templates #log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers') # return # FIXME ignore self.enable_fundamental_type_wrappers = lambda: True import pkgutil headers = pkgutil.get_data( 'ctypeslib', 'data/fundamental_type_name.tpl').decode() from clang.cindex import TypeKind size = str(self.parser.get_ctypes_size(TypeKind.LONGDOUBLE) // 8) headers = headers.replace('__LONG_DOUBLE_SIZE__', size) print(headers, file=self.imports) return
python
def enable_fundamental_type_wrappers(self): """ If a type is a int128, a long_double_t or a void, some placeholders need to be in the generated code to be valid. """ # 2015-01 reactivating header templates #log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers') # return # FIXME ignore self.enable_fundamental_type_wrappers = lambda: True import pkgutil headers = pkgutil.get_data( 'ctypeslib', 'data/fundamental_type_name.tpl').decode() from clang.cindex import TypeKind size = str(self.parser.get_ctypes_size(TypeKind.LONGDOUBLE) // 8) headers = headers.replace('__LONG_DOUBLE_SIZE__', size) print(headers, file=self.imports) return
[ "def", "enable_fundamental_type_wrappers", "(", "self", ")", ":", "# 2015-01 reactivating header templates", "#log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers')", "# return # FIXME ignore", "self", ".", "enable_fundamental_type_wrappers", "=", "lambd...
If a type is a int128, a long_double_t or a void, some placeholders need to be in the generated code to be valid.
[ "If", "a", "type", "is", "a", "int128", "a", "long_double_t", "or", "a", "void", "some", "placeholders", "need", "to", "be", "in", "the", "generated", "code", "to", "be", "valid", "." ]
2aeb1942a5a32a5cc798c287cd0d9e684a0181a8
https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/codegenerator.py#L46-L63
train
203,800
trolldbois/ctypeslib
ctypeslib/codegen/codegenerator.py
Generator.enable_pointer_type
def enable_pointer_type(self): """ If a type is a pointer, a platform-independent POINTER_T type needs to be in the generated code. """ # 2015-01 reactivating header templates #log.warning('enable_pointer_type deprecated - replaced by generate_headers') # return # FIXME ignore self.enable_pointer_type = lambda: True import pkgutil headers = pkgutil.get_data('ctypeslib', 'data/pointer_type.tpl').decode() import ctypes from clang.cindex import TypeKind # assuming a LONG also has the same sizeof than a pointer. word_size = self.parser.get_ctypes_size(TypeKind.POINTER) // 8 word_type = self.parser.get_ctypes_name(TypeKind.ULONG) # pylint: disable=protected-access word_char = getattr(ctypes, word_type)._type_ # replacing template values headers = headers.replace('__POINTER_SIZE__', str(word_size)) headers = headers.replace('__REPLACEMENT_TYPE__', word_type) headers = headers.replace('__REPLACEMENT_TYPE_CHAR__', word_char) print(headers, file=self.imports) return
python
def enable_pointer_type(self): """ If a type is a pointer, a platform-independent POINTER_T type needs to be in the generated code. """ # 2015-01 reactivating header templates #log.warning('enable_pointer_type deprecated - replaced by generate_headers') # return # FIXME ignore self.enable_pointer_type = lambda: True import pkgutil headers = pkgutil.get_data('ctypeslib', 'data/pointer_type.tpl').decode() import ctypes from clang.cindex import TypeKind # assuming a LONG also has the same sizeof than a pointer. word_size = self.parser.get_ctypes_size(TypeKind.POINTER) // 8 word_type = self.parser.get_ctypes_name(TypeKind.ULONG) # pylint: disable=protected-access word_char = getattr(ctypes, word_type)._type_ # replacing template values headers = headers.replace('__POINTER_SIZE__', str(word_size)) headers = headers.replace('__REPLACEMENT_TYPE__', word_type) headers = headers.replace('__REPLACEMENT_TYPE_CHAR__', word_char) print(headers, file=self.imports) return
[ "def", "enable_pointer_type", "(", "self", ")", ":", "# 2015-01 reactivating header templates", "#log.warning('enable_pointer_type deprecated - replaced by generate_headers')", "# return # FIXME ignore", "self", ".", "enable_pointer_type", "=", "lambda", ":", "True", "import", "pkg...
If a type is a pointer, a platform-independent POINTER_T type needs to be in the generated code.
[ "If", "a", "type", "is", "a", "pointer", "a", "platform", "-", "independent", "POINTER_T", "type", "needs", "to", "be", "in", "the", "generated", "code", "." ]
2aeb1942a5a32a5cc798c287cd0d9e684a0181a8
https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/codegenerator.py#L65-L88
train
203,801
trolldbois/ctypeslib
ctypeslib/codegen/codegenerator.py
Generator.Alias
def Alias(self, alias): """Handles Aliases. No test cases yet""" # FIXME if self.generate_comments: self.print_comment(alias) print("%s = %s # alias" % (alias.name, alias.alias), file=self.stream) self._aliases += 1 return
python
def Alias(self, alias): """Handles Aliases. No test cases yet""" # 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", ")", ":", "# FIXME", "if", "self", ".", "generate_comments", ":", "self", ".", "print_comment", "(", "alias", ")", "print", "(", "\"%s = %s # alias\"", "%", "(", "alias", ".", "name", ",", "alias", ".", "alias",...
Handles Aliases. No test cases yet
[ "Handles", "Aliases", ".", "No", "test", "cases", "yet" ]
2aeb1942a5a32a5cc798c287cd0d9e684a0181a8
https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/codegenerator.py#L152-L159
train
203,802
trolldbois/ctypeslib
ctypeslib/codegen/codegenerator.py
Generator.get_undeclared_type
def get_undeclared_type(self, item): """ Checks if a typed has already been declared in the python output or is a builtin python type. """ 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
python
def get_undeclared_type(self, item): """ Checks if a typed has already been declared in the python output or is a builtin python type. """ 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", ")", ":", "if", "item", "in", "self", ".", "done", ":", "return", "None", "if", "isinstance", "(", "item", ",", "typedesc", ".", "FundamentalType", ")", ":", "return", "None", "if", "isinstance", "(...
Checks if a typed has already been declared in the python output or is a builtin python type.
[ "Checks", "if", "a", "typed", "has", "already", "been", "declared", "in", "the", "python", "output", "or", "is", "a", "builtin", "python", "type", "." ]
2aeb1942a5a32a5cc798c287cd0d9e684a0181a8
https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/codegenerator.py#L415-L429
train
203,803
trolldbois/ctypeslib
ctypeslib/codegen/codegenerator.py
Generator.FundamentalType
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 """ 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)
python
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 """ 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", ")", ":", "log", ".", "debug", "(", "'HERE in FundamentalType for %s %s'", ",", "_type", ",", "_type", ".", "name", ")", "if", "_type", ".", "name", "in", "[", "\"None\"", ",", "\"c_long_double_t\"", ",", ...
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
[ "Returns", "the", "proper", "ctypes", "class", "name", "for", "a", "fundamental", "type" ]
2aeb1942a5a32a5cc798c287cd0d9e684a0181a8
https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/codegenerator.py#L722-L734
train
203,804
trolldbois/ctypeslib
ctypeslib/codegen/codegenerator.py
Generator._generate
def _generate(self, item, *args): """ wraps execution of specific methods.""" 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
python
def _generate(self, item, *args): """ wraps execution of specific methods.""" 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", ")", ":", "if", "item", "in", "self", ".", "done", ":", "return", "# verbose output with location.", "if", "self", ".", "generate_locations", "and", "item", ".", "location", ":", "print", "(",...
wraps execution of specific methods.
[ "wraps", "execution", "of", "specific", "methods", "." ]
2aeb1942a5a32a5cc798c287cd0d9e684a0181a8
https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/codegenerator.py#L738-L766
train
203,805
SHTOOLS/SHTOOLS
examples/python/ClassInterface/exact_power.py
example
def example(): """Plot random phase and Gaussian random variable spectra.""" 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()
python
def example(): """Plot random phase and Gaussian random variable spectra.""" 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", "(", ")", ":", "ldata", "=", "200", "degrees", "=", "np", ".", "arange", "(", "ldata", "+", "1", ",", "dtype", "=", "float", ")", "degrees", "[", "0", "]", "=", "np", ".", "inf", "power", "=", "degrees", "**", "(", "-", "1", ...
Plot random phase and Gaussian random variable spectra.
[ "Plot", "random", "phase", "and", "Gaussian", "random", "variable", "spectra", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/examples/python/ClassInterface/exact_power.py#L9-L27
train
203,806
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravgrid.py
SHGravGrid.plot_rad
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. """ 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)
python
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. """ 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.
[ "Plot", "the", "radial", "component", "of", "the", "gravity", "field", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravgrid.py#L124-L174
train
203,807
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravgrid.py
SHGravGrid.plot_theta
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. """ 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)
python
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. """ 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", ",", "*", "*", "kw...
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.
[ "Plot", "the", "theta", "component", "of", "the", "gravity", "field", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravgrid.py#L176-L227
train
203,808
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravgrid.py
SHGravGrid.plot_phi
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. """ 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)
python
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. """ 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.
[ "Plot", "the", "phi", "component", "of", "the", "gravity", "field", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravgrid.py#L229-L279
train
203,809
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravgrid.py
SHGravGrid.plot_total
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. """ 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)
python
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. """ 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.
[ "Plot", "the", "total", "gravity", "disturbance", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravgrid.py#L281-L354
train
203,810
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravgrid.py
SHGravGrid.plot_pot
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. """ 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)
python
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. """ 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", ",", "*", "*", "kwar...
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.
[ "Plot", "the", "gravitational", "potential", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravgrid.py#L356-L406
train
203,811
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravgrid.py
SHGravGrid.plot
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. """ 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
python
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. """ 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'", "...
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.
[ "Plot", "the", "three", "vector", "components", "of", "the", "gravity", "field", "and", "the", "gravity", "disturbance", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravgrid.py#L408-L499
train
203,812
SHTOOLS/SHTOOLS
pyshtools/shclasses/slepiancoeffs.py
SlepianCoeffs.expand
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. """ 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)))
python
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. """ 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", ")", ":", "if", "type", "(", "grid", ")", "!=", "str", ":", "raise", "ValueError", "(", "'grid must be a string. '", "+", "'Input type was {:s}'...
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.
[ "Expand", "the", "function", "on", "a", "grid", "using", "the", "first", "n", "Slepian", "coefficients", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/slepiancoeffs.py#L90-L147
train
203,813
SHTOOLS/SHTOOLS
pyshtools/shclasses/slepiancoeffs.py
SlepianCoeffs.to_shcoeffs
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. """ 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
python
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. """ 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", ")", ":", "if", "type", "(", "normalization", ")", "!=", "str", ":", "raise", "ValueError", "(", "'normalization must be a string. '", ...
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.
[ "Return", "the", "spherical", "harmonic", "coefficients", "using", "the", "first", "n", "Slepian", "coefficients", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/slepiancoeffs.py#L149-L210
train
203,814
SHTOOLS/SHTOOLS
pyshtools/shtools/__init__.py
_shtools_status_message
def _shtools_status_message(status): ''' 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
python
def _shtools_status_message(status): ''' 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", ")", ":", "if", "(", "status", "==", "1", ")", ":", "errmsg", "=", "'Improper dimensions of input array.'", "elif", "(", "status", "==", "2", ")", ":", "errmsg", "=", "'Improper bounds for input variable.'", "elif",...
Determine error message to print when a SHTOOLS Fortran 95 routine exits improperly.
[ "Determine", "error", "message", "to", "print", "when", "a", "SHTOOLS", "Fortran", "95", "routine", "exits", "improperly", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shtools/__init__.py#L177-L192
train
203,815
SHTOOLS/SHTOOLS
pyshtools/shclasses/slepian.py
Slepian.from_cap
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. """ 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)
python
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. """ 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.
[ "Construct", "spherical", "cap", "Slepian", "functions", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/slepian.py#L106-L148
train
203,816
SHTOOLS/SHTOOLS
pyshtools/shclasses/slepian.py
Slepian.from_mask
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. """ 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)
python
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. """ 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", ")", ":", "if", "nmax", "is", "None", ":", "nmax", "=", "(", "lmax", "+", "1", ")", "**", "2", "else", ":", "if", "nmax", ">", "(", "lmax", "+", "1", ")", ...
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.
[ "Construct", "Slepian", "functions", "that", "are", "optimally", "concentrated", "within", "the", "region", "specified", "by", "a", "mask", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/slepian.py#L151-L206
train
203,817
SHTOOLS/SHTOOLS
pyshtools/shclasses/slepian.py
Slepian.expand
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 """ 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)
python
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 """ 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", ")", ":", "if", "nmax", "is", "None", ":", "nmax", "=", "(", "self", ".", "lmax", "+", "1", ")", "**", "2", "elif", "nmax", "is", "not", "None", "and", "nmax", ">", "(", "sel...
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
[ "Return", "the", "Slepian", "expansion", "coefficients", "of", "the", "input", "function", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/slepian.py#L251-L290
train
203,818
SHTOOLS/SHTOOLS
pyshtools/shclasses/slepian.py
Slepian.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). """ 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
python
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). """ 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.", ")", ":", "if", "alpha", "is", "None", ":", "if", "nmax", "is", "None", "...
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).
[ "Return", "the", "spectra", "of", "one", "or", "more", "Slepian", "functions", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/slepian.py#L444-L521
train
203,819
SHTOOLS/SHTOOLS
pyshtools/shclasses/slepian.py
SlepianCap._taper2coeffs
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. """ 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
python
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. """ 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", ")", ":", "taperm", "=", "self", ".", "orders", "[", "alpha", "]", "coeffs", "=", "_np", ".", "zeros", "(", "(", "2", ",", "self", ".", "lmax", "+", "1", ",", "self", ".", "lmax", "+", "1", ")"...
Return the spherical harmonic coefficients of the unrotated Slepian function i as an array, where i = 0 is the best concentrated function.
[ "Return", "the", "spherical", "harmonic", "coefficients", "of", "the", "unrotated", "Slepian", "function", "i", "as", "an", "array", "where", "i", "=", "0", "is", "the", "best", "concentrated", "function", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/slepian.py#L904-L916
train
203,820
SHTOOLS/SHTOOLS
pyshtools/shclasses/shmaggrid.py
SHMagGrid.plot_total
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. """ 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)
python
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. """ 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.
[ "Plot", "the", "total", "magnetic", "intensity", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shmaggrid.py#L269-L321
train
203,821
SHTOOLS/SHTOOLS
pyshtools/expand/spharm_functions.py
spharm_lm
def spharm_lm(l, m, theta, phi, normalization='4pi', kind='real', csphase=1, degrees=True): """ Compute the spherical harmonic function for a specific degree and order. Usage ----- ylm = spharm (l, m, theta, phi, [normalization, kind, csphase, degrees]) Returns ------- ylm : float or complex The spherical harmonic function ylm, where l and m are the spherical harmonic degree and order, respectively. Parameters ---------- l : integer The spherical harmonic degree. m : integer The spherical harmonic order. theta : float The colatitude in degrees. phi : float The longitude in degrees. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind : str, optional, default = 'real' 'real' or 'complex' spherical harmonic coefficients. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the spherical harmonic functions. degrees : optional, bool, default = True If True, colat and phi are expressed in degrees. Description ----------- spharm_lm will calculate the spherical harmonic function for a specific degree l and order m, and for a given colatitude theta and longitude phi. Three parameters determine how the spherical harmonic functions are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind can be either 'real' or 'complex', and csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. The spherical harmonic functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the spherical harmonic functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """ if l < 0: raise ValueError( "The degree l must be greater or equal than 0. Input value was {:s}." .format(repr(l)) ) if m > l: raise ValueError( "The order m must be less than or equal to the degree l. " + "Input values were l={:s} and m={:s}.".format(repr(l), repr(m)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if kind.lower() not in ('real', 'complex'): raise ValueError( "kind must be 'real' or 'complex'. " + "Input value was {:s}.".format(repr(kind)) ) 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 ind = (l*(l+1))//2 + abs(m) if degrees is True: theta = _np.deg2rad(theta) phi = _np.deg2rad(phi) if kind.lower() == 'real': p = _legendre(l, _np.cos(theta), normalization=normalization, csphase=csphase, cnorm=0, packed=True) if m >= 0: ylm = p[ind] * _np.cos(m*phi) else: ylm = p[ind] * _np.sin(abs(m)*phi) else: p = _legendre(l, _np.cos(theta), normalization=normalization, csphase=csphase, cnorm=1, packed=True) ylm = p[ind] * (_np.cos(m*phi) + 1j * _np.sin(abs(m)*phi)) # Yl|m| if m < 0: ylm = ylm.conj() if _np.mod(m, 2) == 1: ylm = - ylm return ylm
python
def spharm_lm(l, m, theta, phi, normalization='4pi', kind='real', csphase=1, degrees=True): """ Compute the spherical harmonic function for a specific degree and order. Usage ----- ylm = spharm (l, m, theta, phi, [normalization, kind, csphase, degrees]) Returns ------- ylm : float or complex The spherical harmonic function ylm, where l and m are the spherical harmonic degree and order, respectively. Parameters ---------- l : integer The spherical harmonic degree. m : integer The spherical harmonic order. theta : float The colatitude in degrees. phi : float The longitude in degrees. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind : str, optional, default = 'real' 'real' or 'complex' spherical harmonic coefficients. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the spherical harmonic functions. degrees : optional, bool, default = True If True, colat and phi are expressed in degrees. Description ----------- spharm_lm will calculate the spherical harmonic function for a specific degree l and order m, and for a given colatitude theta and longitude phi. Three parameters determine how the spherical harmonic functions are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind can be either 'real' or 'complex', and csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. The spherical harmonic functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the spherical harmonic functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """ if l < 0: raise ValueError( "The degree l must be greater or equal than 0. Input value was {:s}." .format(repr(l)) ) if m > l: raise ValueError( "The order m must be less than or equal to the degree l. " + "Input values were l={:s} and m={:s}.".format(repr(l), repr(m)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if kind.lower() not in ('real', 'complex'): raise ValueError( "kind must be 'real' or 'complex'. " + "Input value was {:s}.".format(repr(kind)) ) 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 ind = (l*(l+1))//2 + abs(m) if degrees is True: theta = _np.deg2rad(theta) phi = _np.deg2rad(phi) if kind.lower() == 'real': p = _legendre(l, _np.cos(theta), normalization=normalization, csphase=csphase, cnorm=0, packed=True) if m >= 0: ylm = p[ind] * _np.cos(m*phi) else: ylm = p[ind] * _np.sin(abs(m)*phi) else: p = _legendre(l, _np.cos(theta), normalization=normalization, csphase=csphase, cnorm=1, packed=True) ylm = p[ind] * (_np.cos(m*phi) + 1j * _np.sin(abs(m)*phi)) # Yl|m| if m < 0: ylm = ylm.conj() if _np.mod(m, 2) == 1: ylm = - ylm return ylm
[ "def", "spharm_lm", "(", "l", ",", "m", ",", "theta", ",", "phi", ",", "normalization", "=", "'4pi'", ",", "kind", "=", "'real'", ",", "csphase", "=", "1", ",", "degrees", "=", "True", ")", ":", "if", "l", "<", "0", ":", "raise", "ValueError", "(...
Compute the spherical harmonic function for a specific degree and order. Usage ----- ylm = spharm (l, m, theta, phi, [normalization, kind, csphase, degrees]) Returns ------- ylm : float or complex The spherical harmonic function ylm, where l and m are the spherical harmonic degree and order, respectively. Parameters ---------- l : integer The spherical harmonic degree. m : integer The spherical harmonic order. theta : float The colatitude in degrees. phi : float The longitude in degrees. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind : str, optional, default = 'real' 'real' or 'complex' spherical harmonic coefficients. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the spherical harmonic functions. degrees : optional, bool, default = True If True, colat and phi are expressed in degrees. Description ----------- spharm_lm will calculate the spherical harmonic function for a specific degree l and order m, and for a given colatitude theta and longitude phi. Three parameters determine how the spherical harmonic functions are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind can be either 'real' or 'complex', and csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. The spherical harmonic functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the spherical harmonic functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018.
[ "Compute", "the", "spherical", "harmonic", "function", "for", "a", "specific", "degree", "and", "order", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/expand/spharm_functions.py#L185-L315
train
203,822
SHTOOLS/SHTOOLS
pyshtools/shclasses/shmagcoeffs.py
SHMagCoeffs.set_coeffs
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. """ # 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
python
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. """ # 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", ")", ":", "# Ensure that the type is correct", "values", "=", "_np", ".", "array", "(", "values", ")", "ls", "=", "_np", ".", "array", "(", "ls", ")", "ms", "=", "_np", ".", "arra...
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.
[ "Set", "spherical", "harmonic", "coefficients", "in", "-", "place", "to", "specified", "values", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shmagcoeffs.py#L611-L643
train
203,823
SHTOOLS/SHTOOLS
pyshtools/shclasses/shmagcoeffs.py
SHMagCoeffs.convert
def convert(self, normalization=None, csphase=None, lmax=None): """ Return an SHMagCoeffs class instance with a different normalization convention. Usage ----- clm = x.convert([normalization, csphase, lmax]) Returns ------- clm : SHMagCoeffs class instance Parameters ---------- normalization : str, optional, default = x.normalization Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention for the output class: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. Description ----------- This method will return a new class instance of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention. A different maximum spherical harmonic degree of the output coefficients can be specified, and if this maximum degree is smaller than the maximum degree of the original class, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the original class, the coefficients of the new class will be zero padded. """ if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax # check argument consistency if type(normalization) != str: raise ValueError('normalization must be a string. ' 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "normalization must be '4pi', 'ortho', 'schmidt', or " "'unnorm'. Provided value was {:s}" .format(repr(normalization))) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase))) if self.errors is not None: coeffs, errors = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHMagCoeffs.from_array( coeffs, r0=self.r0, errors=errors, normalization=normalization.lower(), csphase=csphase, copy=False) else: coeffs = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHMagCoeffs.from_array( coeffs, r0=self.r0, normalization=normalization.lower(), csphase=csphase, copy=False)
python
def convert(self, normalization=None, csphase=None, lmax=None): """ Return an SHMagCoeffs class instance with a different normalization convention. Usage ----- clm = x.convert([normalization, csphase, lmax]) Returns ------- clm : SHMagCoeffs class instance Parameters ---------- normalization : str, optional, default = x.normalization Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention for the output class: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. Description ----------- This method will return a new class instance of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention. A different maximum spherical harmonic degree of the output coefficients can be specified, and if this maximum degree is smaller than the maximum degree of the original class, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the original class, the coefficients of the new class will be zero padded. """ if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax # check argument consistency if type(normalization) != str: raise ValueError('normalization must be a string. ' 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "normalization must be '4pi', 'ortho', 'schmidt', or " "'unnorm'. Provided value was {:s}" .format(repr(normalization))) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase))) if self.errors is not None: coeffs, errors = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHMagCoeffs.from_array( coeffs, r0=self.r0, errors=errors, normalization=normalization.lower(), csphase=csphase, copy=False) else: coeffs = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHMagCoeffs.from_array( coeffs, r0=self.r0, normalization=normalization.lower(), csphase=csphase, copy=False)
[ "def", "convert", "(", "self", ",", "normalization", "=", "None", ",", "csphase", "=", "None", ",", "lmax", "=", "None", ")", ":", "if", "normalization", "is", "None", ":", "normalization", "=", "self", ".", "normalization", "if", "csphase", "is", "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.
[ "Return", "an", "SHMagCoeffs", "class", "instance", "with", "a", "different", "normalization", "convention", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shmagcoeffs.py#L1231-L1301
train
203,824
SHTOOLS/SHTOOLS
pyshtools/shclasses/shmagcoeffs.py
SHMagCoeffs.pad
def pad(self, lmax): """ Return an SHMagCoeffs class where the coefficients are zero padded or truncated to a different lmax. Usage ----- clm = x.pad(lmax) Returns ------- clm : SHMagCoeffs class instance Parameters ---------- lmax : int Maximum spherical harmonic degree to output. """ clm = self.copy() if lmax <= self.lmax: clm.coeffs = clm.coeffs[:, :lmax+1, :lmax+1] clm.mask = clm.mask[:, :lmax+1, :lmax+1] if self.errors is not None: clm.errors = clm.errors[:, :lmax+1, :lmax+1] else: clm.coeffs = _np.pad(clm.coeffs, ((0, 0), (0, lmax - self.lmax), (0, lmax - self.lmax)), 'constant') if self.errors is not None: clm.errors = _np.pad( clm.errors, ((0, 0), (0, lmax - self.lmax), (0, lmax - self.lmax)), 'constant') mask = _np.zeros((2, lmax + 1, lmax + 1), dtype=_np.bool) for l in _np.arange(lmax + 1): mask[:, l, :l + 1] = True mask[1, :, 0] = False clm.mask = mask clm.lmax = lmax return clm
python
def pad(self, lmax): """ Return an SHMagCoeffs class where the coefficients are zero padded or truncated to a different lmax. Usage ----- clm = x.pad(lmax) Returns ------- clm : SHMagCoeffs class instance Parameters ---------- lmax : int Maximum spherical harmonic degree to output. """ clm = self.copy() if lmax <= self.lmax: clm.coeffs = clm.coeffs[:, :lmax+1, :lmax+1] clm.mask = clm.mask[:, :lmax+1, :lmax+1] if self.errors is not None: clm.errors = clm.errors[:, :lmax+1, :lmax+1] else: clm.coeffs = _np.pad(clm.coeffs, ((0, 0), (0, lmax - self.lmax), (0, lmax - self.lmax)), 'constant') if self.errors is not None: clm.errors = _np.pad( clm.errors, ((0, 0), (0, lmax - self.lmax), (0, lmax - self.lmax)), 'constant') mask = _np.zeros((2, lmax + 1, lmax + 1), dtype=_np.bool) for l in _np.arange(lmax + 1): mask[:, l, :l + 1] = True mask[1, :, 0] = False clm.mask = mask clm.lmax = lmax return clm
[ "def", "pad", "(", "self", ",", "lmax", ")", ":", "clm", "=", "self", ".", "copy", "(", ")", "if", "lmax", "<=", "self", ".", "lmax", ":", "clm", ".", "coeffs", "=", "clm", ".", "coeffs", "[", ":", ",", ":", "lmax", "+", "1", ",", ":", "lma...
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.
[ "Return", "an", "SHMagCoeffs", "class", "where", "the", "coefficients", "are", "zero", "padded", "or", "truncated", "to", "a", "different", "lmax", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shmagcoeffs.py#L1303-L1342
train
203,825
SHTOOLS/SHTOOLS
pyshtools/shclasses/shmagcoeffs.py
SHMagCoeffs.change_ref
def change_ref(self, r0=None, lmax=None): """ Return a new SHMagCoeffs class instance with a different reference r0. Usage ----- clm = x.change_ref([r0, lmax]) Returns ------- clm : SHMagCoeffs class instance. Parameters ---------- r0 : float, optional, default = self.r0 The reference radius of the spherical harmonic coefficients. lmax : int, optional, default = self.lmax Maximum spherical harmonic degree to output. Description ----------- This method returns a new class instance of the magnetic potential, but using a difference reference r0. When changing the reference radius r0, the spherical harmonic coefficients will be upward or downward continued under the assumption that the reference radius is exterior to the body. """ if lmax is None: lmax = self.lmax clm = self.pad(lmax) if r0 is not None and r0 != self.r0: for l in _np.arange(lmax+1): clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**(l+2) if self.errors is not None: clm.errors[:, l, :l+1] *= (self.r0 / r0)**(l+2) clm.r0 = r0 return clm
python
def change_ref(self, r0=None, lmax=None): """ Return a new SHMagCoeffs class instance with a different reference r0. Usage ----- clm = x.change_ref([r0, lmax]) Returns ------- clm : SHMagCoeffs class instance. Parameters ---------- r0 : float, optional, default = self.r0 The reference radius of the spherical harmonic coefficients. lmax : int, optional, default = self.lmax Maximum spherical harmonic degree to output. Description ----------- This method returns a new class instance of the magnetic potential, but using a difference reference r0. When changing the reference radius r0, the spherical harmonic coefficients will be upward or downward continued under the assumption that the reference radius is exterior to the body. """ if lmax is None: lmax = self.lmax clm = self.pad(lmax) if r0 is not None and r0 != self.r0: for l in _np.arange(lmax+1): clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**(l+2) if self.errors is not None: clm.errors[:, l, :l+1] *= (self.r0 / r0)**(l+2) clm.r0 = r0 return clm
[ "def", "change_ref", "(", "self", ",", "r0", "=", "None", ",", "lmax", "=", "None", ")", ":", "if", "lmax", "is", "None", ":", "lmax", "=", "self", ".", "lmax", "clm", "=", "self", ".", "pad", "(", "lmax", ")", "if", "r0", "is", "not", "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.
[ "Return", "a", "new", "SHMagCoeffs", "class", "instance", "with", "a", "different", "reference", "r0", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shmagcoeffs.py#L1344-L1383
train
203,826
SHTOOLS/SHTOOLS
pyshtools/shclasses/shmagcoeffs.py
SHMagCoeffs.expand
def expand(self, a=None, f=None, lmax=None, lmax_calc=None, sampling=2): """ Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the magnetic field, the total magnetic intensity, and the magnetic potential, and return as a SHMagGrid class instance. Usage ----- mag = x.expand([a, f, lmax, lmax_calc, sampling]) Returns ------- mag : SHMagGrid class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree, which determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps of the three components of the magnetic field, the total field, and the magnetic potential, and return these as an SHMagGrid class instance. Each map is stored as an SHGrid class instance using Driscoll and Healy grids that are either equally sampled (n by n) or equally spaced (n by 2n) in latitude and longitude. All grids use geocentric coordinates, and the units are either in nT (for the magnetic field), or nT m (for the potential), The magnetic potential is given by V = r0 Sum_{l=1}^lmax (r0/r)^{l+1} Sum_{m=-l}^l g_{lm} Y_{lm} and the magnetic field is B = - Grad V. The coefficients are referenced to a radius r0, and the function is computed on a flattened ellipsoid with semi-major axis a (i.e., the mean equatorial radius) and flattening f. """ if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='schmidt', csphase=1) else: coeffs = self.to_array(normalization='schmidt', csphase=1) rad, theta, phi, total, pot = _MakeMagGridDH( coeffs, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHMagGrid(rad, theta, phi, total, pot, a, f, lmax, lmax_calc)
python
def expand(self, a=None, f=None, lmax=None, lmax_calc=None, sampling=2): """ Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the magnetic field, the total magnetic intensity, and the magnetic potential, and return as a SHMagGrid class instance. Usage ----- mag = x.expand([a, f, lmax, lmax_calc, sampling]) Returns ------- mag : SHMagGrid class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree, which determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps of the three components of the magnetic field, the total field, and the magnetic potential, and return these as an SHMagGrid class instance. Each map is stored as an SHGrid class instance using Driscoll and Healy grids that are either equally sampled (n by n) or equally spaced (n by 2n) in latitude and longitude. All grids use geocentric coordinates, and the units are either in nT (for the magnetic field), or nT m (for the potential), The magnetic potential is given by V = r0 Sum_{l=1}^lmax (r0/r)^{l+1} Sum_{m=-l}^l g_{lm} Y_{lm} and the magnetic field is B = - Grad V. The coefficients are referenced to a radius r0, and the function is computed on a flattened ellipsoid with semi-major axis a (i.e., the mean equatorial radius) and flattening f. """ if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='schmidt', csphase=1) else: coeffs = self.to_array(normalization='schmidt', csphase=1) rad, theta, phi, total, pot = _MakeMagGridDH( coeffs, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHMagGrid(rad, theta, phi, total, pot, a, f, lmax, lmax_calc)
[ "def", "expand", "(", "self", ",", "a", "=", "None", ",", "f", "=", "None", ",", "lmax", "=", "None", ",", "lmax_calc", "=", "None", ",", "sampling", "=", "2", ")", ":", "if", "a", "is", "None", ":", "a", "=", "self", ".", "r0", "if", "f", ...
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.
[ "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", ...
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shmagcoeffs.py#L1386-L1459
train
203,827
SHTOOLS/SHTOOLS
pyshtools/shclasses/shmagcoeffs.py
SHMagCoeffs.tensor
def tensor(self, a=None, f=None, lmax=None, lmax_calc=None, sampling=2): """ Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the magnetic field tensor in a local north-oriented reference frame, and return an SHMagTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHMagTensor class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps for the 9 components of the magnetic field tensor and return an SHMagTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The magnetic potential is defined as V = r0 Sum_{l=0}^lmax (r0/r)^(l+1) Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the vector magnetic field is B = - Grad V. The components of the tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of nT / m. References ---------- Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006. """ if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='schmidt', csphase=1) else: coeffs = self.to_array(normalization='schmidt', csphase=1) vxx, vyy, vzz, vxy, vxz, vyz = _MakeMagGradGridDH( coeffs, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHMagTensor(vxx, vyy, vzz, vxy, vxz, vyz, a, f, lmax, lmax_calc)
python
def tensor(self, a=None, f=None, lmax=None, lmax_calc=None, sampling=2): """ Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the magnetic field tensor in a local north-oriented reference frame, and return an SHMagTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHMagTensor class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps for the 9 components of the magnetic field tensor and return an SHMagTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The magnetic potential is defined as V = r0 Sum_{l=0}^lmax (r0/r)^(l+1) Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the vector magnetic field is B = - Grad V. The components of the tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of nT / m. References ---------- Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006. """ if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='schmidt', csphase=1) else: coeffs = self.to_array(normalization='schmidt', csphase=1) vxx, vyy, vzz, vxy, vxz, vyz = _MakeMagGradGridDH( coeffs, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHMagTensor(vxx, vyy, vzz, vxy, vxz, vyz, a, f, lmax, lmax_calc)
[ "def", "tensor", "(", "self", ",", "a", "=", "None", ",", "f", "=", "None", ",", "lmax", "=", "None", ",", "lmax_calc", "=", "None", ",", "sampling", "=", "2", ")", ":", "if", "a", "is", "None", ":", "a", "=", "self", ".", "r0", "if", "f", ...
Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the magnetic field tensor in a local north-oriented reference frame, and return an SHMagTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHMagTensor class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps for the 9 components of the magnetic field tensor and return an SHMagTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The magnetic potential is defined as V = r0 Sum_{l=0}^lmax (r0/r)^(l+1) Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the vector magnetic field is B = - Grad V. The components of the tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of nT / m. References ---------- Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006.
[ "Create", "2D", "cylindrical", "maps", "on", "a", "flattened", "ellipsoid", "of", "the", "9", "components", "of", "the", "magnetic", "field", "tensor", "in", "a", "local", "north", "-", "oriented", "reference", "frame", "and", "return", "an", "SHMagTensor", ...
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shmagcoeffs.py#L1461-L1561
train
203,828
SHTOOLS/SHTOOLS
pyshtools/legendre/legendre_functions.py
legendre
def legendre(lmax, z, normalization='4pi', csphase=1, cnorm=0, packed=False): """ Compute all the associated Legendre functions up to a maximum degree and order. Usage ----- plm = legendre (lmax, z, [normalization, csphase, cnorm, packed]) Returns ------- plm : float, dimension (lmax+1, lmax+1) or ((lmax+1)*(lmax+2)/2) An array of associated Legendre functions, plm[l, m], where l and m are the degree and order, respectively. If packed is True, the array is 1-dimensional with the index corresponding to l*(l+1)/2+m. Parameters ---------- lmax : integer The maximum degree of the associated Legendre functions to be computed. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. packed : optional, bool, default = False If True, return a 1-dimensional packed array with the index corresponding to l*(l+1)/2+m, where l and m are respectively the degree and order. Description ----------- legendre` will calculate all of the associated Legendre functions up to degree lmax for a given argument. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. `normalization` can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. By default, the routine will return a 2-dimensional array, p[l, m]. If the optional parameter `packed` is set to True, the output will instead be a 1-dimensional array where the indices correspond to `l*(l+1)/2+m`. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """ if lmax < 0: raise ValueError( "lmax must be greater or equal to 0. Input value was {:s}." .format(repr(lmax)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if cnorm != 0 and cnorm != 1: raise ValueError( "cnorm must be either 0 or 1. Input value was {:s}." .format(repr(cnorm)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 if normalization == '4pi': p = _PlmBar(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'ortho': p = _PlmON(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'schmidt': p = _PlmSchmidt(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'unnorm': p = _PLegendreA(lmax, z, csphase=csphase, cnorm=cnorm) if packed is True: return p else: plm = _np.zeros((lmax+1, lmax+1)) for l in range(lmax+1): for m in range(l+1): plm[l, m] = p[(l*(l+1))//2+m] return plm
python
def legendre(lmax, z, normalization='4pi', csphase=1, cnorm=0, packed=False): """ Compute all the associated Legendre functions up to a maximum degree and order. Usage ----- plm = legendre (lmax, z, [normalization, csphase, cnorm, packed]) Returns ------- plm : float, dimension (lmax+1, lmax+1) or ((lmax+1)*(lmax+2)/2) An array of associated Legendre functions, plm[l, m], where l and m are the degree and order, respectively. If packed is True, the array is 1-dimensional with the index corresponding to l*(l+1)/2+m. Parameters ---------- lmax : integer The maximum degree of the associated Legendre functions to be computed. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. packed : optional, bool, default = False If True, return a 1-dimensional packed array with the index corresponding to l*(l+1)/2+m, where l and m are respectively the degree and order. Description ----------- legendre` will calculate all of the associated Legendre functions up to degree lmax for a given argument. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. `normalization` can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. By default, the routine will return a 2-dimensional array, p[l, m]. If the optional parameter `packed` is set to True, the output will instead be a 1-dimensional array where the indices correspond to `l*(l+1)/2+m`. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """ if lmax < 0: raise ValueError( "lmax must be greater or equal to 0. Input value was {:s}." .format(repr(lmax)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if cnorm != 0 and cnorm != 1: raise ValueError( "cnorm must be either 0 or 1. Input value was {:s}." .format(repr(cnorm)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 if normalization == '4pi': p = _PlmBar(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'ortho': p = _PlmON(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'schmidt': p = _PlmSchmidt(lmax, z, csphase=csphase, cnorm=cnorm) elif normalization == 'unnorm': p = _PLegendreA(lmax, z, csphase=csphase, cnorm=cnorm) if packed is True: return p else: plm = _np.zeros((lmax+1, lmax+1)) for l in range(lmax+1): for m in range(l+1): plm[l, m] = p[(l*(l+1))//2+m] return plm
[ "def", "legendre", "(", "lmax", ",", "z", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ",", "cnorm", "=", "0", ",", "packed", "=", "False", ")", ":", "if", "lmax", "<", "0", ":", "raise", "ValueError", "(", "\"lmax must be greater or e...
Compute all the associated Legendre functions up to a maximum degree and order. Usage ----- plm = legendre (lmax, z, [normalization, csphase, cnorm, packed]) Returns ------- plm : float, dimension (lmax+1, lmax+1) or ((lmax+1)*(lmax+2)/2) An array of associated Legendre functions, plm[l, m], where l and m are the degree and order, respectively. If packed is True, the array is 1-dimensional with the index corresponding to l*(l+1)/2+m. Parameters ---------- lmax : integer The maximum degree of the associated Legendre functions to be computed. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. packed : optional, bool, default = False If True, return a 1-dimensional packed array with the index corresponding to l*(l+1)/2+m, where l and m are respectively the degree and order. Description ----------- legendre` will calculate all of the associated Legendre functions up to degree lmax for a given argument. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. `normalization` can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. By default, the routine will return a 2-dimensional array, p[l, m]. If the optional parameter `packed` is set to True, the output will instead be a 1-dimensional array where the indices correspond to `l*(l+1)/2+m`. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018.
[ "Compute", "all", "the", "associated", "Legendre", "functions", "up", "to", "a", "maximum", "degree", "and", "order", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/legendre/legendre_functions.py#L17-L138
train
203,829
SHTOOLS/SHTOOLS
pyshtools/legendre/legendre_functions.py
legendre_lm
def legendre_lm(l, m, z, normalization='4pi', csphase=1, cnorm=0): """ Compute the associated Legendre function for a specific degree and order. Usage ----- plm = legendre_lm (l, m, z, [normalization, csphase, cnorm]) Returns ------- plm : float The associated Legendre functions for degree l and order m. Parameters ---------- l : integer The spherical harmonic degree. m : integer The spherical harmonic order. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. Description ----------- legendre_lm will calculate the associated Legendre function for a specific degree l and order m. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """ if l < 0: raise ValueError( "The degree l must be greater or equal to 0. Input value was {:s}." .format(repr(l)) ) if m < 0: raise ValueError( "The order m must be greater or equal to 0. Input value was {:s}." .format(repr(m)) ) if m > l: raise ValueError( "The order m must be less than or equal to the degree l. " + "Input values were l={:s} and m={:s}.".format(repr(l), repr(m)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if cnorm != 0 and cnorm != 1: raise ValueError( "cnorm must be either 0 or 1. Input value was {:s}." .format(repr(cnorm)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 if normalization == '4pi': p = _PlmBar(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'ortho': p = _PlmON(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'schmidt': p = _PlmSchmidt(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'unnorm': p = _PLegendreA(l, z, csphase=csphase, cnorm=cnorm) return p[(l*(l+1))//2+m]
python
def legendre_lm(l, m, z, normalization='4pi', csphase=1, cnorm=0): """ Compute the associated Legendre function for a specific degree and order. Usage ----- plm = legendre_lm (l, m, z, [normalization, csphase, cnorm]) Returns ------- plm : float The associated Legendre functions for degree l and order m. Parameters ---------- l : integer The spherical harmonic degree. m : integer The spherical harmonic order. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. Description ----------- legendre_lm will calculate the associated Legendre function for a specific degree l and order m. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """ if l < 0: raise ValueError( "The degree l must be greater or equal to 0. Input value was {:s}." .format(repr(l)) ) if m < 0: raise ValueError( "The order m must be greater or equal to 0. Input value was {:s}." .format(repr(m)) ) if m > l: raise ValueError( "The order m must be less than or equal to the degree l. " + "Input values were l={:s} and m={:s}.".format(repr(l), repr(m)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if cnorm != 0 and cnorm != 1: raise ValueError( "cnorm must be either 0 or 1. Input value was {:s}." .format(repr(cnorm)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 if normalization == '4pi': p = _PlmBar(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'ortho': p = _PlmON(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'schmidt': p = _PlmSchmidt(l, z, csphase=csphase, cnorm=cnorm) elif normalization == 'unnorm': p = _PLegendreA(l, z, csphase=csphase, cnorm=cnorm) return p[(l*(l+1))//2+m]
[ "def", "legendre_lm", "(", "l", ",", "m", ",", "z", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ",", "cnorm", "=", "0", ")", ":", "if", "l", "<", "0", ":", "raise", "ValueError", "(", "\"The degree l must be greater or equal to 0. Input v...
Compute the associated Legendre function for a specific degree and order. Usage ----- plm = legendre_lm (l, m, z, [normalization, csphase, cnorm]) Returns ------- plm : float The associated Legendre functions for degree l and order m. Parameters ---------- l : integer The spherical harmonic degree. m : integer The spherical harmonic order. z : float The argument of the associated Legendre functions. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for use with geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the associated Legendre functions. cnorm : optional, integer, default = 0 If 1, the complex normalization of the associated Legendre functions will be used. The default is to use the real normalization. Description ----------- legendre_lm will calculate the associated Legendre function for a specific degree l and order m. The Legendre functions are used typically as a part of the spherical harmonic functions, and three parameters determine how they are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for use with 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. cnorm determines whether to normalize the Legendre functions for use with real (default) or complex spherical harmonic functions. The Legendre functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the Legendre functions are defined. References ---------- Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools — Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018.
[ "Compute", "the", "associated", "Legendre", "function", "for", "a", "specific", "degree", "and", "order", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/legendre/legendre_functions.py#L141-L258
train
203,830
SHTOOLS/SHTOOLS
pyshtools/shio/shread.py
_iscomment
def _iscomment(line): """ Determine if a line is a comment line. A valid line contains at least three words, with the first two being integers. Note that Python 2 and 3 deal with strings differently. """ if line.isspace(): return True elif len(line.split()) >= 3: try: # python 3 str if line.split()[0].isdecimal() and line.split()[1].isdecimal(): return False except: # python 2 str if (line.decode().split()[0].isdecimal() and line.split()[1].decode().isdecimal()): return False return True else: return True
python
def _iscomment(line): """ Determine if a line is a comment line. A valid line contains at least three words, with the first two being integers. Note that Python 2 and 3 deal with strings differently. """ if line.isspace(): return True elif len(line.split()) >= 3: try: # python 3 str if line.split()[0].isdecimal() and line.split()[1].isdecimal(): return False except: # python 2 str if (line.decode().split()[0].isdecimal() and line.split()[1].decode().isdecimal()): return False return True else: return True
[ "def", "_iscomment", "(", "line", ")", ":", "if", "line", ".", "isspace", "(", ")", ":", "return", "True", "elif", "len", "(", "line", ".", "split", "(", ")", ")", ">=", "3", ":", "try", ":", "# python 3 str", "if", "line", ".", "split", "(", ")"...
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.
[ "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", "s...
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shio/shread.py#L240-L258
train
203,831
SHTOOLS/SHTOOLS
pyshtools/make_docs.py
process_f2pydoc
def process_f2pydoc(f2pydoc): """ this function replace all optional _d0 arguments with their default values in the function signature. These arguments are not intended to be used and signify merely the array dimensions of the associated argument. """ # ---- split f2py document in its parts # 0=Call Signature # 1=Parameters # 2=Other (optional) Parameters (only if present) # 3=Returns docparts = re.split('\n--', f2pydoc) if len(docparts) == 4: doc_has_optionals = True elif len(docparts) == 3: doc_has_optionals = False else: print('-- uninterpretable f2py documentation --') return f2pydoc # ---- replace arguments with _d suffix with empty string in ---- # ---- function signature (remove them): ---- docparts[0] = re.sub('[\[(,]\w+_d\d', '', docparts[0]) # ---- replace _d arguments of the return arrays with their default value: if doc_has_optionals: returnarray_dims = re.findall('[\[(,](\w+_d\d)', docparts[3]) for arg in returnarray_dims: searchpattern = arg + ' : input.*\n.*Default: (.*)\n' match = re.search(searchpattern, docparts[2]) if match: default = match.group(1) docparts[3] = re.sub(arg, default, docparts[3]) docparts[2] = re.sub(searchpattern, '', docparts[2]) # ---- remove all optional _d# from optional argument list: if doc_has_optionals: searchpattern = '\w+_d\d : input.*\n.*Default: (.*)\n' docparts[2] = re.sub(searchpattern, '', docparts[2]) # ---- combine doc parts to a single string processed_signature = '\n--'.join(docparts) return processed_signature
python
def process_f2pydoc(f2pydoc): """ this function replace all optional _d0 arguments with their default values in the function signature. These arguments are not intended to be used and signify merely the array dimensions of the associated argument. """ # ---- split f2py document in its parts # 0=Call Signature # 1=Parameters # 2=Other (optional) Parameters (only if present) # 3=Returns docparts = re.split('\n--', f2pydoc) if len(docparts) == 4: doc_has_optionals = True elif len(docparts) == 3: doc_has_optionals = False else: print('-- uninterpretable f2py documentation --') return f2pydoc # ---- replace arguments with _d suffix with empty string in ---- # ---- function signature (remove them): ---- docparts[0] = re.sub('[\[(,]\w+_d\d', '', docparts[0]) # ---- replace _d arguments of the return arrays with their default value: if doc_has_optionals: returnarray_dims = re.findall('[\[(,](\w+_d\d)', docparts[3]) for arg in returnarray_dims: searchpattern = arg + ' : input.*\n.*Default: (.*)\n' match = re.search(searchpattern, docparts[2]) if match: default = match.group(1) docparts[3] = re.sub(arg, default, docparts[3]) docparts[2] = re.sub(searchpattern, '', docparts[2]) # ---- remove all optional _d# from optional argument list: if doc_has_optionals: searchpattern = '\w+_d\d : input.*\n.*Default: (.*)\n' docparts[2] = re.sub(searchpattern, '', docparts[2]) # ---- combine doc parts to a single string processed_signature = '\n--'.join(docparts) return processed_signature
[ "def", "process_f2pydoc", "(", "f2pydoc", ")", ":", "# ---- 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", ")",...
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.
[ "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...
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/make_docs.py#L143-L188
train
203,832
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.from_cap
def from_cap(cls, theta, lwin, clat=None, clon=None, nwin=None, theta_degrees=True, coord_degrees=True, dj_matrix=None, weights=None): """ Construct spherical cap localization windows. Usage ----- x = SHWindow.from_cap(theta, lwin, [clat, clon, nwin, theta_degrees, coord_degrees, dj_matrix, weights]) Returns ------- x : SHWindow class instance Parameters ---------- theta : float Angular radius of the spherical cap localization domain (default in degrees). lwin : int Spherical harmonic bandwidth of the localization windows. clat, clon : float, optional, default = None Latitude and longitude of the center of the rotated spherical cap localization windows (default in degrees). nwin : int, optional, default (lwin+1)**2 Number of localization windows. theta_degrees : bool, optional, default = True True if theta is in degrees. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. weights : ndarray, optional, default = None Taper weights used with the multitaper spectral analyses. """ if theta_degrees: tapers, eigenvalues, taper_order = _shtools.SHReturnTapers( _np.radians(theta), lwin) else: tapers, eigenvalues, taper_order = _shtools.SHReturnTapers( theta, lwin) return SHWindowCap(theta, tapers, eigenvalues, taper_order, clat, clon, nwin, theta_degrees, coord_degrees, dj_matrix, weights, copy=False)
python
def from_cap(cls, theta, lwin, clat=None, clon=None, nwin=None, theta_degrees=True, coord_degrees=True, dj_matrix=None, weights=None): """ Construct spherical cap localization windows. Usage ----- x = SHWindow.from_cap(theta, lwin, [clat, clon, nwin, theta_degrees, coord_degrees, dj_matrix, weights]) Returns ------- x : SHWindow class instance Parameters ---------- theta : float Angular radius of the spherical cap localization domain (default in degrees). lwin : int Spherical harmonic bandwidth of the localization windows. clat, clon : float, optional, default = None Latitude and longitude of the center of the rotated spherical cap localization windows (default in degrees). nwin : int, optional, default (lwin+1)**2 Number of localization windows. theta_degrees : bool, optional, default = True True if theta is in degrees. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. weights : ndarray, optional, default = None Taper weights used with the multitaper spectral analyses. """ if theta_degrees: tapers, eigenvalues, taper_order = _shtools.SHReturnTapers( _np.radians(theta), lwin) else: tapers, eigenvalues, taper_order = _shtools.SHReturnTapers( theta, lwin) return SHWindowCap(theta, tapers, eigenvalues, taper_order, clat, clon, nwin, theta_degrees, coord_degrees, dj_matrix, weights, copy=False)
[ "def", "from_cap", "(", "cls", ",", "theta", ",", "lwin", ",", "clat", "=", "None", ",", "clon", "=", "None", ",", "nwin", "=", "None", ",", "theta_degrees", "=", "True", ",", "coord_degrees", "=", "True", ",", "dj_matrix", "=", "None", ",", "weights...
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.
[ "Construct", "spherical", "cap", "localization", "windows", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L119-L164
train
203,833
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.from_mask
def from_mask(cls, dh_mask, lwin, nwin=None, weights=None): """ Construct localization windows that are optimally concentrated within the region specified by a mask. Usage ----- x = SHWindow.from_mask(dh_mask, lwin, [nwin, weights]) Returns ------- x : SHWindow class instance Parameters ---------- dh_mask :ndarray, shape (nlat, nlon) A Driscoll and Healy (1994) sampled grid describing the concentration region R. All elements should either be 1 (for inside the concentration region) or 0 (for outside the concentration region). The grid must have dimensions nlon=nlat or nlon=2*nlat, where nlat is even. lwin : int The spherical harmonic bandwidth of the localization windows. nwin : int, optional, default = (lwin+1)**2 The number of best concentrated eigenvalues and eigenfunctions to return. weights ndarray, optional, default = None Taper weights used with the multitaper spectral analyses. """ if nwin is None: nwin = (lwin + 1)**2 else: if nwin > (lwin + 1)**2: raise ValueError('nwin must be less than or equal to ' + '(lwin + 1)**2. lwin = {:d} and nwin = {:d}' .format(lwin, nwin)) if dh_mask.shape[0] % 2 != 0: raise ValueError('The number of latitude bands in dh_mask ' + 'must be even. nlat = {:d}' .format(dh_mask.shape[0])) if dh_mask.shape[1] == dh_mask.shape[0]: _sampling = 1 elif dh_mask.shape[1] == 2 * dh_mask.shape[0]: _sampling = 2 else: raise ValueError('dh_mask must be dimensioned as (n, n) or ' + '(n, 2 * n). Input shape is ({:d}, {:d})' .format(dh_mask.shape[0], dh_mask.shape[1])) mask_lm = _shtools.SHExpandDH(dh_mask, sampling=_sampling, lmax_calc=0) area = mask_lm[0, 0, 0] * 4 * _np.pi tapers, eigenvalues = _shtools.SHReturnTapersMap(dh_mask, lwin, ntapers=nwin) return SHWindowMask(tapers, eigenvalues, weights, area, copy=False)
python
def from_mask(cls, dh_mask, lwin, nwin=None, weights=None): """ Construct localization windows that are optimally concentrated within the region specified by a mask. Usage ----- x = SHWindow.from_mask(dh_mask, lwin, [nwin, weights]) Returns ------- x : SHWindow class instance Parameters ---------- dh_mask :ndarray, shape (nlat, nlon) A Driscoll and Healy (1994) sampled grid describing the concentration region R. All elements should either be 1 (for inside the concentration region) or 0 (for outside the concentration region). The grid must have dimensions nlon=nlat or nlon=2*nlat, where nlat is even. lwin : int The spherical harmonic bandwidth of the localization windows. nwin : int, optional, default = (lwin+1)**2 The number of best concentrated eigenvalues and eigenfunctions to return. weights ndarray, optional, default = None Taper weights used with the multitaper spectral analyses. """ if nwin is None: nwin = (lwin + 1)**2 else: if nwin > (lwin + 1)**2: raise ValueError('nwin must be less than or equal to ' + '(lwin + 1)**2. lwin = {:d} and nwin = {:d}' .format(lwin, nwin)) if dh_mask.shape[0] % 2 != 0: raise ValueError('The number of latitude bands in dh_mask ' + 'must be even. nlat = {:d}' .format(dh_mask.shape[0])) if dh_mask.shape[1] == dh_mask.shape[0]: _sampling = 1 elif dh_mask.shape[1] == 2 * dh_mask.shape[0]: _sampling = 2 else: raise ValueError('dh_mask must be dimensioned as (n, n) or ' + '(n, 2 * n). Input shape is ({:d}, {:d})' .format(dh_mask.shape[0], dh_mask.shape[1])) mask_lm = _shtools.SHExpandDH(dh_mask, sampling=_sampling, lmax_calc=0) area = mask_lm[0, 0, 0] * 4 * _np.pi tapers, eigenvalues = _shtools.SHReturnTapersMap(dh_mask, lwin, ntapers=nwin) return SHWindowMask(tapers, eigenvalues, weights, area, copy=False)
[ "def", "from_mask", "(", "cls", ",", "dh_mask", ",", "lwin", ",", "nwin", "=", "None", ",", "weights", "=", "None", ")", ":", "if", "nwin", "is", "None", ":", "nwin", "=", "(", "lwin", "+", "1", ")", "**", "2", "else", ":", "if", "nwin", ">", ...
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.
[ "Construct", "localization", "windows", "that", "are", "optimally", "concentrated", "within", "the", "region", "specified", "by", "a", "mask", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L167-L224
train
203,834
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.to_array
def to_array(self, itaper, normalization='4pi', csphase=1): """ Return the spherical harmonic coefficients of taper i as a numpy array. Usage ----- coeffs = x.to_array(itaper, [normalization, csphase]) Returns ------- coeffs : ndarray, shape (2, lwin+1, lwin+11) 3-D numpy ndarray of the spherical harmonic coefficients of the window. Parameters ---------- itaper : int Taper number, where itaper=0 is the best concentrated. normalization : str, optional, default = '4pi' Normalization of the output coefficients: '4pi', 'ortho' or 'schmidt' for geodesy 4pi normalized, orthonormalized, or Schmidt semi-normalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """ if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt'): raise ValueError( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase)) ) return self._to_array( itaper, normalization=normalization.lower(), csphase=csphase)
python
def to_array(self, itaper, normalization='4pi', csphase=1): """ Return the spherical harmonic coefficients of taper i as a numpy array. Usage ----- coeffs = x.to_array(itaper, [normalization, csphase]) Returns ------- coeffs : ndarray, shape (2, lwin+1, lwin+11) 3-D numpy ndarray of the spherical harmonic coefficients of the window. Parameters ---------- itaper : int Taper number, where itaper=0 is the best concentrated. normalization : str, optional, default = '4pi' Normalization of the output coefficients: '4pi', 'ortho' or 'schmidt' for geodesy 4pi normalized, orthonormalized, or Schmidt semi-normalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """ if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt'): raise ValueError( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase)) ) return self._to_array( itaper, normalization=normalization.lower(), csphase=csphase)
[ "def", "to_array", "(", "self", ",", "itaper", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ")", ":", "if", "type", "(", "normalization", ")", "!=", "str", ":", "raise", "ValueError", "(", "'normalization must be a string. '", "+", "'Input t...
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.
[ "Return", "the", "spherical", "harmonic", "coefficients", "of", "taper", "i", "as", "a", "numpy", "array", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L269-L314
train
203,835
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.to_shcoeffs
def to_shcoeffs(self, itaper, normalization='4pi', csphase=1): """ Return the spherical harmonic coefficients of taper i as a SHCoeffs class instance. Usage ----- clm = x.to_shcoeffs(itaper, [normalization, csphase]) Returns ------- clm : SHCoeffs class instance Parameters ---------- itaper : int Taper number, where itaper=0 is the best concentrated. normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho' or 'schmidt' for geodesy 4pi-normalized, orthonormalized, or Schmidt semi-normalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """ if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in set(['4pi', 'ortho', 'schmidt']): raise ValueError( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase)) ) coeffs = self.to_array(itaper, normalization=normalization.lower(), csphase=csphase) return SHCoeffs.from_array(coeffs, normalization=normalization.lower(), csphase=csphase, copy=False)
python
def to_shcoeffs(self, itaper, normalization='4pi', csphase=1): """ Return the spherical harmonic coefficients of taper i as a SHCoeffs class instance. Usage ----- clm = x.to_shcoeffs(itaper, [normalization, csphase]) Returns ------- clm : SHCoeffs class instance Parameters ---------- itaper : int Taper number, where itaper=0 is the best concentrated. normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho' or 'schmidt' for geodesy 4pi-normalized, orthonormalized, or Schmidt semi-normalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """ if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in set(['4pi', 'ortho', 'schmidt']): raise ValueError( "normalization must be '4pi', 'ortho' " + "or 'schmidt'. Provided value was {:s}" .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase)) ) coeffs = self.to_array(itaper, normalization=normalization.lower(), csphase=csphase) return SHCoeffs.from_array(coeffs, normalization=normalization.lower(), csphase=csphase, copy=False)
[ "def", "to_shcoeffs", "(", "self", ",", "itaper", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ")", ":", "if", "type", "(", "normalization", ")", "!=", "str", ":", "raise", "ValueError", "(", "'normalization must be a string. '", "+", "'Inpu...
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.
[ "Return", "the", "spherical", "harmonic", "coefficients", "of", "taper", "i", "as", "a", "SHCoeffs", "class", "instance", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L316-L361
train
203,836
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.to_shgrid
def to_shgrid(self, itaper, grid='DH2', zeros=None): """ Evaluate the coefficients of taper i on a spherical grid and return a SHGrid class instance. Usage ----- f = x.to_shgrid(itaper, [grid, zeros]) Returns ------- f : SHGrid class instance Parameters ---------- itaper : int Taper number, where itaper=0 is the best concentrated. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2' for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a Gauss-Legendre quadrature grid. zeros : ndarray, optional, default = None The cos(colatitude) nodes used in the Gauss-Legendre Quadrature grids. Description ----------- For more information concerning the spherical harmonic expansions and the properties of the output grids, see the documentation for SHExpandDH and SHExpandGLQ. """ if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() in ('DH', 'DH1'): gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=1, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='DH', copy=False) elif grid.upper() == 'DH2': gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=2, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='DH', copy=False) elif grid.upper() == 'GLQ': if zeros is None: zeros, weights = _shtools.SHGLQ(self.lwin) gridout = _shtools.MakeGridGLQ(self.to_array(itaper), zeros, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='GLQ', copy=False) else: raise ValueError( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}".format(repr(grid)))
python
def to_shgrid(self, itaper, grid='DH2', zeros=None): """ Evaluate the coefficients of taper i on a spherical grid and return a SHGrid class instance. Usage ----- f = x.to_shgrid(itaper, [grid, zeros]) Returns ------- f : SHGrid class instance Parameters ---------- itaper : int Taper number, where itaper=0 is the best concentrated. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2' for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a Gauss-Legendre quadrature grid. zeros : ndarray, optional, default = None The cos(colatitude) nodes used in the Gauss-Legendre Quadrature grids. Description ----------- For more information concerning the spherical harmonic expansions and the properties of the output grids, see the documentation for SHExpandDH and SHExpandGLQ. """ if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() in ('DH', 'DH1'): gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=1, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='DH', copy=False) elif grid.upper() == 'DH2': gridout = _shtools.MakeGridDH(self.to_array(itaper), sampling=2, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='DH', copy=False) elif grid.upper() == 'GLQ': if zeros is None: zeros, weights = _shtools.SHGLQ(self.lwin) gridout = _shtools.MakeGridGLQ(self.to_array(itaper), zeros, norm=1, csphase=1) return SHGrid.from_array(gridout, grid='GLQ', copy=False) else: raise ValueError( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}".format(repr(grid)))
[ "def", "to_shgrid", "(", "self", ",", "itaper", ",", "grid", "=", "'DH2'", ",", "zeros", "=", "None", ")", ":", "if", "type", "(", "grid", ")", "!=", "str", ":", "raise", "ValueError", "(", "'grid must be a string. '", "+", "'Input type was {:s}'", ".", ...
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.
[ "Evaluate", "the", "coefficients", "of", "taper", "i", "on", "a", "spherical", "grid", "and", "return", "a", "SHGrid", "class", "instance", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L363-L416
train
203,837
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.multitaper_spectrum
def multitaper_spectrum(self, clm, k, convention='power', unit='per_l', **kwargs): """ Return the multitaper spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_spectrum(clm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper spectrum estimate, where lmax is the spherical-harmonic bandwidth of clm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper spectrum estimate. Parameters ---------- clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = clm.lmax The maximum spherical-harmonic degree of clm to use. taper_wt : ndarray, optional, default = None 1-D numpy array of the weights used in calculating the multitaper spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. """ return self._multitaper_spectrum(clm, k, convention=convention, unit=unit, **kwargs)
python
def multitaper_spectrum(self, clm, k, convention='power', unit='per_l', **kwargs): """ Return the multitaper spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_spectrum(clm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper spectrum estimate, where lmax is the spherical-harmonic bandwidth of clm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper spectrum estimate. Parameters ---------- clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = clm.lmax The maximum spherical-harmonic degree of clm to use. taper_wt : ndarray, optional, default = None 1-D numpy array of the weights used in calculating the multitaper spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. """ return self._multitaper_spectrum(clm, k, convention=convention, unit=unit, **kwargs)
[ "def", "multitaper_spectrum", "(", "self", ",", "clm", ",", "k", ",", "convention", "=", "'power'", ",", "unit", "=", "'per_l'", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_multitaper_spectrum", "(", "clm", ",", "k", ",", "convention", ...
Return the multitaper spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_spectrum(clm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper spectrum estimate, where lmax is the spherical-harmonic bandwidth of clm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper spectrum estimate. Parameters ---------- clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = clm.lmax The maximum spherical-harmonic degree of clm to use. taper_wt : ndarray, optional, default = None 1-D numpy array of the weights used in calculating the multitaper spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees.
[ "Return", "the", "multitaper", "spectrum", "estimate", "and", "standard", "error", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L418-L467
train
203,838
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.multitaper_cross_spectrum
def multitaper_cross_spectrum(self, clm, slm, k, convention='power', unit='per_l', **kwargs): """ Return the multitaper cross-spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper cross-spectrum estimate, where lmax is the smaller of the two spherical-harmonic bandwidths of clm and slm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper cross-spectrum estimate. Parameters ---------- clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the first global field to analyze. slm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the second global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = min(clm.lmax, slm.lmax) The maximum spherical-harmonic degree of the input coefficients to use. taper_wt : ndarray, optional, default = None The weights used in calculating the multitaper cross-spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. """ return self._multitaper_cross_spectrum(clm, slm, k, convention=convention, unit=unit, **kwargs)
python
def multitaper_cross_spectrum(self, clm, slm, k, convention='power', unit='per_l', **kwargs): """ Return the multitaper cross-spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper cross-spectrum estimate, where lmax is the smaller of the two spherical-harmonic bandwidths of clm and slm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper cross-spectrum estimate. Parameters ---------- clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the first global field to analyze. slm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the second global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = min(clm.lmax, slm.lmax) The maximum spherical-harmonic degree of the input coefficients to use. taper_wt : ndarray, optional, default = None The weights used in calculating the multitaper cross-spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. """ return self._multitaper_cross_spectrum(clm, slm, k, convention=convention, unit=unit, **kwargs)
[ "def", "multitaper_cross_spectrum", "(", "self", ",", "clm", ",", "slm", ",", "k", ",", "convention", "=", "'power'", ",", "unit", "=", "'per_l'", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_multitaper_cross_spectrum", "(", "clm", ",", "s...
Return the multitaper cross-spectrum estimate and standard error. Usage ----- mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit, lmax, taper_wt, clat, clon, coord_degrees]) Returns ------- mtse : ndarray, shape (lmax-lwin+1) The localized multitaper cross-spectrum estimate, where lmax is the smaller of the two spherical-harmonic bandwidths of clm and slm, and lwin is the spherical-harmonic bandwidth of the localization windows. sd : ndarray, shape (lmax-lwin+1) The standard error of the localized multitaper cross-spectrum estimate. Parameters ---------- clm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the first global field to analyze. slm : SHCoeffs class instance SHCoeffs class instance containing the spherical harmonic coefficients of the second global field to analyze. k : int The number of tapers to be utilized in performing the multitaper spectral analysis. convention : str, optional, default = 'power' The type of output spectra: 'power' for power spectra, and 'energy' for energy spectra. unit : str, optional, default = 'per_l' The units of the output spectra. If 'per_l', the spectra contain the total contribution for each spherical harmonic degree l. If 'per_lm', the spectra contain the average contribution for each coefficient at spherical harmonic degree l. lmax : int, optional, default = min(clm.lmax, slm.lmax) The maximum spherical-harmonic degree of the input coefficients to use. taper_wt : ndarray, optional, default = None The weights used in calculating the multitaper cross-spectral estimates and standard error. clat, clon : float, optional, default = 90., 0. Latitude and longitude of the center of the spherical-cap localization windows. coord_degrees : bool, optional, default = True True if clat and clon are in degrees.
[ "Return", "the", "multitaper", "cross", "-", "spectrum", "estimate", "and", "standard", "error", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L469-L525
train
203,839
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.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). """ 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
python
def spectra(self, itaper=None, nwin=None, convention='power', unit='per_l', base=10.): """ Return the spectra of one or more localization windows. Usage ----- spectra = x.spectra([itaper, nwin, convention, unit, base]) Returns ------- spectra : ndarray, shape (lwin+1, nwin) A matrix with each column containing the spectrum of a localization window, and where the windows are arranged with increasing concentration factors. If itaper is set, only a single vector is returned, whereas if nwin is set, the first nwin spectra are returned. Parameters ---------- itaper : int, optional, default = None The taper number of the output spectrum, where itaper=0 corresponds to the best concentrated taper. nwin : int, optional, default = 1 The number of best concentrated localization window power spectra to return. convention : str, optional, default = 'power' The type of spectrum to return: 'power' for power spectrum, 'energy' for energy spectrum, and 'l2norm' for the l2 norm spectrum. unit : str, optional, default = 'per_l' If 'per_l', return the total contribution to the spectrum for each spherical harmonic degree l. If 'per_lm', return the average contribution to the spectrum for each coefficient at spherical harmonic degree l. If 'per_dlogl', return the spectrum per log interval dlog_a(l). base : float, optional, default = 10. The logarithm base when calculating the 'per_dlogl' spectrum. Description ----------- This function returns either the power spectrum, energy spectrum, or l2-norm spectrum of one or more of the localization windows. Total power is defined as the integral of the function squared over all space, divided by the area the function spans. If the mean of the function is zero, this is equivalent to the variance of the function. The total energy is the integral of the function squared over all space and is 4pi times the total power. The l2-norm is the sum of the magnitude of the coefficients squared. The output spectrum can be expresed using one of three units. 'per_l' returns the contribution to the total spectrum from all angular orders at degree l. 'per_lm' returns the average contribution to the total spectrum from a single coefficient at degree l. The 'per_lm' spectrum is equal to the 'per_l' spectrum divided by (2l+1). 'per_dlogl' returns the contribution to the total spectrum from all angular orders over an infinitessimal logarithmic degree band. The contrubution in the band dlog_a(l) is spectrum(l, 'per_dlogl')*dlog_a(l), where a is the base, and where spectrum(l, 'per_dlogl) is equal to spectrum(l, 'per_l')*l*log(a). """ if itaper is None: if nwin is None: nwin = self.nwin spectra = _np.zeros((self.lwin+1, nwin)) for iwin in range(nwin): coeffs = self.to_array(iwin) spectra[:, iwin] = _spectrum(coeffs, normalization='4pi', convention=convention, unit=unit, base=base) else: coeffs = self.to_array(itaper) spectra = _spectrum(coeffs, normalization='4pi', convention=convention, unit=unit, base=base) return spectra
[ "def", "spectra", "(", "self", ",", "itaper", "=", "None", ",", "nwin", "=", "None", ",", "convention", "=", "'power'", ",", "unit", "=", "'per_l'", ",", "base", "=", "10.", ")", ":", "if", "itaper", "is", "None", ":", "if", "nwin", "is", "None", ...
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).
[ "Return", "the", "spectra", "of", "one", "or", "more", "localization", "windows", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L574-L651
train
203,840
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.coupling_matrix
def coupling_matrix(self, lmax, nwin=None, weights=None, mode='full'): """ Return the coupling matrix of the first nwin tapers. This matrix relates the global power spectrum to the expectation of the localized multitaper spectrum. Usage ----- Mmt = x.coupling_matrix(lmax, [nwin, weights, mode]) Returns ------- Mmt : ndarray, shape (lmax+lwin+1, lmax+1) or (lmax+1, lmax+1) or (lmax-lwin+1, lmax+1) Parameters ---------- lmax : int Spherical harmonic bandwidth of the global power spectrum. nwin : int, optional, default = x.nwin Number of tapers used in the mutlitaper spectral analysis. weights : ndarray, optional, default = x.weights Taper weights used with the multitaper spectral analyses. mode : str, opitonal, default = 'full' 'full' returns a biased output spectrum of size lmax+lwin+1. The input spectrum is assumed to be zero for degrees l>lmax. 'same' returns a biased output spectrum with the same size (lmax+1) as the input spectrum. The input spectrum is assumed to be zero for degrees l>lmax. 'valid' returns a biased spectrum with size lmax-lwin+1. This returns only that part of the biased spectrum that is not influenced by the input spectrum beyond degree lmax. """ if weights is not None: if nwin is not None: if len(weights) != nwin: raise ValueError( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}'.format(len(weights), nwin)) else: if len(weights) != self.nwin: raise ValueError( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}'.format(len(weights), self.nwin)) if mode == 'full': return self._coupling_matrix(lmax, nwin=nwin, weights=weights) elif mode == 'same': cmatrix = self._coupling_matrix(lmax, nwin=nwin, weights=weights) return cmatrix[:lmax+1, :] elif mode == 'valid': cmatrix = self._coupling_matrix(lmax, nwin=nwin, weights=weights) return cmatrix[:lmax - self.lwin+1, :] else: raise ValueError("mode has to be 'full', 'same' or 'valid', not " "{}".format(mode))
python
def coupling_matrix(self, lmax, nwin=None, weights=None, mode='full'): """ Return the coupling matrix of the first nwin tapers. This matrix relates the global power spectrum to the expectation of the localized multitaper spectrum. Usage ----- Mmt = x.coupling_matrix(lmax, [nwin, weights, mode]) Returns ------- Mmt : ndarray, shape (lmax+lwin+1, lmax+1) or (lmax+1, lmax+1) or (lmax-lwin+1, lmax+1) Parameters ---------- lmax : int Spherical harmonic bandwidth of the global power spectrum. nwin : int, optional, default = x.nwin Number of tapers used in the mutlitaper spectral analysis. weights : ndarray, optional, default = x.weights Taper weights used with the multitaper spectral analyses. mode : str, opitonal, default = 'full' 'full' returns a biased output spectrum of size lmax+lwin+1. The input spectrum is assumed to be zero for degrees l>lmax. 'same' returns a biased output spectrum with the same size (lmax+1) as the input spectrum. The input spectrum is assumed to be zero for degrees l>lmax. 'valid' returns a biased spectrum with size lmax-lwin+1. This returns only that part of the biased spectrum that is not influenced by the input spectrum beyond degree lmax. """ if weights is not None: if nwin is not None: if len(weights) != nwin: raise ValueError( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}'.format(len(weights), nwin)) else: if len(weights) != self.nwin: raise ValueError( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}'.format(len(weights), self.nwin)) if mode == 'full': return self._coupling_matrix(lmax, nwin=nwin, weights=weights) elif mode == 'same': cmatrix = self._coupling_matrix(lmax, nwin=nwin, weights=weights) return cmatrix[:lmax+1, :] elif mode == 'valid': cmatrix = self._coupling_matrix(lmax, nwin=nwin, weights=weights) return cmatrix[:lmax - self.lwin+1, :] else: raise ValueError("mode has to be 'full', 'same' or 'valid', not " "{}".format(mode))
[ "def", "coupling_matrix", "(", "self", ",", "lmax", ",", "nwin", "=", "None", ",", "weights", "=", "None", ",", "mode", "=", "'full'", ")", ":", "if", "weights", "is", "not", "None", ":", "if", "nwin", "is", "not", "None", ":", "if", "len", "(", ...
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.
[ "Return", "the", "coupling", "matrix", "of", "the", "first", "nwin", "tapers", ".", "This", "matrix", "relates", "the", "global", "power", "spectrum", "to", "the", "expectation", "of", "the", "localized", "multitaper", "spectrum", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L653-L712
train
203,841
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindow.plot_coupling_matrix
def plot_coupling_matrix(self, lmax, nwin=None, weights=None, mode='full', axes_labelsize=None, tick_labelsize=None, show=True, ax=None, fname=None): """ Plot the multitaper coupling matrix. This matrix relates the global power spectrum to the expectation of the localized multitaper spectrum. Usage ----- x.plot_coupling_matrix(lmax, [nwin, weights, mode, axes_labelsize, tick_labelsize, show, ax, fname]) Parameters ---------- lmax : int Spherical harmonic bandwidth of the global power spectrum. nwin : int, optional, default = x.nwin Number of tapers used in the mutlitaper spectral analysis. weights : ndarray, optional, default = x.weights Taper weights used with the multitaper spectral analyses. mode : str, opitonal, default = 'full' 'full' returns a biased output spectrum of size lmax+lwin+1. The input spectrum is assumed to be zero for degrees l>lmax. 'same' returns a biased output spectrum with the same size (lmax+1) as the input spectrum. The input spectrum is assumed to be zero for degrees l>lmax. 'valid' returns a biased spectrum with size lmax-lwin+1. This returns only that part of the biased spectrum that is not influenced by the input spectrum beyond degree lmax. axes_labelsize : int, optional, default = None The font size for the x and y axes labels. tick_labelsize : int, optional, default = None The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. ax : matplotlib axes object, optional, default = None An array of matplotlib axes objects where the plots will appear. fname : str, optional, default = None If present, save the image to the specified file. """ figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0]) if axes_labelsize is None: axes_labelsize = _mpl.rcParams['axes.labelsize'] if tick_labelsize is None: tick_labelsize = _mpl.rcParams['xtick.labelsize'] if ax is None: fig = _plt.figure(figsize=figsize) axes = fig.add_subplot(111) else: axes = ax axes.imshow(self.coupling_matrix(lmax, nwin=nwin, weights=weights, mode=mode), aspect='auto') axes.set_xlabel('Input power', fontsize=axes_labelsize) axes.set_ylabel('Output power', fontsize=axes_labelsize) axes.tick_params(labelsize=tick_labelsize) axes.minorticks_on() if ax is None: fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes
python
def plot_coupling_matrix(self, lmax, nwin=None, weights=None, mode='full', axes_labelsize=None, tick_labelsize=None, show=True, ax=None, fname=None): """ Plot the multitaper coupling matrix. This matrix relates the global power spectrum to the expectation of the localized multitaper spectrum. Usage ----- x.plot_coupling_matrix(lmax, [nwin, weights, mode, axes_labelsize, tick_labelsize, show, ax, fname]) Parameters ---------- lmax : int Spherical harmonic bandwidth of the global power spectrum. nwin : int, optional, default = x.nwin Number of tapers used in the mutlitaper spectral analysis. weights : ndarray, optional, default = x.weights Taper weights used with the multitaper spectral analyses. mode : str, opitonal, default = 'full' 'full' returns a biased output spectrum of size lmax+lwin+1. The input spectrum is assumed to be zero for degrees l>lmax. 'same' returns a biased output spectrum with the same size (lmax+1) as the input spectrum. The input spectrum is assumed to be zero for degrees l>lmax. 'valid' returns a biased spectrum with size lmax-lwin+1. This returns only that part of the biased spectrum that is not influenced by the input spectrum beyond degree lmax. axes_labelsize : int, optional, default = None The font size for the x and y axes labels. tick_labelsize : int, optional, default = None The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. ax : matplotlib axes object, optional, default = None An array of matplotlib axes objects where the plots will appear. fname : str, optional, default = None If present, save the image to the specified file. """ figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0]) if axes_labelsize is None: axes_labelsize = _mpl.rcParams['axes.labelsize'] if tick_labelsize is None: tick_labelsize = _mpl.rcParams['xtick.labelsize'] if ax is None: fig = _plt.figure(figsize=figsize) axes = fig.add_subplot(111) else: axes = ax axes.imshow(self.coupling_matrix(lmax, nwin=nwin, weights=weights, mode=mode), aspect='auto') axes.set_xlabel('Input power', fontsize=axes_labelsize) axes.set_ylabel('Output power', fontsize=axes_labelsize) axes.tick_params(labelsize=tick_labelsize) axes.minorticks_on() if ax is None: fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes
[ "def", "plot_coupling_matrix", "(", "self", ",", "lmax", ",", "nwin", "=", "None", ",", "weights", "=", "None", ",", "mode", "=", "'full'", ",", "axes_labelsize", "=", "None", ",", "tick_labelsize", "=", "None", ",", "show", "=", "True", ",", "ax", "="...
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.
[ "Plot", "the", "multitaper", "coupling", "matrix", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L1020-L1089
train
203,842
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindowCap._taper2coeffs
def _taper2coeffs(self, itaper): """ Return the spherical harmonic coefficients of the unrotated taper i as an array, where i = 0 is the best concentrated. """ taperm = self.orders[itaper] coeffs = _np.zeros((2, self.lwin + 1, self.lwin + 1)) if taperm < 0: coeffs[1, :, abs(taperm)] = self.tapers[:, itaper] else: coeffs[0, :, abs(taperm)] = self.tapers[:, itaper] return coeffs
python
def _taper2coeffs(self, itaper): """ Return the spherical harmonic coefficients of the unrotated taper i as an array, where i = 0 is the best concentrated. """ taperm = self.orders[itaper] coeffs = _np.zeros((2, self.lwin + 1, self.lwin + 1)) if taperm < 0: coeffs[1, :, abs(taperm)] = self.tapers[:, itaper] else: coeffs[0, :, abs(taperm)] = self.tapers[:, itaper] return coeffs
[ "def", "_taper2coeffs", "(", "self", ",", "itaper", ")", ":", "taperm", "=", "self", ".", "orders", "[", "itaper", "]", "coeffs", "=", "_np", ".", "zeros", "(", "(", "2", ",", "self", ".", "lwin", "+", "1", ",", "self", ".", "lwin", "+", "1", "...
Return the spherical harmonic coefficients of the unrotated taper i as an array, where i = 0 is the best concentrated.
[ "Return", "the", "spherical", "harmonic", "coefficients", "of", "the", "unrotated", "taper", "i", "as", "an", "array", "where", "i", "=", "0", "is", "the", "best", "concentrated", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L1157-L1169
train
203,843
SHTOOLS/SHTOOLS
pyshtools/shclasses/shwindow.py
SHWindowCap.rotate
def rotate(self, clat, clon, coord_degrees=True, dj_matrix=None, nwinrot=None): """" Rotate the spherical-cap windows centered on the North pole to clat and clon, and save the spherical harmonic coefficients in the attribute coeffs. Usage ----- x.rotate(clat, clon [coord_degrees, dj_matrix, nwinrot]) Parameters ---------- clat, clon : float Latitude and longitude of the center of the rotated spherical-cap localization windows (default in degrees). coord_degrees : bool, optional, default = True True if clat and clon are in degrees. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. nwinrot : int, optional, default = (lwin+1)**2 The number of best concentrated windows to rotate, where lwin is the spherical harmonic bandwidth of the localization windows. Description ----------- This function will take the spherical-cap localization windows centered at the North pole (and saved in the attributes tapers and orders), rotate each function to the coordinate (clat, clon), and save the spherical harmonic coefficients in the attribute coeffs. Each column of coeffs contains a single window, and the coefficients are ordered according to the convention in SHCilmToVector. """ self.coeffs = _np.zeros(((self.lwin + 1)**2, self.nwin)) self.clat = clat self.clon = clon self.coord_degrees = coord_degrees if nwinrot is not None: self.nwinrot = nwinrot else: self.nwinrot = self.nwin if self.coord_degrees: angles = _np.radians(_np.array([0., -(90. - clat), -clon])) else: angles = _np.array([0., -(_np.pi/2. - clat), -clon]) if dj_matrix is None: if self.dj_matrix is None: self.dj_matrix = _shtools.djpi2(self.lwin + 1) dj_matrix = self.dj_matrix else: dj_matrix = self.dj_matrix if ((coord_degrees is True and clat == 90. and clon == 0.) or (coord_degrees is False and clat == _np.pi/2. and clon == 0.)): for i in range(self.nwinrot): coeffs = self._taper2coeffs(i) self.coeffs[:, i] = _shtools.SHCilmToVector(coeffs) else: coeffs = _shtools.SHRotateTapers(self.tapers, self.orders, self.nwinrot, angles, dj_matrix) self.coeffs = coeffs
python
def rotate(self, clat, clon, coord_degrees=True, dj_matrix=None, nwinrot=None): """" Rotate the spherical-cap windows centered on the North pole to clat and clon, and save the spherical harmonic coefficients in the attribute coeffs. Usage ----- x.rotate(clat, clon [coord_degrees, dj_matrix, nwinrot]) Parameters ---------- clat, clon : float Latitude and longitude of the center of the rotated spherical-cap localization windows (default in degrees). coord_degrees : bool, optional, default = True True if clat and clon are in degrees. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. nwinrot : int, optional, default = (lwin+1)**2 The number of best concentrated windows to rotate, where lwin is the spherical harmonic bandwidth of the localization windows. Description ----------- This function will take the spherical-cap localization windows centered at the North pole (and saved in the attributes tapers and orders), rotate each function to the coordinate (clat, clon), and save the spherical harmonic coefficients in the attribute coeffs. Each column of coeffs contains a single window, and the coefficients are ordered according to the convention in SHCilmToVector. """ self.coeffs = _np.zeros(((self.lwin + 1)**2, self.nwin)) self.clat = clat self.clon = clon self.coord_degrees = coord_degrees if nwinrot is not None: self.nwinrot = nwinrot else: self.nwinrot = self.nwin if self.coord_degrees: angles = _np.radians(_np.array([0., -(90. - clat), -clon])) else: angles = _np.array([0., -(_np.pi/2. - clat), -clon]) if dj_matrix is None: if self.dj_matrix is None: self.dj_matrix = _shtools.djpi2(self.lwin + 1) dj_matrix = self.dj_matrix else: dj_matrix = self.dj_matrix if ((coord_degrees is True and clat == 90. and clon == 0.) or (coord_degrees is False and clat == _np.pi/2. and clon == 0.)): for i in range(self.nwinrot): coeffs = self._taper2coeffs(i) self.coeffs[:, i] = _shtools.SHCilmToVector(coeffs) else: coeffs = _shtools.SHRotateTapers(self.tapers, self.orders, self.nwinrot, angles, dj_matrix) self.coeffs = coeffs
[ "def", "rotate", "(", "self", ",", "clat", ",", "clon", ",", "coord_degrees", "=", "True", ",", "dj_matrix", "=", "None", ",", "nwinrot", "=", "None", ")", ":", "self", ".", "coeffs", "=", "_np", ".", "zeros", "(", "(", "(", "self", ".", "lwin", ...
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.
[ "Rotate", "the", "spherical", "-", "cap", "windows", "centered", "on", "the", "North", "pole", "to", "clat", "and", "clon", "and", "save", "the", "spherical", "harmonic", "coefficients", "in", "the", "attribute", "coeffs", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L1198-L1262
train
203,844
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vxx
def plot_vxx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxx component of the tensor. Usage ----- x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = False If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xx}$' Text label for the colorbar.. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vxx_label if ax is None: fig, axes = self.vxx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vxx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxx component of the tensor. Usage ----- x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = False If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xx}$' Text label for the colorbar.. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vxx_label if ax is None: fig, axes = self.vxx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vxx", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vxx", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L123-L175
train
203,845
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vyy
def plot_vyy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyy component of the tensor. Usage ----- x.plot_vyy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vyy_label if ax is None: fig, axes = self.vyy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vyy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyy component of the tensor. Usage ----- x.plot_vyy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vyy_label if ax is None: fig, axes = self.vyy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vyy", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vyy", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L177-L229
train
203,846
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vzz
def plot_vzz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzz component of the tensor. Usage ----- x.plot_vzz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vzz_label if ax is None: fig, axes = self.vzz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vzz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzz component of the tensor. Usage ----- x.plot_vzz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vzz_label if ax is None: fig, axes = self.vzz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vzz", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vzz", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L231-L283
train
203,847
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vxy
def plot_vxy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxy component of the tensor. Usage ----- x.plot_vxy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vxy_label if ax is None: fig, axes = self.vxy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vxy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxy component of the tensor. Usage ----- x.plot_vxy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vxy_label if ax is None: fig, axes = self.vxy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vxy", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vxy", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L285-L337
train
203,848
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vyx
def plot_vyx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyx component of the tensor. Usage ----- x.plot_vyx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yx}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vyx_label if ax is None: fig, axes = self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vyx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyx component of the tensor. Usage ----- x.plot_vyx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yx}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vyx_label if ax is None: fig, axes = self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vyx", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vyx", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L339-L391
train
203,849
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vxz
def plot_vxz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxz component of the tensor. Usage ----- x.plot_vxz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vxz_label if ax is None: fig, axes = self.vxz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vxz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxz component of the tensor. Usage ----- x.plot_vxz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{xz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vxz_label if ax is None: fig, axes = self.vxz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vxz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vxz", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vxz", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L393-L445
train
203,850
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vzx
def plot_vzx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzx component of the tensor. Usage ----- x.plot_vzx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zx}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vzx_label if ax is None: fig, axes = self.vzx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vzx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzx component of the tensor. Usage ----- x.plot_vzx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zx}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vzx_label if ax is None: fig, axes = self.vzx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzx.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vzx", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vzx", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L447-L499
train
203,851
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vyz
def plot_vyz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyz component of the tensor. Usage ----- x.plot_vyz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vyz_label if ax is None: fig, axes = self.vyz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vyz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vyz component of the tensor. Usage ----- x.plot_vyz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{yz}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vyz_label if ax is None: fig, axes = self.vyz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vyz.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vyz", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vyz", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L501-L553
train
203,852
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_vzy
def plot_vzy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzy component of the tensor. Usage ----- x.plot_vzy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vzy_label if ax is None: fig, axes = self.vzy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_vzy(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vzy component of the tensor. Usage ----- x.plot_vzy([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$V_{zy}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._vzy_label if ax is None: fig, axes = self.vzy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.vzy.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "def", "plot_vzy", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
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.
[ "Plot", "the", "Vzy", "component", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L555-L607
train
203,853
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_invar
def plot_invar(self, colorbar=True, cb_orientation='horizontal', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the three invariants of the tensor and the derived quantity I. Usage ----- x.plot_invar([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if colorbar is True: if cb_orientation == 'horizontal': scale = 0.8 else: scale = 0.5 else: scale = 0.6 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(2, 2, figsize=figsize) self.plot_i0(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[3], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
python
def plot_invar(self, colorbar=True, cb_orientation='horizontal', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the three invariants of the tensor and the derived quantity I. Usage ----- x.plot_invar([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if colorbar is True: if cb_orientation == 'horizontal': scale = 0.8 else: scale = 0.5 else: scale = 0.6 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(2, 2, figsize=figsize) self.plot_i0(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_i(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[3], tick_interval=tick_interval, xlabel=xlabel, ylabel=ylabel, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
[ "def", "plot_invar", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'horizontal'", ",", "tick_interval", "=", "[", "60", ",", "60", "]", ",", "minor_tick_interval", "=", "[", "20", ",", "20", "]", ",", "xlabel", "=", "'Longitude'...
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.
[ "Plot", "the", "three", "invariants", "of", "the", "tensor", "and", "the", "derived", "quantity", "I", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L979-L1072
train
203,854
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eig1
def plot_eig1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first eigenvalue of the tensor. Usage ----- x.plot_eig1([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_1$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eig1_label if self.eig1 is None: self.compute_eig() if ax is None: fig, axes = self.eig1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_eig1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first eigenvalue of the tensor. Usage ----- x.plot_eig1([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_1$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eig1_label if self.eig1 is None: self.compute_eig() if ax is None: fig, axes = self.eig1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "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.
[ "Plot", "the", "first", "eigenvalue", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1074-L1130
train
203,855
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eig2
def plot_eig2(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second eigenvalue of the tensor. Usage ----- x.plot_eig2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_2$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eig2_label if self.eig2 is None: self.compute_eig() if ax is None: fig, axes = self.eig2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_eig2(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second eigenvalue of the tensor. Usage ----- x.plot_eig2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_2$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eig2_label if self.eig2 is None: self.compute_eig() if ax is None: fig, axes = self.eig2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "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.
[ "Plot", "the", "second", "eigenvalue", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1132-L1188
train
203,856
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eig3
def plot_eig3(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the third eigenvalue of the tensor. Usage ----- x.plot_eig3([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_3$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eig3_label if self.eig3 is None: self.compute_eig() if ax is None: fig, axes = self.eig3.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig3.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_eig3(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the third eigenvalue of the tensor. Usage ----- x.plot_eig3([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_3$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eig3_label if self.eig3 is None: self.compute_eig() if ax is None: fig, axes = self.eig3.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eig3.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "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.
[ "Plot", "the", "third", "eigenvalue", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1190-L1246
train
203,857
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eigs
def plot_eigs(self, colorbar=True, cb_orientation='vertical', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the three eigenvalues of the tensor. Usage ----- x.plot_eigs([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if colorbar is True: if cb_orientation == 'horizontal': scale = 2.3 else: scale = 1.4 else: scale = 1.65 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(3, 1, figsize=figsize) self.plot_eig1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eig2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eig3(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
python
def plot_eigs(self, colorbar=True, cb_orientation='vertical', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the three eigenvalues of the tensor. Usage ----- x.plot_eigs([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if colorbar is True: if cb_orientation == 'horizontal': scale = 2.3 else: scale = 1.4 else: scale = 1.65 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(3, 1, figsize=figsize) self.plot_eig1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eig2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eig3(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, axes_labelsize=axes_labelsize, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
[ "def", "plot_eigs", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "tick_interval", "=", "[", "60", ",", "60", "]", ",", "minor_tick_interval", "=", "[", "20", ",", "20", "]", ",", "xlabel", "=", "'Longitude'", ...
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.
[ "Plot", "the", "three", "eigenvalues", "of", "the", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1248-L1334
train
203,858
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eigh1
def plot_eigh1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh1([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{h1}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eigh1_label if self.eigh1 is None: self.compute_eigh() if ax is None: fig, axes = self.eigh1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eigh1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_eigh1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh1([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{h1}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eigh1_label if self.eigh1 is None: self.compute_eigh() if ax is None: fig, axes = self.eigh1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eigh1.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "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.
[ "Plot", "the", "first", "eigenvalue", "of", "the", "horizontal", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1336-L1392
train
203,859
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eigh2
def plot_eigh2(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{h2}$, Eotvos$^{-1}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eigh2_label if self.eigh2 is None: self.compute_eigh() if ax is None: fig, axes = self.eigh2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eigh2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_eigh2(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh2([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{h2}$, Eotvos$^{-1}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eigh2_label if self.eigh2 is None: self.compute_eigh() if ax is None: fig, axes = self.eigh2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eigh2.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "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.
[ "Plot", "the", "second", "eigenvalue", "of", "the", "horizontal", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1394-L1450
train
203,860
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eighh
def plot_eighh(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eighh([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{hh}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eighh_label if self.eighh is None: self.compute_eigh() if ax is None: fig, axes = self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def plot_eighh(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eighh([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{hh}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eighh_label if self.eighh is None: self.compute_eigh() if ax is None: fig, axes = self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
[ "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.
[ "Plot", "the", "maximum", "absolute", "value", "eigenvalue", "of", "the", "horizontal", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1452-L1508
train
203,861
SHTOOLS/SHTOOLS
pyshtools/shclasses/shtensor.py
Tensor.plot_eigh
def plot_eigh(self, colorbar=True, cb_orientation='vertical', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the two eigenvalues and maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if colorbar is True: if cb_orientation == 'horizontal': scale = 2.3 else: scale = 1.4 else: scale = 1.65 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(3, 1, figsize=figsize) self.plot_eigh1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eigh2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eighh(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
python
def plot_eigh(self, colorbar=True, cb_orientation='vertical', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the two eigenvalues and maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if colorbar is True: if cb_orientation == 'horizontal': scale = 2.3 else: scale = 1.4 else: scale = 1.65 figsize = (_mpl.rcParams['figure.figsize'][0], _mpl.rcParams['figure.figsize'][0] * scale) fig, ax = _plt.subplots(3, 1, figsize=figsize) self.plot_eigh1(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[0], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eigh2(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[1], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) self.plot_eighh(colorbar=colorbar, cb_orientation=cb_orientation, ax=ax.flat[2], xlabel=xlabel, ylabel=ylabel, tick_interval=tick_interval, tick_labelsize=tick_labelsize, minor_tick_interval=minor_tick_interval, **kwargs) fig.tight_layout(pad=0.5) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, ax
[ "def", "plot_eigh", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "tick_interval", "=", "[", "60", ",", "60", "]", ",", "minor_tick_interval", "=", "[", "20", ",", "20", "]", ",", "xlabel", "=", "'Longitude'", ...
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.
[ "Plot", "the", "two", "eigenvalues", "and", "maximum", "absolute", "value", "eigenvalue", "of", "the", "horizontal", "tensor", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1510-L1594
train
203,862
SHTOOLS/SHTOOLS
setup.py
get_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 """ 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
python
def get_version(): """Get version from git and VERSION file. In the case where the version is not tagged in git, this function appends .post0+commit if the version has been released and .dev0+commit if the version has not yet been released. Derived from: https://github.com/Changaco/version.py """ d = os.path.dirname(__file__) # get release number from VERSION with open(os.path.join(d, 'VERSION')) as f: vre = re.compile('.Version: (.+)$', re.M) version = vre.search(f.read()).group(1) if os.path.isdir(os.path.join(d, '.git')): # Get the version using "git describe". cmd = 'git describe --tags' try: git_version = check_output(cmd.split()).decode().strip()[1:] except CalledProcessError: print('Unable to get version number from git tags\n' 'Setting to x.x') git_version = 'x.x' # PEP440 compatibility if '-' in git_version: git_revision = check_output(['git', 'rev-parse', 'HEAD']) git_revision = git_revision.strip().decode('ascii') # add post0 if the version is released # otherwise add dev0 if the version is not yet released if ISRELEASED: version += '.post0+' + git_revision[:7] else: version += '.dev0+' + git_revision[:7] return version
[ "def", "get_version", "(", ")", ":", "d", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "# get release number from VERSION", "with", "open", "(", "os", ".", "path", ".", "join", "(", "d", ",", "'VERSION'", ")", ")", "as", "f", ":", "v...
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
[ "Get", "version", "from", "git", "and", "VERSION", "file", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/setup.py#L49-L85
train
203,863
SHTOOLS/SHTOOLS
setup.py
get_compiler_flags
def get_compiler_flags(): """Set fortran flags depending on the compiler.""" compiler = get_default_fcompiler() if compiler == 'absoft': flags = ['-m64', '-O3', '-YEXT_NAMES=LCS', '-YEXT_SFX=_', '-fpic', '-speed_math=10'] elif compiler == 'gnu95': flags = ['-m64', '-fPIC', '-O3', '-ffast-math'] elif compiler == 'intel': flags = ['-m64', '-fpp', '-free', '-O3', '-Tf'] elif compiler == 'g95': flags = ['-O3', '-fno-second-underscore'] elif compiler == 'pg': flags = ['-fast'] else: flags = ['-m64', '-O3'] return flags
python
def get_compiler_flags(): """Set fortran flags depending on the compiler.""" compiler = get_default_fcompiler() if compiler == 'absoft': flags = ['-m64', '-O3', '-YEXT_NAMES=LCS', '-YEXT_SFX=_', '-fpic', '-speed_math=10'] elif compiler == 'gnu95': flags = ['-m64', '-fPIC', '-O3', '-ffast-math'] elif compiler == 'intel': flags = ['-m64', '-fpp', '-free', '-O3', '-Tf'] elif compiler == 'g95': flags = ['-O3', '-fno-second-underscore'] elif compiler == 'pg': flags = ['-fast'] else: flags = ['-m64', '-O3'] return flags
[ "def", "get_compiler_flags", "(", ")", ":", "compiler", "=", "get_default_fcompiler", "(", ")", "if", "compiler", "==", "'absoft'", ":", "flags", "=", "[", "'-m64'", ",", "'-O3'", ",", "'-YEXT_NAMES=LCS'", ",", "'-YEXT_SFX=_'", ",", "'-fpic'", ",", "'-speed_ma...
Set fortran flags depending on the compiler.
[ "Set", "fortran", "flags", "depending", "on", "the", "compiler", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/setup.py#L183-L199
train
203,864
SHTOOLS/SHTOOLS
setup.py
configuration
def configuration(parent_package='', top_path=None): """Configure all packages that need to be built.""" config = Configuration('', parent_package, top_path) F95FLAGS = get_compiler_flags() kwargs = { 'libraries': [], 'include_dirs': [], 'library_dirs': [], } kwargs['extra_compile_args'] = F95FLAGS kwargs['f2py_options'] = ['--quiet'] # numpy.distutils.fcompiler.FCompiler doesn't support .F95 extension compiler = FCompiler(get_default_fcompiler()) compiler.src_extensions.append('.F95') compiler.language_map['.F95'] = 'f90' # collect all Fortran sources files = os.listdir('src') exclude_sources = ['PlanetsConstants.f95', 'PythonWrapper.f95'] sources = [os.path.join('src', file) for file in files if file.lower().endswith(('.f95', '.c')) and file not in exclude_sources] # (from http://stackoverflow.com/questions/14320220/ # testing-python-c-libraries-get-build-path)): build_lib_dir = "{dirname}.{platform}-{version[0]}.{version[1]}" dirparams = {'dirname': 'temp', 'platform': sysconfig.get_platform(), 'version': sys.version_info} libdir = os.path.join('build', build_lib_dir.format(**dirparams)) print('searching SHTOOLS in:', libdir) # Fortran compilation config.add_library('SHTOOLS', sources=sources, **kwargs) # SHTOOLS kwargs['libraries'].extend(['SHTOOLS']) kwargs['include_dirs'].extend([libdir]) kwargs['library_dirs'].extend([libdir]) # FFTW info fftw_info = get_info('fftw', notfound_action=2) dict_append(kwargs, **fftw_info) if sys.platform != 'win32': kwargs['libraries'].extend(['m']) # BLAS / Lapack info lapack_info = get_info('lapack_opt', notfound_action=2) blas_info = get_info('blas_opt', notfound_action=2) dict_append(kwargs, **blas_info) dict_append(kwargs, **lapack_info) config.add_extension('pyshtools._SHTOOLS', sources=['src/pyshtools.pyf', 'src/PythonWrapper.f95'], **kwargs) return config
python
def configuration(parent_package='', top_path=None): """Configure all packages that need to be built.""" config = Configuration('', parent_package, top_path) F95FLAGS = get_compiler_flags() kwargs = { 'libraries': [], 'include_dirs': [], 'library_dirs': [], } kwargs['extra_compile_args'] = F95FLAGS kwargs['f2py_options'] = ['--quiet'] # numpy.distutils.fcompiler.FCompiler doesn't support .F95 extension compiler = FCompiler(get_default_fcompiler()) compiler.src_extensions.append('.F95') compiler.language_map['.F95'] = 'f90' # collect all Fortran sources files = os.listdir('src') exclude_sources = ['PlanetsConstants.f95', 'PythonWrapper.f95'] sources = [os.path.join('src', file) for file in files if file.lower().endswith(('.f95', '.c')) and file not in exclude_sources] # (from http://stackoverflow.com/questions/14320220/ # testing-python-c-libraries-get-build-path)): build_lib_dir = "{dirname}.{platform}-{version[0]}.{version[1]}" dirparams = {'dirname': 'temp', 'platform': sysconfig.get_platform(), 'version': sys.version_info} libdir = os.path.join('build', build_lib_dir.format(**dirparams)) print('searching SHTOOLS in:', libdir) # Fortran compilation config.add_library('SHTOOLS', sources=sources, **kwargs) # SHTOOLS kwargs['libraries'].extend(['SHTOOLS']) kwargs['include_dirs'].extend([libdir]) kwargs['library_dirs'].extend([libdir]) # FFTW info fftw_info = get_info('fftw', notfound_action=2) dict_append(kwargs, **fftw_info) if sys.platform != 'win32': kwargs['libraries'].extend(['m']) # BLAS / Lapack info lapack_info = get_info('lapack_opt', notfound_action=2) blas_info = get_info('blas_opt', notfound_action=2) dict_append(kwargs, **blas_info) dict_append(kwargs, **lapack_info) config.add_extension('pyshtools._SHTOOLS', sources=['src/pyshtools.pyf', 'src/PythonWrapper.f95'], **kwargs) return config
[ "def", "configuration", "(", "parent_package", "=", "''", ",", "top_path", "=", "None", ")", ":", "config", "=", "Configuration", "(", "''", ",", "parent_package", ",", "top_path", ")", "F95FLAGS", "=", "get_compiler_flags", "(", ")", "kwargs", "=", "{", "...
Configure all packages that need to be built.
[ "Configure", "all", "packages", "that", "need", "to", "be", "built", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/setup.py#L202-L265
train
203,865
SHTOOLS/SHTOOLS
pyshtools/shio/icgem.py
_time_variable_part
def _time_variable_part(epoch, ref_epoch, trnd, periodic): """ Return sum of the time-variable part of the coefficients The formula is: G(t) = G(t0) + trnd*(t-t0) + asin1*sin(2pi/p1 * (t-t0)) + acos1*cos(2pi/p1 * (t-t0)) + asin2*sin(2pi/p2 * (t-t0)) + acos2*cos(2pi/p2 * (t-t0)) This function computes all terms after G(t0). """ delta_t = epoch - ref_epoch trend = trnd * delta_t periodic_sum = _np.zeros_like(trnd) for period in periodic: for trifunc in periodic[period]: coeffs = periodic[period][trifunc] if trifunc == 'acos': periodic_sum += coeffs * _np.cos(2 * _np.pi / period * delta_t) elif trifunc == 'asin': periodic_sum += coeffs * _np.sin(2 * _np.pi / period * delta_t) return trend + periodic_sum
python
def _time_variable_part(epoch, ref_epoch, trnd, periodic): """ Return sum of the time-variable part of the coefficients The formula is: G(t) = G(t0) + trnd*(t-t0) + asin1*sin(2pi/p1 * (t-t0)) + acos1*cos(2pi/p1 * (t-t0)) + asin2*sin(2pi/p2 * (t-t0)) + acos2*cos(2pi/p2 * (t-t0)) This function computes all terms after G(t0). """ delta_t = epoch - ref_epoch trend = trnd * delta_t periodic_sum = _np.zeros_like(trnd) for period in periodic: for trifunc in periodic[period]: coeffs = periodic[period][trifunc] if trifunc == 'acos': periodic_sum += coeffs * _np.cos(2 * _np.pi / period * delta_t) elif trifunc == 'asin': periodic_sum += coeffs * _np.sin(2 * _np.pi / period * delta_t) return trend + periodic_sum
[ "def", "_time_variable_part", "(", "epoch", ",", "ref_epoch", ",", "trnd", ",", "periodic", ")", ":", "delta_t", "=", "epoch", "-", "ref_epoch", "trend", "=", "trnd", "*", "delta_t", "periodic_sum", "=", "_np", ".", "zeros_like", "(", "trnd", ")", "for", ...
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).
[ "Return", "sum", "of", "the", "time", "-", "variable", "part", "of", "the", "coefficients" ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shio/icgem.py#L13-L34
train
203,866
SHTOOLS/SHTOOLS
src/create_wrapper.py
modify_subroutine
def modify_subroutine(subroutine): """loops through variables of a subroutine and modifies them""" # print('\n----',subroutine['name'],'----') #-- use original function from shtools: subroutine['use'] = {'shtools': {'map': {subroutine['name']: subroutine['name']}, 'only': 1}} #-- loop through variables: for varname, varattribs in subroutine['vars'].items(): #-- prefix function return variables with 'py' if varname == subroutine['name']: subroutine['vars']['py' + varname] = subroutine['vars'].pop(varname) varname = 'py' + varname # print('prefix added:',varname) #-- change assumed to explicit: if has_assumed_shape(varattribs): make_explicit(subroutine, varname, varattribs) # print('assumed shape variable modified to:',varname,varattribs['dimension']) #-- add py prefix to subroutine: subroutine['name'] = 'py' + subroutine['name']
python
def modify_subroutine(subroutine): """loops through variables of a subroutine and modifies them""" # print('\n----',subroutine['name'],'----') #-- use original function from shtools: subroutine['use'] = {'shtools': {'map': {subroutine['name']: subroutine['name']}, 'only': 1}} #-- loop through variables: for varname, varattribs in subroutine['vars'].items(): #-- prefix function return variables with 'py' if varname == subroutine['name']: subroutine['vars']['py' + varname] = subroutine['vars'].pop(varname) varname = 'py' + varname # print('prefix added:',varname) #-- change assumed to explicit: if has_assumed_shape(varattribs): make_explicit(subroutine, varname, varattribs) # print('assumed shape variable modified to:',varname,varattribs['dimension']) #-- add py prefix to subroutine: subroutine['name'] = 'py' + subroutine['name']
[ "def", "modify_subroutine", "(", "subroutine", ")", ":", "# print('\\n----',subroutine['name'],'----')", "#-- use original function from shtools:", "subroutine", "[", "'use'", "]", "=", "{", "'shtools'", ":", "{", "'map'", ":", "{", "subroutine", "[", "'name'", "]", "...
loops through variables of a subroutine and modifies them
[ "loops", "through", "variables", "of", "a", "subroutine", "and", "modifies", "them" ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/src/create_wrapper.py#L102-L122
train
203,867
SHTOOLS/SHTOOLS
pyshtools/utils/figstyle.py
figstyle
def figstyle(rel_width=0.75, screen_dpi=114, aspect_ratio=4/3, max_width=7.48031): """ Set matplotlib parameters for creating publication quality graphics. Usage ----- figstyle([rel_width, screen_dpi, aspect_ratio, max_width]) Parameters ---------- rel_width : float, optional, default = 0.75 The relative width of the plot (from 0 to 1) wih respect to max_width. screen_dpi : int, optional, default = 114 The screen resolution of the display in dpi, which determines the size of the plot on the display. aspect_ratio : float, optional, default = 4/3 The aspect ratio of the plot. max_width : float, optional, default = 7.48031 The maximum width of the usable area of a journal page in inches. Description ----------- This function sets a variety of matplotlib parameters for creating publication quality graphics. The default parameters are tailored to AGU/Wiley-Blackwell journals that accept relative widths of 0.5, 0.75, and 1. To reset the maplotlib parameters to their default values, use matplotlib.pyplot.style.use('default') """ width_x = max_width * rel_width width_y = max_width * rel_width / aspect_ratio shtools = { # fonts 'font.size': 10, 'font.family': 'sans-serif', 'font.sans-serif': ['Myriad Pro', 'DejaVu Sans', 'Bitstream Vera Sans', 'Verdana', 'Arial', 'Helvetica'], 'axes.titlesize': 10, 'axes.labelsize': 10, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 9, 'text.usetex': False, 'axes.formatter.limits': (-3, 3), # figure 'figure.dpi': screen_dpi, 'figure.figsize': (width_x, width_y), # line and tick widths 'axes.linewidth': 1, 'lines.linewidth': 1.5, 'xtick.major.width': 0.6, 'ytick.major.width': 0.6, 'xtick.minor.width': 0.6, 'xtick.minor.width': 0.6, 'xtick.top': True, 'ytick.right': True, # grids 'grid.linewidth': 0.3, 'grid.color': 'k', 'grid.linestyle': '-', # legends 'legend.framealpha': 1., 'legend.edgecolor': 'k', # images 'image.lut': 65536, # 16 bit # savefig 'savefig.bbox': 'tight', 'savefig.pad_inches': 0.02, 'savefig.dpi': 600, 'savefig.format': 'pdf' } _plt.style.use([shtools])
python
def figstyle(rel_width=0.75, screen_dpi=114, aspect_ratio=4/3, max_width=7.48031): """ Set matplotlib parameters for creating publication quality graphics. Usage ----- figstyle([rel_width, screen_dpi, aspect_ratio, max_width]) Parameters ---------- rel_width : float, optional, default = 0.75 The relative width of the plot (from 0 to 1) wih respect to max_width. screen_dpi : int, optional, default = 114 The screen resolution of the display in dpi, which determines the size of the plot on the display. aspect_ratio : float, optional, default = 4/3 The aspect ratio of the plot. max_width : float, optional, default = 7.48031 The maximum width of the usable area of a journal page in inches. Description ----------- This function sets a variety of matplotlib parameters for creating publication quality graphics. The default parameters are tailored to AGU/Wiley-Blackwell journals that accept relative widths of 0.5, 0.75, and 1. To reset the maplotlib parameters to their default values, use matplotlib.pyplot.style.use('default') """ width_x = max_width * rel_width width_y = max_width * rel_width / aspect_ratio shtools = { # fonts 'font.size': 10, 'font.family': 'sans-serif', 'font.sans-serif': ['Myriad Pro', 'DejaVu Sans', 'Bitstream Vera Sans', 'Verdana', 'Arial', 'Helvetica'], 'axes.titlesize': 10, 'axes.labelsize': 10, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 9, 'text.usetex': False, 'axes.formatter.limits': (-3, 3), # figure 'figure.dpi': screen_dpi, 'figure.figsize': (width_x, width_y), # line and tick widths 'axes.linewidth': 1, 'lines.linewidth': 1.5, 'xtick.major.width': 0.6, 'ytick.major.width': 0.6, 'xtick.minor.width': 0.6, 'xtick.minor.width': 0.6, 'xtick.top': True, 'ytick.right': True, # grids 'grid.linewidth': 0.3, 'grid.color': 'k', 'grid.linestyle': '-', # legends 'legend.framealpha': 1., 'legend.edgecolor': 'k', # images 'image.lut': 65536, # 16 bit # savefig 'savefig.bbox': 'tight', 'savefig.pad_inches': 0.02, 'savefig.dpi': 600, 'savefig.format': 'pdf' } _plt.style.use([shtools])
[ "def", "figstyle", "(", "rel_width", "=", "0.75", ",", "screen_dpi", "=", "114", ",", "aspect_ratio", "=", "4", "/", "3", ",", "max_width", "=", "7.48031", ")", ":", "width_x", "=", "max_width", "*", "rel_width", "width_y", "=", "max_width", "*", "rel_wi...
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')
[ "Set", "matplotlib", "parameters", "for", "creating", "publication", "quality", "graphics", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/utils/figstyle.py#L7-L82
train
203,868
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHCoeffs.from_zeros
def from_zeros(self, lmax, kind='real', normalization='4pi', csphase=1): """ Initialize class with spherical harmonic coefficients set to zero from degree 0 to lmax. Usage ----- x = SHCoeffs.from_zeros(lmax, [normalization, csphase]) Returns ------- x : SHCoeffs class instance. Parameters ---------- lmax : int The highest spherical harmonic degree l of the coefficients. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. kind : str, optional, default = 'real' 'real' or 'complex' spherical harmonic coefficients. """ if kind.lower() not in ('real', 'complex'): raise ValueError( "Kind must be 'real' or 'complex'. " + "Input value was {:s}." .format(repr(kind)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 nl = lmax + 1 if kind.lower() == 'real': coeffs = _np.zeros((2, nl, nl)) else: coeffs = _np.zeros((2, nl, nl), dtype=complex) for cls in self.__subclasses__(): if cls.istype(kind): return cls(coeffs, normalization=normalization.lower(), csphase=csphase)
python
def from_zeros(self, lmax, kind='real', normalization='4pi', csphase=1): """ Initialize class with spherical harmonic coefficients set to zero from degree 0 to lmax. Usage ----- x = SHCoeffs.from_zeros(lmax, [normalization, csphase]) Returns ------- x : SHCoeffs class instance. Parameters ---------- lmax : int The highest spherical harmonic degree l of the coefficients. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. kind : str, optional, default = 'real' 'real' or 'complex' spherical harmonic coefficients. """ if kind.lower() not in ('real', 'complex'): raise ValueError( "Kind must be 'real' or 'complex'. " + "Input value was {:s}." .format(repr(kind)) ) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " + "are stable only for degrees less than or equal " + "to 85. lmax for the coefficients will be set to " + "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 nl = lmax + 1 if kind.lower() == 'real': coeffs = _np.zeros((2, nl, nl)) else: coeffs = _np.zeros((2, nl, nl), dtype=complex) for cls in self.__subclasses__(): if cls.istype(kind): return cls(coeffs, normalization=normalization.lower(), csphase=csphase)
[ "def", "from_zeros", "(", "self", ",", "lmax", ",", "kind", "=", "'real'", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ")", ":", "if", "kind", ".", "lower", "(", ")", "not", "in", "(", "'real'", ",", "'complex'", ")", ":", "raise"...
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.
[ "Initialize", "class", "with", "spherical", "harmonic", "coefficients", "set", "to", "zero", "from", "degree", "0", "to", "lmax", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L111-L175
train
203,869
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHCoeffs.to_file
def to_file(self, filename, format='shtools', header=None, **kwargs): """ Save raw spherical harmonic coefficients to a file. Usage ----- x.to_file(filename, [format='shtools', header]) x.to_file(filename, [format='npy', **kwargs]) Parameters ---------- filename : str Name of the output file. format : str, optional, default = 'shtools' 'shtools' or 'npy'. See method from_file() for more information. header : str, optional, default = None A header string written to an 'shtools'-formatted file directly before the spherical harmonic coefficients. **kwargs : keyword argument list, optional for format = 'npy' Keyword arguments of numpy.save(). Description ----------- If format='shtools', the coefficients will be written to an ascii formatted file. The first line of the file is an optional user provided header line, and the spherical harmonic coefficients are then listed, with increasing degree and order, with the format l, m, coeffs[0, l, m], coeffs[1, l, m] where l and m are the spherical harmonic degree and order, respectively. If format='npy', the spherical harmonic coefficients will be saved to a binary numpy 'npy' file using numpy.save(). """ if format is 'shtools': with open(filename, mode='w') as file: if header is not None: file.write(header + '\n') for l in range(self.lmax+1): for m in range(l+1): file.write('{:d}, {:d}, {:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m])) elif format is 'npy': _np.save(filename, self.coeffs, **kwargs) else: raise NotImplementedError( 'format={:s} not implemented'.format(repr(format)))
python
def to_file(self, filename, format='shtools', header=None, **kwargs): """ Save raw spherical harmonic coefficients to a file. Usage ----- x.to_file(filename, [format='shtools', header]) x.to_file(filename, [format='npy', **kwargs]) Parameters ---------- filename : str Name of the output file. format : str, optional, default = 'shtools' 'shtools' or 'npy'. See method from_file() for more information. header : str, optional, default = None A header string written to an 'shtools'-formatted file directly before the spherical harmonic coefficients. **kwargs : keyword argument list, optional for format = 'npy' Keyword arguments of numpy.save(). Description ----------- If format='shtools', the coefficients will be written to an ascii formatted file. The first line of the file is an optional user provided header line, and the spherical harmonic coefficients are then listed, with increasing degree and order, with the format l, m, coeffs[0, l, m], coeffs[1, l, m] where l and m are the spherical harmonic degree and order, respectively. If format='npy', the spherical harmonic coefficients will be saved to a binary numpy 'npy' file using numpy.save(). """ if format is 'shtools': with open(filename, mode='w') as file: if header is not None: file.write(header + '\n') for l in range(self.lmax+1): for m in range(l+1): file.write('{:d}, {:d}, {:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m])) elif format is 'npy': _np.save(filename, self.coeffs, **kwargs) else: raise NotImplementedError( 'format={:s} not implemented'.format(repr(format)))
[ "def", "to_file", "(", "self", ",", "filename", ",", "format", "=", "'shtools'", ",", "header", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "format", "is", "'shtools'", ":", "with", "open", "(", "filename", ",", "mode", "=", "'w'", ")", "...
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().
[ "Save", "raw", "spherical", "harmonic", "coefficients", "to", "a", "file", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L543-L592
train
203,870
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHCoeffs.to_array
def to_array(self, normalization=None, csphase=None, lmax=None): """ Return spherical harmonic coefficients as a numpy array. Usage ----- coeffs = x.to_array([normalization, csphase, lmax]) Returns ------- coeffs : ndarry, shape (2, lmax+1, lmax+1) numpy ndarray of the spherical harmonic coefficients. Parameters ---------- normalization : str, optional, default = x.normalization Normalization of the output coefficients: '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. If lmax is greater than x.lmax, the array will be zero padded. Description ----------- This method will return an array of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention, and a different maximum spherical harmonic degree. If the maximum degree is smaller than the maximum degree of the class instance, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the class instance, the output array will be zero padded. """ if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax coeffs = _convert(self.coeffs, normalization_in=self.normalization, normalization_out=normalization, csphase_in=self.csphase, csphase_out=csphase, lmax=lmax) return coeffs
python
def to_array(self, normalization=None, csphase=None, lmax=None): """ Return spherical harmonic coefficients as a numpy array. Usage ----- coeffs = x.to_array([normalization, csphase, lmax]) Returns ------- coeffs : ndarry, shape (2, lmax+1, lmax+1) numpy ndarray of the spherical harmonic coefficients. Parameters ---------- normalization : str, optional, default = x.normalization Normalization of the output coefficients: '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. If lmax is greater than x.lmax, the array will be zero padded. Description ----------- This method will return an array of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention, and a different maximum spherical harmonic degree. If the maximum degree is smaller than the maximum degree of the class instance, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the class instance, the output array will be zero padded. """ if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax coeffs = _convert(self.coeffs, normalization_in=self.normalization, normalization_out=normalization, csphase_in=self.csphase, csphase_out=csphase, lmax=lmax) return coeffs
[ "def", "to_array", "(", "self", ",", "normalization", "=", "None", ",", "csphase", "=", "None", ",", "lmax", "=", "None", ")", ":", "if", "normalization", "is", "None", ":", "normalization", "=", "self", ".", "normalization", "if", "csphase", "is", "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.
[ "Return", "spherical", "harmonic", "coefficients", "as", "a", "numpy", "array", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L594-L643
train
203,871
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHCoeffs.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. """ 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
python
def volume(self, lmax=None): """ If the function is the real shape of an object, calculate the volume of the body. Usage ----- volume = x.volume([lmax]) Returns ------- volume : float The volume of the object. Parameters ---------- lmax : int, optional, default = x.lmax The maximum spherical harmonic degree to use when calculating the volume. Description ----------- If the function is the real shape of an object, this method will calculate the volume of the body exactly by integration. This routine raises the function to the nth power, with n from 1 to 3, and calculates the spherical harmonic degree and order 0 term. To avoid aliases, the function is first expand on a grid that can resolve spherical harmonic degrees up to 3*lmax. """ if self.coeffs[0, 0, 0] == 0: raise ValueError('The volume of the object can not be calculated ' 'when the degree and order 0 term is equal to ' 'zero.') if self.kind == 'complex': raise ValueError('The volume of the object can not be calculated ' 'for complex functions.') if lmax is None: lmax = self.lmax r0 = self.coeffs[0, 0, 0] grid = self.expand(lmax=3*lmax) - r0 h200 = (grid**2).expand(lmax_calc=0).coeffs[0, 0, 0] h300 = (grid**3).expand(lmax_calc=0).coeffs[0, 0, 0] volume = 4 * _np.pi / 3 * (h300 + 3 * r0 * h200 + r0**3) return volume
[ "def", "volume", "(", "self", ",", "lmax", "=", "None", ")", ":", "if", "self", ".", "coeffs", "[", "0", ",", "0", ",", "0", "]", "==", "0", ":", "raise", "ValueError", "(", "'The volume of the object can not be calculated '", "'when the degree and order 0 ter...
If the function is the real shape of an object, calculate the volume of the body. Usage ----- volume = x.volume([lmax]) Returns ------- volume : float The volume of the object. Parameters ---------- lmax : int, optional, default = x.lmax The maximum spherical harmonic degree to use when calculating the volume. Description ----------- If the function is the real shape of an object, this method will calculate the volume of the body exactly by integration. This routine raises the function to the nth power, with n from 1 to 3, and calculates the spherical harmonic degree and order 0 term. To avoid aliases, the function is first expand on a grid that can resolve spherical harmonic degrees up to 3*lmax.
[ "If", "the", "function", "is", "the", "real", "shape", "of", "an", "object", "calculate", "the", "volume", "of", "the", "body", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L970-L1017
train
203,872
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHCoeffs.rotate
def rotate(self, alpha, beta, gamma, degrees=True, convention='y', body=False, dj_matrix=None): """ Rotate either the coordinate system used to express the spherical harmonic coefficients or the physical body, and return a new class instance. Usage ----- x_rotated = x.rotate(alpha, beta, gamma, [degrees, convention, body, dj_matrix]) Returns ------- x_rotated : SHCoeffs class instance Parameters ---------- alpha, beta, gamma : float The three Euler rotation angles in degrees. degrees : bool, optional, default = True True if the Euler angles are in degrees, False if they are in radians. convention : str, optional, default = 'y' The convention used for the rotation of the second angle, which can be either 'x' or 'y' for a rotation about the x or y axes, respectively. body : bool, optional, default = False If true, rotate the physical body and not the coordinate system. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. Description ----------- This method will take the spherical harmonic coefficients of a function, rotate the coordinate frame by the three Euler anlges, and output the spherical harmonic coefficients of the new function. If the optional parameter body is set to True, then the physical body will be rotated instead of the coordinate system. The rotation of a coordinate system or body can be viewed in two complementary ways involving three successive rotations. Both methods have the same initial and final configurations, and the angles listed in both schemes are the same. Scheme A: (I) Rotation about the z axis by alpha. (II) Rotation about the new y axis by beta. (III) Rotation about the new z axis by gamma. Scheme B: (I) Rotation about the z axis by gamma. (II) Rotation about the initial y axis by beta. (III) Rotation about the initial z axis by alpha. Here, the 'y convention' is employed, where the second rotation is with respect to the y axis. When using the 'x convention', the second rotation is instead with respect to the x axis. The relation between the Euler angles in the x and y conventions is given by alpha_y=alpha_x-pi/2, beta_y=beta_x, and gamma_y=gamma_x+pi/2. To perform the inverse transform associated with the three angles (alpha, beta, gamma), one would perform an additional rotation using the angles (-gamma, -beta, -alpha). The rotations can be viewed either as a rotation of the coordinate system or the physical body. To rotate the physical body without rotation of the coordinate system, set the optional parameter body to True. This rotation is accomplished by performing the inverse rotation using the angles (-gamma, -beta, -alpha). """ if type(convention) != str: raise ValueError('convention must be a string. ' + 'Input type was {:s}' .format(str(type(convention)))) if convention.lower() not in ('x', 'y'): raise ValueError( "convention must be either 'x' or 'y'. " + "Provided value was {:s}".format(repr(convention)) ) if convention is 'y': if body is True: angles = _np.array([-gamma, -beta, -alpha]) else: angles = _np.array([alpha, beta, gamma]) elif convention is 'x': if body is True: angles = _np.array([-gamma - _np.pi/2, -beta, -alpha + _np.pi/2]) else: angles = _np.array([alpha - _np.pi/2, beta, gamma + _np.pi/2]) if degrees: angles = _np.radians(angles) if self.lmax > 1200: _warnings.warn("The rotate() method is accurate only to about" + " spherical harmonic degree 1200. " + "lmax = {:d}".format(self.lmax), category=RuntimeWarning) rot = self._rotate(angles, dj_matrix) return rot
python
def rotate(self, alpha, beta, gamma, degrees=True, convention='y', body=False, dj_matrix=None): """ Rotate either the coordinate system used to express the spherical harmonic coefficients or the physical body, and return a new class instance. Usage ----- x_rotated = x.rotate(alpha, beta, gamma, [degrees, convention, body, dj_matrix]) Returns ------- x_rotated : SHCoeffs class instance Parameters ---------- alpha, beta, gamma : float The three Euler rotation angles in degrees. degrees : bool, optional, default = True True if the Euler angles are in degrees, False if they are in radians. convention : str, optional, default = 'y' The convention used for the rotation of the second angle, which can be either 'x' or 'y' for a rotation about the x or y axes, respectively. body : bool, optional, default = False If true, rotate the physical body and not the coordinate system. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. Description ----------- This method will take the spherical harmonic coefficients of a function, rotate the coordinate frame by the three Euler anlges, and output the spherical harmonic coefficients of the new function. If the optional parameter body is set to True, then the physical body will be rotated instead of the coordinate system. The rotation of a coordinate system or body can be viewed in two complementary ways involving three successive rotations. Both methods have the same initial and final configurations, and the angles listed in both schemes are the same. Scheme A: (I) Rotation about the z axis by alpha. (II) Rotation about the new y axis by beta. (III) Rotation about the new z axis by gamma. Scheme B: (I) Rotation about the z axis by gamma. (II) Rotation about the initial y axis by beta. (III) Rotation about the initial z axis by alpha. Here, the 'y convention' is employed, where the second rotation is with respect to the y axis. When using the 'x convention', the second rotation is instead with respect to the x axis. The relation between the Euler angles in the x and y conventions is given by alpha_y=alpha_x-pi/2, beta_y=beta_x, and gamma_y=gamma_x+pi/2. To perform the inverse transform associated with the three angles (alpha, beta, gamma), one would perform an additional rotation using the angles (-gamma, -beta, -alpha). The rotations can be viewed either as a rotation of the coordinate system or the physical body. To rotate the physical body without rotation of the coordinate system, set the optional parameter body to True. This rotation is accomplished by performing the inverse rotation using the angles (-gamma, -beta, -alpha). """ if type(convention) != str: raise ValueError('convention must be a string. ' + 'Input type was {:s}' .format(str(type(convention)))) if convention.lower() not in ('x', 'y'): raise ValueError( "convention must be either 'x' or 'y'. " + "Provided value was {:s}".format(repr(convention)) ) if convention is 'y': if body is True: angles = _np.array([-gamma, -beta, -alpha]) else: angles = _np.array([alpha, beta, gamma]) elif convention is 'x': if body is True: angles = _np.array([-gamma - _np.pi/2, -beta, -alpha + _np.pi/2]) else: angles = _np.array([alpha - _np.pi/2, beta, gamma + _np.pi/2]) if degrees: angles = _np.radians(angles) if self.lmax > 1200: _warnings.warn("The rotate() method is accurate only to about" + " spherical harmonic degree 1200. " + "lmax = {:d}".format(self.lmax), category=RuntimeWarning) rot = self._rotate(angles, dj_matrix) return rot
[ "def", "rotate", "(", "self", ",", "alpha", ",", "beta", ",", "gamma", ",", "degrees", "=", "True", ",", "convention", "=", "'y'", ",", "body", "=", "False", ",", "dj_matrix", "=", "None", ")", ":", "if", "type", "(", "convention", ")", "!=", "str"...
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).
[ "Rotate", "either", "the", "coordinate", "system", "used", "to", "express", "the", "spherical", "harmonic", "coefficients", "or", "the", "physical", "body", "and", "return", "a", "new", "class", "instance", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L1020-L1127
train
203,873
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHCoeffs.convert
def convert(self, normalization=None, csphase=None, lmax=None, kind=None, check=True): """ Return a SHCoeffs class instance with a different normalization convention. Usage ----- clm = x.convert([normalization, csphase, lmax, kind, check]) Returns ------- clm : SHCoeffs class instance Parameters ---------- normalization : str, optional, default = x.normalization Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention for the output class: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. kind : str, optional, default = clm.kind 'real' or 'complex' spherical harmonic coefficients for the output class. check : bool, optional, default = True When converting complex coefficients to real coefficients, if True, check if function is entirely real. Description ----------- This method will return a new class instance of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention. The coefficients can be converted between real and complex form, and a different maximum spherical harmonic degree of the output coefficients can be specified. If this maximum degree is smaller than the maximum degree of the original class, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the original class, the coefficients of the new class will be zero padded. """ if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax if kind is None: kind = self.kind # check argument consistency if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Provided value was {:s}" .format(repr(normalization))) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase))) if (kind != self.kind): if (kind == 'complex'): temp = self._make_complex() else: temp = self._make_real(check=check) coeffs = temp.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) else: coeffs = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHCoeffs.from_array(coeffs, normalization=normalization.lower(), csphase=csphase, copy=False)
python
def convert(self, normalization=None, csphase=None, lmax=None, kind=None, check=True): """ Return a SHCoeffs class instance with a different normalization convention. Usage ----- clm = x.convert([normalization, csphase, lmax, kind, check]) Returns ------- clm : SHCoeffs class instance Parameters ---------- normalization : str, optional, default = x.normalization Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = x.csphase Condon-Shortley phase convention for the output class: 1 to exclude the phase factor, or -1 to include it. lmax : int, optional, default = x.lmax Maximum spherical harmonic degree to output. kind : str, optional, default = clm.kind 'real' or 'complex' spherical harmonic coefficients for the output class. check : bool, optional, default = True When converting complex coefficients to real coefficients, if True, check if function is entirely real. Description ----------- This method will return a new class instance of the spherical harmonic coefficients using a different normalization and Condon-Shortley phase convention. The coefficients can be converted between real and complex form, and a different maximum spherical harmonic degree of the output coefficients can be specified. If this maximum degree is smaller than the maximum degree of the original class, the coefficients will be truncated. Conversely, if this degree is larger than the maximum degree of the original class, the coefficients of the new class will be zero padded. """ if normalization is None: normalization = self.normalization if csphase is None: csphase = self.csphase if lmax is None: lmax = self.lmax if kind is None: kind = self.kind # check argument consistency if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Provided value was {:s}" .format(repr(normalization))) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be 1 or -1. Input value was {:s}" .format(repr(csphase))) if (kind != self.kind): if (kind == 'complex'): temp = self._make_complex() else: temp = self._make_real(check=check) coeffs = temp.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) else: coeffs = self.to_array(normalization=normalization.lower(), csphase=csphase, lmax=lmax) return SHCoeffs.from_array(coeffs, normalization=normalization.lower(), csphase=csphase, copy=False)
[ "def", "convert", "(", "self", ",", "normalization", "=", "None", ",", "csphase", "=", "None", ",", "lmax", "=", "None", ",", "kind", "=", "None", ",", "check", "=", "True", ")", ":", "if", "normalization", "is", "None", ":", "normalization", "=", "s...
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.
[ "Return", "a", "SHCoeffs", "class", "instance", "with", "a", "different", "normalization", "convention", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L1129-L1210
train
203,874
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHCoeffs.expand
def expand(self, grid='DH', lat=None, colat=None, lon=None, degrees=True, zeros=None, lmax=None, lmax_calc=None): """ Evaluate the spherical harmonic coefficients either on a global grid or for a list of coordinates. Usage ----- f = x.expand([grid, lmax, lmax_calc, zeros]) g = x.expand(lat=lat, lon=lon, [lmax_calc, degrees]) g = x.expand(colat=colat, lon=lon, [lmax_calc, degrees]) Returns ------- f : SHGrid class instance g : float, ndarray, or list Parameters ---------- lat : int, float, ndarray, or list, optional, default = None Latitude coordinates where the function is to be evaluated. colat : int, float, ndarray, or list, optional, default = None Colatitude coordinates where the function is to be evaluated. lon : int, float, ndarray, or list, optional, default = None Longitude coordinates where the function is to be evaluated. degrees : bool, optional, default = True True if lat, colat and lon are in degrees, False if in radians. grid : str, optional, default = 'DH' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2' for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a Gauss-Legendre quadrature grid. lmax : int, optional, default = x.lmax The maximum spherical harmonic degree, which determines the grid spacing of the output grid. lmax_calc : int, optional, default = x.lmax The maximum spherical harmonic degree to use when evaluating the function. zeros : ndarray, optional, default = None The cos(colatitude) nodes used in the Gauss-Legendre Quadrature grids. Description ----------- This method either (1) evaluates the spherical harmonic coefficients on a global grid and returns an SHGrid class instance, or (2) evaluates the spherical harmonic coefficients for a list of (co)latitude and longitude coordinates. For the first case, the grid type is defined by the optional parameter grid, which can be 'DH', 'DH2' or 'GLQ'.For the second case, the optional parameters lon and either colat or lat must be provided. """ if lat is not None and colat is not None: raise ValueError('lat and colat can not both be specified.') if lat is not None and lon is not None: if lmax_calc is None: lmax_calc = self.lmax values = self._expand_coord(lat=lat, lon=lon, degrees=degrees, lmax_calc=lmax_calc) return values if colat is not None and lon is not None: if lmax_calc is None: lmax_calc = self.lmax if type(colat) is list: lat = list(map(lambda x: 90 - x, colat)) else: lat = 90 - colat values = self._expand_coord(lat=lat, lon=lon, degrees=degrees, lmax_calc=lmax_calc) return values else: if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() in ('DH', 'DH1'): gridout = self._expandDH(sampling=1, lmax=lmax, lmax_calc=lmax_calc) elif grid.upper() == 'DH2': gridout = self._expandDH(sampling=2, lmax=lmax, lmax_calc=lmax_calc) elif grid.upper() == 'GLQ': gridout = self._expandGLQ(zeros=zeros, lmax=lmax, lmax_calc=lmax_calc) else: raise ValueError( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}".format(repr(grid))) return gridout
python
def expand(self, grid='DH', lat=None, colat=None, lon=None, degrees=True, zeros=None, lmax=None, lmax_calc=None): """ Evaluate the spherical harmonic coefficients either on a global grid or for a list of coordinates. Usage ----- f = x.expand([grid, lmax, lmax_calc, zeros]) g = x.expand(lat=lat, lon=lon, [lmax_calc, degrees]) g = x.expand(colat=colat, lon=lon, [lmax_calc, degrees]) Returns ------- f : SHGrid class instance g : float, ndarray, or list Parameters ---------- lat : int, float, ndarray, or list, optional, default = None Latitude coordinates where the function is to be evaluated. colat : int, float, ndarray, or list, optional, default = None Colatitude coordinates where the function is to be evaluated. lon : int, float, ndarray, or list, optional, default = None Longitude coordinates where the function is to be evaluated. degrees : bool, optional, default = True True if lat, colat and lon are in degrees, False if in radians. grid : str, optional, default = 'DH' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2' for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a Gauss-Legendre quadrature grid. lmax : int, optional, default = x.lmax The maximum spherical harmonic degree, which determines the grid spacing of the output grid. lmax_calc : int, optional, default = x.lmax The maximum spherical harmonic degree to use when evaluating the function. zeros : ndarray, optional, default = None The cos(colatitude) nodes used in the Gauss-Legendre Quadrature grids. Description ----------- This method either (1) evaluates the spherical harmonic coefficients on a global grid and returns an SHGrid class instance, or (2) evaluates the spherical harmonic coefficients for a list of (co)latitude and longitude coordinates. For the first case, the grid type is defined by the optional parameter grid, which can be 'DH', 'DH2' or 'GLQ'.For the second case, the optional parameters lon and either colat or lat must be provided. """ if lat is not None and colat is not None: raise ValueError('lat and colat can not both be specified.') if lat is not None and lon is not None: if lmax_calc is None: lmax_calc = self.lmax values = self._expand_coord(lat=lat, lon=lon, degrees=degrees, lmax_calc=lmax_calc) return values if colat is not None and lon is not None: if lmax_calc is None: lmax_calc = self.lmax if type(colat) is list: lat = list(map(lambda x: 90 - x, colat)) else: lat = 90 - colat values = self._expand_coord(lat=lat, lon=lon, degrees=degrees, lmax_calc=lmax_calc) return values else: if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() in ('DH', 'DH1'): gridout = self._expandDH(sampling=1, lmax=lmax, lmax_calc=lmax_calc) elif grid.upper() == 'DH2': gridout = self._expandDH(sampling=2, lmax=lmax, lmax_calc=lmax_calc) elif grid.upper() == 'GLQ': gridout = self._expandGLQ(zeros=zeros, lmax=lmax, lmax_calc=lmax_calc) else: raise ValueError( "grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " + "Input value was {:s}".format(repr(grid))) return gridout
[ "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.
[ "Evaluate", "the", "spherical", "harmonic", "coefficients", "either", "on", "a", "global", "grid", "or", "for", "a", "list", "of", "coordinates", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L1248-L1348
train
203,875
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHRealCoeffs._make_complex
def _make_complex(self): """Convert the real SHCoeffs class to the complex class.""" rcomplex_coeffs = _shtools.SHrtoc(self.coeffs, convention=1, switchcs=0) # These coefficients are using real floats, and need to be # converted to complex form. complex_coeffs = _np.zeros((2, self.lmax+1, self.lmax+1), dtype='complex') complex_coeffs[0, :, :] = (rcomplex_coeffs[0, :, :] + 1j * rcomplex_coeffs[1, :, :]) complex_coeffs[1, :, :] = complex_coeffs[0, :, :].conjugate() for m in self.degrees(): if m % 2 == 1: complex_coeffs[1, :, m] = - complex_coeffs[1, :, m] # complex_coeffs is initialized in this function and can be # passed as reference return SHCoeffs.from_array(complex_coeffs, normalization=self.normalization, csphase=self.csphase, copy=False)
python
def _make_complex(self): """Convert the real SHCoeffs class to the complex class.""" rcomplex_coeffs = _shtools.SHrtoc(self.coeffs, convention=1, switchcs=0) # These coefficients are using real floats, and need to be # converted to complex form. complex_coeffs = _np.zeros((2, self.lmax+1, self.lmax+1), dtype='complex') complex_coeffs[0, :, :] = (rcomplex_coeffs[0, :, :] + 1j * rcomplex_coeffs[1, :, :]) complex_coeffs[1, :, :] = complex_coeffs[0, :, :].conjugate() for m in self.degrees(): if m % 2 == 1: complex_coeffs[1, :, m] = - complex_coeffs[1, :, m] # complex_coeffs is initialized in this function and can be # passed as reference return SHCoeffs.from_array(complex_coeffs, normalization=self.normalization, csphase=self.csphase, copy=False)
[ "def", "_make_complex", "(", "self", ")", ":", "rcomplex_coeffs", "=", "_shtools", ".", "SHrtoc", "(", "self", ".", "coeffs", ",", "convention", "=", "1", ",", "switchcs", "=", "0", ")", "# These coefficients are using real floats, and need to be", "# converted to c...
Convert the real SHCoeffs class to the complex class.
[ "Convert", "the", "real", "SHCoeffs", "class", "to", "the", "complex", "class", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L1729-L1749
train
203,876
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHRealCoeffs._expand_coord
def _expand_coord(self, lat, lon, lmax_calc, degrees): """Evaluate the function at the coordinates lat and lon.""" if self.normalization == '4pi': norm = 1 elif self.normalization == 'schmidt': norm = 2 elif self.normalization == 'unnorm': norm = 3 elif self.normalization == 'ortho': norm = 4 else: raise ValueError( "Normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Input value was {:s}" .format(repr(self.normalization))) if degrees is True: latin = lat lonin = lon else: latin = _np.rad2deg(lat) lonin = _np.rad2deg(lon) if type(lat) is not type(lon): raise ValueError('lat and lon must be of the same type. ' + 'Input types are {:s} and {:s}' .format(repr(type(lat)), repr(type(lon)))) if type(lat) is int or type(lat) is float or type(lat) is _np.float_: return _shtools.MakeGridPoint(self.coeffs, lat=latin, lon=lonin, lmax=lmax_calc, norm=norm, csphase=self.csphase) elif type(lat) is _np.ndarray: values = _np.empty_like(lat, dtype=float) for v, latitude, longitude in _np.nditer([values, latin, lonin], op_flags=['readwrite']): v[...] = _shtools.MakeGridPoint(self.coeffs, lat=latitude, lon=longitude, lmax=lmax_calc, norm=norm, csphase=self.csphase) return values elif type(lat) is list: values = [] for latitude, longitude in zip(latin, lonin): values.append( _shtools.MakeGridPoint(self.coeffs, lat=latitude, lon=longitude, lmax=lmax_calc, norm=norm, csphase=self.csphase)) return values else: raise ValueError('lat and lon must be either an int, float, ' + 'ndarray, or list. ' + 'Input types are {:s} and {:s}' .format(repr(type(lat)), repr(type(lon))))
python
def _expand_coord(self, lat, lon, lmax_calc, degrees): """Evaluate the function at the coordinates lat and lon.""" if self.normalization == '4pi': norm = 1 elif self.normalization == 'schmidt': norm = 2 elif self.normalization == 'unnorm': norm = 3 elif self.normalization == 'ortho': norm = 4 else: raise ValueError( "Normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Input value was {:s}" .format(repr(self.normalization))) if degrees is True: latin = lat lonin = lon else: latin = _np.rad2deg(lat) lonin = _np.rad2deg(lon) if type(lat) is not type(lon): raise ValueError('lat and lon must be of the same type. ' + 'Input types are {:s} and {:s}' .format(repr(type(lat)), repr(type(lon)))) if type(lat) is int or type(lat) is float or type(lat) is _np.float_: return _shtools.MakeGridPoint(self.coeffs, lat=latin, lon=lonin, lmax=lmax_calc, norm=norm, csphase=self.csphase) elif type(lat) is _np.ndarray: values = _np.empty_like(lat, dtype=float) for v, latitude, longitude in _np.nditer([values, latin, lonin], op_flags=['readwrite']): v[...] = _shtools.MakeGridPoint(self.coeffs, lat=latitude, lon=longitude, lmax=lmax_calc, norm=norm, csphase=self.csphase) return values elif type(lat) is list: values = [] for latitude, longitude in zip(latin, lonin): values.append( _shtools.MakeGridPoint(self.coeffs, lat=latitude, lon=longitude, lmax=lmax_calc, norm=norm, csphase=self.csphase)) return values else: raise ValueError('lat and lon must be either an int, float, ' + 'ndarray, or list. ' + 'Input types are {:s} and {:s}' .format(repr(type(lat)), repr(type(lon))))
[ "def", "_expand_coord", "(", "self", ",", "lat", ",", "lon", ",", "lmax_calc", ",", "degrees", ")", ":", "if", "self", ".", "normalization", "==", "'4pi'", ":", "norm", "=", "1", "elif", "self", ".", "normalization", "==", "'schmidt'", ":", "norm", "="...
Evaluate the function at the coordinates lat and lon.
[ "Evaluate", "the", "function", "at", "the", "coordinates", "lat", "and", "lon", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L1819-L1873
train
203,877
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHComplexCoeffs._make_real
def _make_real(self, check=True): """Convert the complex SHCoeffs class to the real class.""" # Test if the coefficients correspond to a real grid. # This is not very elegant, and the equality condition # is probably not robust to round off errors. if check: for l in self.degrees(): if self.coeffs[0, l, 0] != self.coeffs[0, l, 0].conjugate(): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = 0: {:e}' .format(l, self.coeffs[0, l, 0])) for m in _np.arange(1, l + 1): if m % 2 == 1: if (self.coeffs[0, l, m] != - self.coeffs[1, l, m].conjugate()): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = {:d}: {:e}, {:e}' .format( l, m, self.coeffs[0, l, 0], self.coeffs[1, l, 0])) else: if (self.coeffs[0, l, m] != self.coeffs[1, l, m].conjugate()): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = {:d}: {:e}, {:e}' .format( l, m, self.coeffs[0, l, 0], self.coeffs[1, l, 0])) coeffs_rc = _np.zeros((2, self.lmax + 1, self.lmax + 1)) coeffs_rc[0, :, :] = self.coeffs[0, :, :].real coeffs_rc[1, :, :] = self.coeffs[0, :, :].imag real_coeffs = _shtools.SHctor(coeffs_rc, convention=1, switchcs=0) return SHCoeffs.from_array(real_coeffs, normalization=self.normalization, csphase=self.csphase)
python
def _make_real(self, check=True): """Convert the complex SHCoeffs class to the real class.""" # Test if the coefficients correspond to a real grid. # This is not very elegant, and the equality condition # is probably not robust to round off errors. if check: for l in self.degrees(): if self.coeffs[0, l, 0] != self.coeffs[0, l, 0].conjugate(): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = 0: {:e}' .format(l, self.coeffs[0, l, 0])) for m in _np.arange(1, l + 1): if m % 2 == 1: if (self.coeffs[0, l, m] != - self.coeffs[1, l, m].conjugate()): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = {:d}: {:e}, {:e}' .format( l, m, self.coeffs[0, l, 0], self.coeffs[1, l, 0])) else: if (self.coeffs[0, l, m] != self.coeffs[1, l, m].conjugate()): raise RuntimeError('Complex coefficients do not ' + 'correspond to a real field. ' + 'l = {:d}, m = {:d}: {:e}, {:e}' .format( l, m, self.coeffs[0, l, 0], self.coeffs[1, l, 0])) coeffs_rc = _np.zeros((2, self.lmax + 1, self.lmax + 1)) coeffs_rc[0, :, :] = self.coeffs[0, :, :].real coeffs_rc[1, :, :] = self.coeffs[0, :, :].imag real_coeffs = _shtools.SHctor(coeffs_rc, convention=1, switchcs=0) return SHCoeffs.from_array(real_coeffs, normalization=self.normalization, csphase=self.csphase)
[ "def", "_make_real", "(", "self", ",", "check", "=", "True", ")", ":", "# Test if the coefficients correspond to a real grid.", "# This is not very elegant, and the equality condition", "# is probably not robust to round off errors.", "if", "check", ":", "for", "l", "in", "self...
Convert the complex SHCoeffs class to the real class.
[ "Convert", "the", "complex", "SHCoeffs", "class", "to", "the", "real", "class", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L1910-L1949
train
203,878
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHComplexCoeffs._expandGLQ
def _expandGLQ(self, zeros, lmax, lmax_calc): """Evaluate the coefficients on a Gauss-Legendre quadrature grid.""" if self.normalization == '4pi': norm = 1 elif self.normalization == 'schmidt': norm = 2 elif self.normalization == 'unnorm': norm = 3 elif self.normalization == 'ortho': norm = 4 else: raise ValueError( "Normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Input value was {:s}" .format(repr(self.normalization))) if zeros is None: zeros, weights = _shtools.SHGLQ(self.lmax) data = _shtools.MakeGridGLQC(self.coeffs, zeros, norm=norm, csphase=self.csphase, lmax=lmax, lmax_calc=lmax_calc) gridout = SHGrid.from_array(data, grid='GLQ', copy=False) return gridout
python
def _expandGLQ(self, zeros, lmax, lmax_calc): """Evaluate the coefficients on a Gauss-Legendre quadrature grid.""" if self.normalization == '4pi': norm = 1 elif self.normalization == 'schmidt': norm = 2 elif self.normalization == 'unnorm': norm = 3 elif self.normalization == 'ortho': norm = 4 else: raise ValueError( "Normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Input value was {:s}" .format(repr(self.normalization))) if zeros is None: zeros, weights = _shtools.SHGLQ(self.lmax) data = _shtools.MakeGridGLQC(self.coeffs, zeros, norm=norm, csphase=self.csphase, lmax=lmax, lmax_calc=lmax_calc) gridout = SHGrid.from_array(data, grid='GLQ', copy=False) return gridout
[ "def", "_expandGLQ", "(", "self", ",", "zeros", ",", "lmax", ",", "lmax_calc", ")", ":", "if", "self", ".", "normalization", "==", "'4pi'", ":", "norm", "=", "1", "elif", "self", ".", "normalization", "==", "'schmidt'", ":", "norm", "=", "2", "elif", ...
Evaluate the coefficients on a Gauss-Legendre quadrature grid.
[ "Evaluate", "the", "coefficients", "on", "a", "Gauss", "-", "Legendre", "quadrature", "grid", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2021-L2044
train
203,879
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHGrid.from_array
def from_array(self, array, grid='DH', copy=True): """ Initialize the class instance from an input array. Usage ----- x = SHGrid.from_array(array, [grid, copy]) Returns ------- x : SHGrid class instance Parameters ---------- array : ndarray, shape (nlat, nlon) 2-D numpy array of the gridded data, where nlat and nlon are the number of latitudinal and longitudinal bands, respectively. grid : str, optional, default = 'DH' 'DH' or 'GLQ' for Driscoll and Healy grids or Gauss Legendre Quadrature grids, respectively. copy : bool, optional, default = True If True (default), make a copy of array when initializing the class instance. If False, initialize the class instance with a reference to array. """ if _np.iscomplexobj(array): kind = 'complex' else: kind = 'real' if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() not in set(['DH', 'GLQ']): raise ValueError( "grid must be 'DH' or 'GLQ'. Input value was {:s}." .format(repr(grid)) ) for cls in self.__subclasses__(): if cls.istype(kind) and cls.isgrid(grid): return cls(array, copy=copy)
python
def from_array(self, array, grid='DH', copy=True): """ Initialize the class instance from an input array. Usage ----- x = SHGrid.from_array(array, [grid, copy]) Returns ------- x : SHGrid class instance Parameters ---------- array : ndarray, shape (nlat, nlon) 2-D numpy array of the gridded data, where nlat and nlon are the number of latitudinal and longitudinal bands, respectively. grid : str, optional, default = 'DH' 'DH' or 'GLQ' for Driscoll and Healy grids or Gauss Legendre Quadrature grids, respectively. copy : bool, optional, default = True If True (default), make a copy of array when initializing the class instance. If False, initialize the class instance with a reference to array. """ if _np.iscomplexobj(array): kind = 'complex' else: kind = 'real' if type(grid) != str: raise ValueError('grid must be a string. ' + 'Input type was {:s}' .format(str(type(grid)))) if grid.upper() not in set(['DH', 'GLQ']): raise ValueError( "grid must be 'DH' or 'GLQ'. Input value was {:s}." .format(repr(grid)) ) for cls in self.__subclasses__(): if cls.istype(kind) and cls.isgrid(grid): return cls(array, copy=copy)
[ "def", "from_array", "(", "self", ",", "array", ",", "grid", "=", "'DH'", ",", "copy", "=", "True", ")", ":", "if", "_np", ".", "iscomplexobj", "(", "array", ")", ":", "kind", "=", "'complex'", "else", ":", "kind", "=", "'real'", "if", "type", "(",...
Initialize the class instance from an input array. Usage ----- x = SHGrid.from_array(array, [grid, copy]) Returns ------- x : SHGrid class instance Parameters ---------- array : ndarray, shape (nlat, nlon) 2-D numpy array of the gridded data, where nlat and nlon are the number of latitudinal and longitudinal bands, respectively. grid : str, optional, default = 'DH' 'DH' or 'GLQ' for Driscoll and Healy grids or Gauss Legendre Quadrature grids, respectively. copy : bool, optional, default = True If True (default), make a copy of array when initializing the class instance. If False, initialize the class instance with a reference to array.
[ "Initialize", "the", "class", "instance", "from", "an", "input", "array", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2158-L2201
train
203,880
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHGrid.from_file
def from_file(self, fname, binary=False, **kwargs): """ Initialize the class instance from gridded data in a file. Usage ----- x = SHGrid.from_file(fname, [binary, **kwargs]) Returns ------- x : SHGrid class instance Parameters ---------- fname : str The filename containing the gridded data. For text files (default) the file is read using the numpy routine loadtxt(), whereas for binary files, the file is read using numpy.load(). The dimensions of the array must be nlon=nlat or nlon=2*nlat for Driscoll and Healy grids, or nlon=2*nlat-1 for Gauss-Legendre Quadrature grids. binary : bool, optional, default = False If False, read a text file. If True, read a binary 'npy' file. **kwargs : keyword arguments, optional Keyword arguments of numpy.loadtxt() or numpy.load(). """ if binary is False: data = _np.loadtxt(fname, **kwargs) elif binary is True: data = _np.load(fname, **kwargs) else: raise ValueError('binary must be True or False. ' 'Input value is {:s}'.format(binary)) if _np.iscomplexobj(data): kind = 'complex' else: kind = 'real' if (data.shape[1] == data.shape[0]) or (data.shape[1] == 2 * data.shape[0]): grid = 'DH' elif data.shape[1] == 2 * data.shape[0] - 1: grid = 'GLQ' else: raise ValueError('Input grid must be dimensioned as ' + '(nlat, nlon). For DH grids, nlon = nlat or ' + 'nlon = 2 * nlat. For GLQ grids, nlon = ' + '2 * nlat - 1. Input dimensions are nlat = ' + '{:d}, nlon = {:d}'.format(data.shape[0], data.shape[1])) for cls in self.__subclasses__(): if cls.istype(kind) and cls.isgrid(grid): return cls(data)
python
def from_file(self, fname, binary=False, **kwargs): """ Initialize the class instance from gridded data in a file. Usage ----- x = SHGrid.from_file(fname, [binary, **kwargs]) Returns ------- x : SHGrid class instance Parameters ---------- fname : str The filename containing the gridded data. For text files (default) the file is read using the numpy routine loadtxt(), whereas for binary files, the file is read using numpy.load(). The dimensions of the array must be nlon=nlat or nlon=2*nlat for Driscoll and Healy grids, or nlon=2*nlat-1 for Gauss-Legendre Quadrature grids. binary : bool, optional, default = False If False, read a text file. If True, read a binary 'npy' file. **kwargs : keyword arguments, optional Keyword arguments of numpy.loadtxt() or numpy.load(). """ if binary is False: data = _np.loadtxt(fname, **kwargs) elif binary is True: data = _np.load(fname, **kwargs) else: raise ValueError('binary must be True or False. ' 'Input value is {:s}'.format(binary)) if _np.iscomplexobj(data): kind = 'complex' else: kind = 'real' if (data.shape[1] == data.shape[0]) or (data.shape[1] == 2 * data.shape[0]): grid = 'DH' elif data.shape[1] == 2 * data.shape[0] - 1: grid = 'GLQ' else: raise ValueError('Input grid must be dimensioned as ' + '(nlat, nlon). For DH grids, nlon = nlat or ' + 'nlon = 2 * nlat. For GLQ grids, nlon = ' + '2 * nlat - 1. Input dimensions are nlat = ' + '{:d}, nlon = {:d}'.format(data.shape[0], data.shape[1])) for cls in self.__subclasses__(): if cls.istype(kind) and cls.isgrid(grid): return cls(data)
[ "def", "from_file", "(", "self", ",", "fname", ",", "binary", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "binary", "is", "False", ":", "data", "=", "_np", ".", "loadtxt", "(", "fname", ",", "*", "*", "kwargs", ")", "elif", "binary", "...
Initialize the class instance from gridded data in a file. Usage ----- x = SHGrid.from_file(fname, [binary, **kwargs]) Returns ------- x : SHGrid class instance Parameters ---------- fname : str The filename containing the gridded data. For text files (default) the file is read using the numpy routine loadtxt(), whereas for binary files, the file is read using numpy.load(). The dimensions of the array must be nlon=nlat or nlon=2*nlat for Driscoll and Healy grids, or nlon=2*nlat-1 for Gauss-Legendre Quadrature grids. binary : bool, optional, default = False If False, read a text file. If True, read a binary 'npy' file. **kwargs : keyword arguments, optional Keyword arguments of numpy.loadtxt() or numpy.load().
[ "Initialize", "the", "class", "instance", "from", "gridded", "data", "in", "a", "file", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2204-L2257
train
203,881
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHGrid.to_file
def to_file(self, filename, binary=False, **kwargs): """ Save gridded data to a file. Usage ----- x.to_file(filename, [binary, **kwargs]) Parameters ---------- filename : str Name of output file. For text files (default), the file will be saved automatically in gzip compressed format if the filename ends in .gz. binary : bool, optional, default = False If False, save as text using numpy.savetxt(). If True, save as a 'npy' binary file using numpy.save(). **kwargs : keyword arguments, optional Keyword arguments of numpy.savetxt() and numpy.save(). """ if binary is False: _np.savetxt(filename, self.data, **kwargs) elif binary is True: _np.save(filename, self.data, **kwargs) else: raise ValueError('binary must be True or False. ' 'Input value is {:s}'.format(binary))
python
def to_file(self, filename, binary=False, **kwargs): """ Save gridded data to a file. Usage ----- x.to_file(filename, [binary, **kwargs]) Parameters ---------- filename : str Name of output file. For text files (default), the file will be saved automatically in gzip compressed format if the filename ends in .gz. binary : bool, optional, default = False If False, save as text using numpy.savetxt(). If True, save as a 'npy' binary file using numpy.save(). **kwargs : keyword arguments, optional Keyword arguments of numpy.savetxt() and numpy.save(). """ if binary is False: _np.savetxt(filename, self.data, **kwargs) elif binary is True: _np.save(filename, self.data, **kwargs) else: raise ValueError('binary must be True or False. ' 'Input value is {:s}'.format(binary))
[ "def", "to_file", "(", "self", ",", "filename", ",", "binary", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "binary", "is", "False", ":", "_np", ".", "savetxt", "(", "filename", ",", "self", ".", "data", ",", "*", "*", "kwargs", ")", "e...
Save gridded data to a file. Usage ----- x.to_file(filename, [binary, **kwargs]) Parameters ---------- filename : str Name of output file. For text files (default), the file will be saved automatically in gzip compressed format if the filename ends in .gz. binary : bool, optional, default = False If False, save as text using numpy.savetxt(). If True, save as a 'npy' binary file using numpy.save(). **kwargs : keyword arguments, optional Keyword arguments of numpy.savetxt() and numpy.save().
[ "Save", "gridded", "data", "to", "a", "file", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2269-L2295
train
203,882
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHGrid.lats
def lats(self, degrees=True): """ Return the latitudes of each row of the gridded data. Usage ----- lats = x.lats([degrees]) Returns ------- lats : ndarray, shape (nlat) 1-D numpy array of size nlat containing the latitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians. """ if degrees is False: return _np.radians(self._lats()) else: return self._lats()
python
def lats(self, degrees=True): """ Return the latitudes of each row of the gridded data. Usage ----- lats = x.lats([degrees]) Returns ------- lats : ndarray, shape (nlat) 1-D numpy array of size nlat containing the latitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians. """ if degrees is False: return _np.radians(self._lats()) else: return self._lats()
[ "def", "lats", "(", "self", ",", "degrees", "=", "True", ")", ":", "if", "degrees", "is", "False", ":", "return", "_np", ".", "radians", "(", "self", ".", "_lats", "(", ")", ")", "else", ":", "return", "self", ".", "_lats", "(", ")" ]
Return the latitudes of each row of the gridded data. Usage ----- lats = x.lats([degrees]) Returns ------- lats : ndarray, shape (nlat) 1-D numpy array of size nlat containing the latitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians.
[ "Return", "the", "latitudes", "of", "each", "row", "of", "the", "gridded", "data", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2475-L2498
train
203,883
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHGrid.lons
def lons(self, degrees=True): """ Return the longitudes of each column of the gridded data. Usage ----- lons = x.get_lon([degrees]) Returns ------- lons : ndarray, shape (nlon) 1-D numpy array of size nlon containing the longitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians. """ if degrees is False: return _np.radians(self._lons()) else: return self._lons()
python
def lons(self, degrees=True): """ Return the longitudes of each column of the gridded data. Usage ----- lons = x.get_lon([degrees]) Returns ------- lons : ndarray, shape (nlon) 1-D numpy array of size nlon containing the longitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians. """ if degrees is False: return _np.radians(self._lons()) else: return self._lons()
[ "def", "lons", "(", "self", ",", "degrees", "=", "True", ")", ":", "if", "degrees", "is", "False", ":", "return", "_np", ".", "radians", "(", "self", ".", "_lons", "(", ")", ")", "else", ":", "return", "self", ".", "_lons", "(", ")" ]
Return the longitudes of each column of the gridded data. Usage ----- lons = x.get_lon([degrees]) Returns ------- lons : ndarray, shape (nlon) 1-D numpy array of size nlon containing the longitude of each row of the gridded data. Parameters ------- degrees : bool, optional, default = True If True, the output will be in degrees. If False, the output will be in radians.
[ "Return", "the", "longitudes", "of", "each", "column", "of", "the", "gridded", "data", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2500-L2523
train
203,884
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
SHGrid.expand
def expand(self, normalization='4pi', csphase=1, **kwargs): """ Expand the grid into spherical harmonics. Usage ----- clm = x.expand([normalization, csphase, lmax_calc]) Returns ------- clm : SHCoeffs class instance Parameters ---------- normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. lmax_calc : int, optional, default = x.lmax Maximum spherical harmonic degree to return. """ if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) return self._expand(normalization=normalization, csphase=csphase, **kwargs)
python
def expand(self, normalization='4pi', csphase=1, **kwargs): """ Expand the grid into spherical harmonics. Usage ----- clm = x.expand([normalization, csphase, lmax_calc]) Returns ------- clm : SHCoeffs class instance Parameters ---------- normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. lmax_calc : int, optional, default = x.lmax Maximum spherical harmonic degree to return. """ if type(normalization) != str: raise ValueError('normalization must be a string. ' + 'Input type was {:s}' .format(str(type(normalization)))) if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) return self._expand(normalization=normalization, csphase=csphase, **kwargs)
[ "def", "expand", "(", "self", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "normalization", ")", "!=", "str", ":", "raise", "ValueError", "(", "'normalization must be a string. '", "+",...
Expand the grid into spherical harmonics. Usage ----- clm = x.expand([normalization, csphase, lmax_calc]) Returns ------- clm : SHCoeffs class instance Parameters ---------- normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho', 'schmidt', or 'unnorm', for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. lmax_calc : int, optional, default = x.lmax Maximum spherical harmonic degree to return.
[ "Expand", "the", "grid", "into", "spherical", "harmonics", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2775-L2818
train
203,885
SHTOOLS/SHTOOLS
pyshtools/shclasses/shcoeffsgrid.py
DHRealGrid._expand
def _expand(self, normalization, csphase, **kwargs): """Expand the grid into real spherical harmonics.""" if normalization.lower() == '4pi': norm = 1 elif normalization.lower() == 'schmidt': norm = 2 elif normalization.lower() == 'unnorm': norm = 3 elif normalization.lower() == 'ortho': norm = 4 else: raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) cilm = _shtools.SHExpandDH(self.data, norm=norm, csphase=csphase, sampling=self.sampling, **kwargs) coeffs = SHCoeffs.from_array(cilm, normalization=normalization.lower(), csphase=csphase, copy=False) return coeffs
python
def _expand(self, normalization, csphase, **kwargs): """Expand the grid into real spherical harmonics.""" if normalization.lower() == '4pi': norm = 1 elif normalization.lower() == 'schmidt': norm = 2 elif normalization.lower() == 'unnorm': norm = 3 elif normalization.lower() == 'ortho': norm = 4 else: raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) cilm = _shtools.SHExpandDH(self.data, norm=norm, csphase=csphase, sampling=self.sampling, **kwargs) coeffs = SHCoeffs.from_array(cilm, normalization=normalization.lower(), csphase=csphase, copy=False) return coeffs
[ "def", "_expand", "(", "self", ",", "normalization", ",", "csphase", ",", "*", "*", "kwargs", ")", ":", "if", "normalization", ".", "lower", "(", ")", "==", "'4pi'", ":", "norm", "=", "1", "elif", "normalization", ".", "lower", "(", ")", "==", "'schm...
Expand the grid into real spherical harmonics.
[ "Expand", "the", "grid", "into", "real", "spherical", "harmonics", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2881-L2904
train
203,886
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgeoid.py
SHGeoid.plot
def plot(self, colorbar=True, cb_orientation='vertical', cb_label='geoid, m', show=True, **kwargs): """ Plot the geoid. Usage ----- x.plot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = 'geoid, m' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ return self.geoid.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=True, **kwargs)
python
def plot(self, colorbar=True, cb_orientation='vertical', cb_label='geoid, m', show=True, **kwargs): """ Plot the geoid. Usage ----- x.plot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = 'geoid, m' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ return self.geoid.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=True, **kwargs)
[ "def", "plot", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "'geoid, m'", ",", "show", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "geoid", ".", "plot", "(", "co...
Plot the geoid. Usage ----- x.plot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = 'geoid, m' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods.
[ "Plot", "the", "geoid", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgeoid.py#L107-L145
train
203,887
SHTOOLS/SHTOOLS
pyshtools/utils/datetime.py
_yyyymmdd_to_year_fraction
def _yyyymmdd_to_year_fraction(date): """Convert YYYMMDD.DD date string or float to YYYY.YYY""" date = str(date) if '.' in date: date, residual = str(date).split('.') residual = float('0.' + residual) else: residual = 0.0 date = _datetime.datetime.strptime(date, '%Y%m%d') date += _datetime.timedelta(days=residual) year = date.year year_start = _datetime.datetime(year=year, month=1, day=1) next_year_start = _datetime.datetime(year=year + 1, month=1, day=1) year_duration = next_year_start - year_start year_elapsed = date - year_start fraction = year_elapsed / year_duration return year + fraction
python
def _yyyymmdd_to_year_fraction(date): """Convert YYYMMDD.DD date string or float to YYYY.YYY""" date = str(date) if '.' in date: date, residual = str(date).split('.') residual = float('0.' + residual) else: residual = 0.0 date = _datetime.datetime.strptime(date, '%Y%m%d') date += _datetime.timedelta(days=residual) year = date.year year_start = _datetime.datetime(year=year, month=1, day=1) next_year_start = _datetime.datetime(year=year + 1, month=1, day=1) year_duration = next_year_start - year_start year_elapsed = date - year_start fraction = year_elapsed / year_duration return year + fraction
[ "def", "_yyyymmdd_to_year_fraction", "(", "date", ")", ":", "date", "=", "str", "(", "date", ")", "if", "'.'", "in", "date", ":", "date", ",", "residual", "=", "str", "(", "date", ")", ".", "split", "(", "'.'", ")", "residual", "=", "float", "(", "...
Convert YYYMMDD.DD date string or float to YYYY.YYY
[ "Convert", "YYYMMDD", ".", "DD", "date", "string", "or", "float", "to", "YYYY", ".", "YYY" ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/utils/datetime.py#L11-L31
train
203,888
SHTOOLS/SHTOOLS
examples/python/GlobalSpectralAnalysis/GlobalSpectralAnalysis.py
example
def example(): """ example that plots the power spectrum of Mars topography data """ # --- input data filename --- infile = os.path.join(os.path.dirname(__file__), '../../ExampleDataFiles/MarsTopo719.shape') coeffs, lmax = shio.shread(infile) # --- plot grid --- grid = expand.MakeGridDH(coeffs, csphase=-1) fig_map = plt.figure() plt.imshow(grid) # ---- compute spectrum ---- ls = np.arange(lmax + 1) pspectrum = spectralanalysis.spectrum(coeffs, unit='per_l') pdensity = spectralanalysis.spectrum(coeffs, unit='per_lm') # ---- plot spectrum ---- fig_spectrum, ax = plt.subplots(1, 1) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('degree l') ax.grid(True, which='both') ax.plot(ls[1:], pspectrum[1:], label='power per degree l') ax.plot(ls[1:], pdensity[1:], label='power per degree l and order m') ax.legend() fig_map.savefig('SHRtopography_mars.png') fig_spectrum.savefig('SHRspectrum_mars.png') print('mars topography and spectrum saved')
python
def example(): """ example that plots the power spectrum of Mars topography data """ # --- input data filename --- infile = os.path.join(os.path.dirname(__file__), '../../ExampleDataFiles/MarsTopo719.shape') coeffs, lmax = shio.shread(infile) # --- plot grid --- grid = expand.MakeGridDH(coeffs, csphase=-1) fig_map = plt.figure() plt.imshow(grid) # ---- compute spectrum ---- ls = np.arange(lmax + 1) pspectrum = spectralanalysis.spectrum(coeffs, unit='per_l') pdensity = spectralanalysis.spectrum(coeffs, unit='per_lm') # ---- plot spectrum ---- fig_spectrum, ax = plt.subplots(1, 1) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('degree l') ax.grid(True, which='both') ax.plot(ls[1:], pspectrum[1:], label='power per degree l') ax.plot(ls[1:], pdensity[1:], label='power per degree l and order m') ax.legend() fig_map.savefig('SHRtopography_mars.png') fig_spectrum.savefig('SHRspectrum_mars.png') print('mars topography and spectrum saved')
[ "def", "example", "(", ")", ":", "# --- input data filename ---", "infile", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../../ExampleDataFiles/MarsTopo719.shape'", ")", "coeffs", ",", "lmax", "=", ...
example that plots the power spectrum of Mars topography data
[ "example", "that", "plots", "the", "power", "spectrum", "of", "Mars", "topography", "data" ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/examples/python/GlobalSpectralAnalysis/GlobalSpectralAnalysis.py#L30-L63
train
203,889
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravcoeffs.py
SHGravCoeffs.from_zeros
def from_zeros(self, lmax, gm, r0, omega=None, errors=False, normalization='4pi', csphase=1): """ Initialize the class with spherical harmonic coefficients set to zero from degree 1 to lmax, and set the degree 0 term to 1. Usage ----- x = SHGravCoeffs.from_zeros(lmax, gm, r0, [omega, errors, normalization, csphase]) Returns ------- x : SHGravCoeffs class instance. Parameters ---------- lmax : int The maximum spherical harmonic degree l of the coefficients. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. r0 : float The reference radius of the spherical harmonic coefficients. omega : float, optional, default = None The angular rotation rate of the body. errors : bool, optional, default = False If True, initialize the attribute errors with zeros. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """ if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " "are stable only for degrees less than or equal " "to 85. lmax for the coefficients will be set to " "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 coeffs = _np.zeros((2, lmax + 1, lmax + 1)) coeffs[0, 0, 0] = 1.0 if errors is False: clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega, normalization=normalization.lower(), csphase=csphase) else: clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega, errors=_np.zeros((2, lmax + 1, lmax + 1)), normalization=normalization.lower(), csphase=csphase) return clm
python
def from_zeros(self, lmax, gm, r0, omega=None, errors=False, normalization='4pi', csphase=1): """ Initialize the class with spherical harmonic coefficients set to zero from degree 1 to lmax, and set the degree 0 term to 1. Usage ----- x = SHGravCoeffs.from_zeros(lmax, gm, r0, [omega, errors, normalization, csphase]) Returns ------- x : SHGravCoeffs class instance. Parameters ---------- lmax : int The maximum spherical harmonic degree l of the coefficients. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. r0 : float The reference radius of the spherical harmonic coefficients. omega : float, optional, default = None The angular rotation rate of the body. errors : bool, optional, default = False If True, initialize the attribute errors with zeros. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """ if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'): raise ValueError( "The normalization must be '4pi', 'ortho', 'schmidt', " "or 'unnorm'. Input value was {:s}." .format(repr(normalization)) ) if csphase != 1 and csphase != -1: raise ValueError( "csphase must be either 1 or -1. Input value was {:s}." .format(repr(csphase)) ) if normalization.lower() == 'unnorm' and lmax > 85: _warnings.warn("Calculations using unnormalized coefficients " "are stable only for degrees less than or equal " "to 85. lmax for the coefficients will be set to " "85. Input value was {:d}.".format(lmax), category=RuntimeWarning) lmax = 85 coeffs = _np.zeros((2, lmax + 1, lmax + 1)) coeffs[0, 0, 0] = 1.0 if errors is False: clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega, normalization=normalization.lower(), csphase=csphase) else: clm = SHGravRealCoeffs(coeffs, gm=gm, r0=r0, omega=omega, errors=_np.zeros((2, lmax + 1, lmax + 1)), normalization=normalization.lower(), csphase=csphase) return clm
[ "def", "from_zeros", "(", "self", ",", "lmax", ",", "gm", ",", "r0", ",", "omega", "=", "None", ",", "errors", "=", "False", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ")", ":", "if", "normalization", ".", "lower", "(", ")", "not...
Initialize the class with spherical harmonic coefficients set to zero from degree 1 to lmax, and set the degree 0 term to 1. Usage ----- x = SHGravCoeffs.from_zeros(lmax, gm, r0, [omega, errors, normalization, csphase]) Returns ------- x : SHGravCoeffs class instance. Parameters ---------- lmax : int The maximum spherical harmonic degree l of the coefficients. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. r0 : float The reference radius of the spherical harmonic coefficients. omega : float, optional, default = None The angular rotation rate of the body. errors : bool, optional, default = False If True, initialize the attribute errors with zeros. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it.
[ "Initialize", "the", "class", "with", "spherical", "harmonic", "coefficients", "set", "to", "zero", "from", "degree", "1", "to", "lmax", "and", "set", "the", "degree", "0", "term", "to", "1", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L248-L317
train
203,890
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravcoeffs.py
SHGravCoeffs.from_shape
def from_shape(self, shape, rho, gm, nmax=7, lmax=None, lmax_grid=None, lmax_calc=None, omega=None): """ Initialize a class of gravitational potential spherical harmonic coefficients by calculuting the gravitational potential associatiated with relief along an interface. Usage ----- x = SHGravCoeffs.from_shape(shape, rho, gm, [nmax, lmax, lmax_grid, lmax_calc, omega]) Returns ------- x : SHGravCoeffs class instance. Parameters ---------- shape : SHGrid or SHCoeffs class instance The shape of the interface, either as an SHGrid or SHCoeffs class instance. If the input is an SHCoeffs class instance, this will be expaned on a grid using the optional parameters lmax_grid and lmax_calc. rho : int, float, or ndarray, or an SHGrid or SHCoeffs class instance The density contrast associated with the interface in kg / m3. If the input is a scalar, the density contrast is constant. If the input is an SHCoeffs or SHGrid class instance, the density contrast will vary laterally. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. nmax : integer, optional, default = 7 The maximum order used in the Taylor-series expansion when calculating the potential coefficients. lmax : int, optional, shape.lmax The maximum spherical harmonic degree of the output spherical harmonic coefficients. lmax_grid : int, optional, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that is resolvable when expanded onto a grid. lmax_calc : optional, integer, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that will be used when expanded onto a grid. omega : float, optional, default = None The angular rotation rate of the body. Description ----------- Initialize an SHGravCoeffs class instance by calculating the spherical harmonic coefficients of the gravitational potential associated with the shape of a density interface. The potential is calculated using the finite-amplitude technique of Wieczorek and Phillips (1998) for a constant density contrast and Wieczorek (2007) for a density contrast that varies laterally. The output coefficients are referenced to the mean radius of shape, and the potential is strictly valid only when it is evaluated at a radius greater than the maximum radius of shape. The input shape (and density contrast rho for variable density) can be either an SHGrid or SHCoeffs class instance. The routine makes direct use of gridded versions of these quantities, so if the input is of type SHCoeffs, it will first be expanded onto a grid. This exansion will be performed on a grid that can resolve degrees up to lmax_grid, with only the first lmax_calc coefficients being used. The input shape must correspond to absolute radii as the degree 0 term determines the reference radius of the coefficients. As an intermediate step, this routine calculates the spherical harmonic coefficients of the interface raised to the nth power, i.e., (shape-r0)**n, where r0 is the mean radius of shape. If the input shape is bandlimited to degree L, the resulting function will thus be bandlimited to degree L*nmax. This subroutine assumes implicitly that the maximum spherical harmonic degree of the input shape (when SHCoeffs) or maximum resolvable spherical harmonic degree of shape (when SHGrid) is greater or equal to this value. If this is not the case, aliasing will occur. In practice, for accurate results, the effective bandwidth needs only to be about three times the size of L, though this should be verified for each application. The effective bandwidth of shape (when SHCoeffs) can be increased by preprocessing with the method pad(), or by increaesing the value of lmax_grid (when SHGrid). """ mass = gm / _G.value if type(shape) is not _SHRealCoeffs and type(shape) is not _DHRealGrid: raise ValueError('shape must be of type SHRealCoeffs ' 'or DHRealGrid. Input type is {:s}' .format(repr(type(shape)))) if (not issubclass(type(rho), float) and type(rho) is not int and type(rho) is not _np.ndarray and type(rho) is not _SHRealCoeffs and type(rho is not _DHRealGrid)): raise ValueError('rho must be of type float, int, ndarray, ' 'SHRealCoeffs or DHRealGrid. Input type is {:s}' .format(repr(type(rho)))) if type(shape) is _SHRealCoeffs: shape = shape.expand(lmax=lmax_grid, lmax_calc=lmax_calc) if type(rho) is _SHRealCoeffs: rho = rho.expand(lmax=lmax_grid, lmax_calc=lmax_calc) if type(rho) is _DHRealGrid: if shape.lmax != rho.lmax: raise ValueError('The grids for shape and rho must have the ' 'same size. ' 'lmax of shape = {:d}, lmax of rho = {:d}' .format(shape.lmax, rho.lmax)) cilm, d = _CilmPlusRhoHDH(shape.data, nmax, mass, rho.data, lmax=lmax) else: cilm, d = _CilmPlusDH(shape.data, nmax, mass, rho, lmax=lmax) clm = SHGravRealCoeffs(cilm, gm=gm, r0=d, omega=omega, normalization='4pi', csphase=1) return clm
python
def from_shape(self, shape, rho, gm, nmax=7, lmax=None, lmax_grid=None, lmax_calc=None, omega=None): """ Initialize a class of gravitational potential spherical harmonic coefficients by calculuting the gravitational potential associatiated with relief along an interface. Usage ----- x = SHGravCoeffs.from_shape(shape, rho, gm, [nmax, lmax, lmax_grid, lmax_calc, omega]) Returns ------- x : SHGravCoeffs class instance. Parameters ---------- shape : SHGrid or SHCoeffs class instance The shape of the interface, either as an SHGrid or SHCoeffs class instance. If the input is an SHCoeffs class instance, this will be expaned on a grid using the optional parameters lmax_grid and lmax_calc. rho : int, float, or ndarray, or an SHGrid or SHCoeffs class instance The density contrast associated with the interface in kg / m3. If the input is a scalar, the density contrast is constant. If the input is an SHCoeffs or SHGrid class instance, the density contrast will vary laterally. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. nmax : integer, optional, default = 7 The maximum order used in the Taylor-series expansion when calculating the potential coefficients. lmax : int, optional, shape.lmax The maximum spherical harmonic degree of the output spherical harmonic coefficients. lmax_grid : int, optional, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that is resolvable when expanded onto a grid. lmax_calc : optional, integer, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that will be used when expanded onto a grid. omega : float, optional, default = None The angular rotation rate of the body. Description ----------- Initialize an SHGravCoeffs class instance by calculating the spherical harmonic coefficients of the gravitational potential associated with the shape of a density interface. The potential is calculated using the finite-amplitude technique of Wieczorek and Phillips (1998) for a constant density contrast and Wieczorek (2007) for a density contrast that varies laterally. The output coefficients are referenced to the mean radius of shape, and the potential is strictly valid only when it is evaluated at a radius greater than the maximum radius of shape. The input shape (and density contrast rho for variable density) can be either an SHGrid or SHCoeffs class instance. The routine makes direct use of gridded versions of these quantities, so if the input is of type SHCoeffs, it will first be expanded onto a grid. This exansion will be performed on a grid that can resolve degrees up to lmax_grid, with only the first lmax_calc coefficients being used. The input shape must correspond to absolute radii as the degree 0 term determines the reference radius of the coefficients. As an intermediate step, this routine calculates the spherical harmonic coefficients of the interface raised to the nth power, i.e., (shape-r0)**n, where r0 is the mean radius of shape. If the input shape is bandlimited to degree L, the resulting function will thus be bandlimited to degree L*nmax. This subroutine assumes implicitly that the maximum spherical harmonic degree of the input shape (when SHCoeffs) or maximum resolvable spherical harmonic degree of shape (when SHGrid) is greater or equal to this value. If this is not the case, aliasing will occur. In practice, for accurate results, the effective bandwidth needs only to be about three times the size of L, though this should be verified for each application. The effective bandwidth of shape (when SHCoeffs) can be increased by preprocessing with the method pad(), or by increaesing the value of lmax_grid (when SHGrid). """ mass = gm / _G.value if type(shape) is not _SHRealCoeffs and type(shape) is not _DHRealGrid: raise ValueError('shape must be of type SHRealCoeffs ' 'or DHRealGrid. Input type is {:s}' .format(repr(type(shape)))) if (not issubclass(type(rho), float) and type(rho) is not int and type(rho) is not _np.ndarray and type(rho) is not _SHRealCoeffs and type(rho is not _DHRealGrid)): raise ValueError('rho must be of type float, int, ndarray, ' 'SHRealCoeffs or DHRealGrid. Input type is {:s}' .format(repr(type(rho)))) if type(shape) is _SHRealCoeffs: shape = shape.expand(lmax=lmax_grid, lmax_calc=lmax_calc) if type(rho) is _SHRealCoeffs: rho = rho.expand(lmax=lmax_grid, lmax_calc=lmax_calc) if type(rho) is _DHRealGrid: if shape.lmax != rho.lmax: raise ValueError('The grids for shape and rho must have the ' 'same size. ' 'lmax of shape = {:d}, lmax of rho = {:d}' .format(shape.lmax, rho.lmax)) cilm, d = _CilmPlusRhoHDH(shape.data, nmax, mass, rho.data, lmax=lmax) else: cilm, d = _CilmPlusDH(shape.data, nmax, mass, rho, lmax=lmax) clm = SHGravRealCoeffs(cilm, gm=gm, r0=d, omega=omega, normalization='4pi', csphase=1) return clm
[ "def", "from_shape", "(", "self", ",", "shape", ",", "rho", ",", "gm", ",", "nmax", "=", "7", ",", "lmax", "=", "None", ",", "lmax_grid", "=", "None", ",", "lmax_calc", "=", "None", ",", "omega", "=", "None", ")", ":", "mass", "=", "gm", "/", "...
Initialize a class of gravitational potential spherical harmonic coefficients by calculuting the gravitational potential associatiated with relief along an interface. Usage ----- x = SHGravCoeffs.from_shape(shape, rho, gm, [nmax, lmax, lmax_grid, lmax_calc, omega]) Returns ------- x : SHGravCoeffs class instance. Parameters ---------- shape : SHGrid or SHCoeffs class instance The shape of the interface, either as an SHGrid or SHCoeffs class instance. If the input is an SHCoeffs class instance, this will be expaned on a grid using the optional parameters lmax_grid and lmax_calc. rho : int, float, or ndarray, or an SHGrid or SHCoeffs class instance The density contrast associated with the interface in kg / m3. If the input is a scalar, the density contrast is constant. If the input is an SHCoeffs or SHGrid class instance, the density contrast will vary laterally. gm : float The gravitational constant times the mass that is associated with the gravitational potential coefficients. nmax : integer, optional, default = 7 The maximum order used in the Taylor-series expansion when calculating the potential coefficients. lmax : int, optional, shape.lmax The maximum spherical harmonic degree of the output spherical harmonic coefficients. lmax_grid : int, optional, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that is resolvable when expanded onto a grid. lmax_calc : optional, integer, default = lmax If shape or rho is of type SHCoeffs, this parameter determines the maximum spherical harmonic degree that will be used when expanded onto a grid. omega : float, optional, default = None The angular rotation rate of the body. Description ----------- Initialize an SHGravCoeffs class instance by calculating the spherical harmonic coefficients of the gravitational potential associated with the shape of a density interface. The potential is calculated using the finite-amplitude technique of Wieczorek and Phillips (1998) for a constant density contrast and Wieczorek (2007) for a density contrast that varies laterally. The output coefficients are referenced to the mean radius of shape, and the potential is strictly valid only when it is evaluated at a radius greater than the maximum radius of shape. The input shape (and density contrast rho for variable density) can be either an SHGrid or SHCoeffs class instance. The routine makes direct use of gridded versions of these quantities, so if the input is of type SHCoeffs, it will first be expanded onto a grid. This exansion will be performed on a grid that can resolve degrees up to lmax_grid, with only the first lmax_calc coefficients being used. The input shape must correspond to absolute radii as the degree 0 term determines the reference radius of the coefficients. As an intermediate step, this routine calculates the spherical harmonic coefficients of the interface raised to the nth power, i.e., (shape-r0)**n, where r0 is the mean radius of shape. If the input shape is bandlimited to degree L, the resulting function will thus be bandlimited to degree L*nmax. This subroutine assumes implicitly that the maximum spherical harmonic degree of the input shape (when SHCoeffs) or maximum resolvable spherical harmonic degree of shape (when SHGrid) is greater or equal to this value. If this is not the case, aliasing will occur. In practice, for accurate results, the effective bandwidth needs only to be about three times the size of L, though this should be verified for each application. The effective bandwidth of shape (when SHCoeffs) can be increased by preprocessing with the method pad(), or by increaesing the value of lmax_grid (when SHGrid).
[ "Initialize", "a", "class", "of", "gravitational", "potential", "spherical", "harmonic", "coefficients", "by", "calculuting", "the", "gravitational", "potential", "associatiated", "with", "relief", "along", "an", "interface", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L676-L794
train
203,891
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravcoeffs.py
SHGravCoeffs.to_file
def to_file(self, filename, format='shtools', header=None, errors=False, **kwargs): """ Save spherical harmonic coefficients to a file. Usage ----- x.to_file(filename, [format='shtools', header, errors]) x.to_file(filename, [format='npy', **kwargs]) Parameters ---------- filename : str Name of the output file. format : str, optional, default = 'shtools' 'shtools' or 'npy'. See method from_file() for more information. header : str, optional, default = None A header string written to an 'shtools'-formatted file directly before the spherical harmonic coefficients. errors : bool, optional, default = False If True, save the errors in the file (for 'shtools' formatted files only). **kwargs : keyword argument list, optional for format = 'npy' Keyword arguments of numpy.save(). Description ----------- If format='shtools', the coefficients and meta-data will be written to an ascii formatted file. The first line is an optional user provided header line, and the following line provides the attributes r0, gm, omega, and lmax. The spherical harmonic coefficients are then listed, with increasing degree and order, with the format l, m, coeffs[0, l, m], coeffs[1, l, m] where l and m are the spherical harmonic degree and order, respectively. If the errors are to be saved, the format of each line will be l, m, coeffs[0, l, m], coeffs[1, l, m], error[0, l, m], error[1, l, m] If format='npy', the spherical harmonic coefficients (but not the meta-data nor errors) will be saved to a binary numpy 'npy' file using numpy.save(). """ if format is 'shtools': if errors is True and self.errors is None: raise ValueError('Can not save errors when then have not been ' 'initialized.') if self.omega is None: omega = 0. else: omega = self.omega with open(filename, mode='w') as file: if header is not None: file.write(header + '\n') file.write('{:.16e}, {:.16e}, {:.16e}, {:d}\n'.format( self.r0, self.gm, omega, self.lmax)) for l in range(self.lmax+1): for m in range(l+1): if errors is True: file.write('{:d}, {:d}, {:.16e}, {:.16e}, ' '{:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m], self.errors[0, l, m], self.errors[1, l, m])) else: file.write('{:d}, {:d}, {:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m])) elif format is 'npy': _np.save(filename, self.coeffs, **kwargs) else: raise NotImplementedError( 'format={:s} not implemented'.format(repr(format)))
python
def to_file(self, filename, format='shtools', header=None, errors=False, **kwargs): """ Save spherical harmonic coefficients to a file. Usage ----- x.to_file(filename, [format='shtools', header, errors]) x.to_file(filename, [format='npy', **kwargs]) Parameters ---------- filename : str Name of the output file. format : str, optional, default = 'shtools' 'shtools' or 'npy'. See method from_file() for more information. header : str, optional, default = None A header string written to an 'shtools'-formatted file directly before the spherical harmonic coefficients. errors : bool, optional, default = False If True, save the errors in the file (for 'shtools' formatted files only). **kwargs : keyword argument list, optional for format = 'npy' Keyword arguments of numpy.save(). Description ----------- If format='shtools', the coefficients and meta-data will be written to an ascii formatted file. The first line is an optional user provided header line, and the following line provides the attributes r0, gm, omega, and lmax. The spherical harmonic coefficients are then listed, with increasing degree and order, with the format l, m, coeffs[0, l, m], coeffs[1, l, m] where l and m are the spherical harmonic degree and order, respectively. If the errors are to be saved, the format of each line will be l, m, coeffs[0, l, m], coeffs[1, l, m], error[0, l, m], error[1, l, m] If format='npy', the spherical harmonic coefficients (but not the meta-data nor errors) will be saved to a binary numpy 'npy' file using numpy.save(). """ if format is 'shtools': if errors is True and self.errors is None: raise ValueError('Can not save errors when then have not been ' 'initialized.') if self.omega is None: omega = 0. else: omega = self.omega with open(filename, mode='w') as file: if header is not None: file.write(header + '\n') file.write('{:.16e}, {:.16e}, {:.16e}, {:d}\n'.format( self.r0, self.gm, omega, self.lmax)) for l in range(self.lmax+1): for m in range(l+1): if errors is True: file.write('{:d}, {:d}, {:.16e}, {:.16e}, ' '{:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m], self.errors[0, l, m], self.errors[1, l, m])) else: file.write('{:d}, {:d}, {:.16e}, {:.16e}\n' .format(l, m, self.coeffs[0, l, m], self.coeffs[1, l, m])) elif format is 'npy': _np.save(filename, self.coeffs, **kwargs) else: raise NotImplementedError( 'format={:s} not implemented'.format(repr(format)))
[ "def", "to_file", "(", "self", ",", "filename", ",", "format", "=", "'shtools'", ",", "header", "=", "None", ",", "errors", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "format", "is", "'shtools'", ":", "if", "errors", "is", "True", "and", ...
Save spherical harmonic coefficients to a file. Usage ----- x.to_file(filename, [format='shtools', header, errors]) x.to_file(filename, [format='npy', **kwargs]) Parameters ---------- filename : str Name of the output file. format : str, optional, default = 'shtools' 'shtools' or 'npy'. See method from_file() for more information. header : str, optional, default = None A header string written to an 'shtools'-formatted file directly before the spherical harmonic coefficients. errors : bool, optional, default = False If True, save the errors in the file (for 'shtools' formatted files only). **kwargs : keyword argument list, optional for format = 'npy' Keyword arguments of numpy.save(). Description ----------- If format='shtools', the coefficients and meta-data will be written to an ascii formatted file. The first line is an optional user provided header line, and the following line provides the attributes r0, gm, omega, and lmax. The spherical harmonic coefficients are then listed, with increasing degree and order, with the format l, m, coeffs[0, l, m], coeffs[1, l, m] where l and m are the spherical harmonic degree and order, respectively. If the errors are to be saved, the format of each line will be l, m, coeffs[0, l, m], coeffs[1, l, m], error[0, l, m], error[1, l, m] If format='npy', the spherical harmonic coefficients (but not the meta-data nor errors) will be saved to a binary numpy 'npy' file using numpy.save().
[ "Save", "spherical", "harmonic", "coefficients", "to", "a", "file", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L853-L930
train
203,892
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravcoeffs.py
SHGravCoeffs.change_ref
def change_ref(self, gm=None, r0=None, lmax=None): """ Return a new SHGravCoeffs class instance with a different reference gm or r0. Usage ----- clm = x.change_ref([gm, r0, lmax]) Returns ------- clm : SHGravCoeffs class instance. Parameters ---------- gm : float, optional, default = self.gm The gravitational constant time the mass that is associated with the gravitational potential coefficients. r0 : float, optional, default = self.r0 The reference radius of the spherical harmonic coefficients. lmax : int, optional, default = self.lmax Maximum spherical harmonic degree to output. Description ----------- This method returns a new class instance of the gravitational potential, but using a difference reference gm or r0. When changing the reference radius r0, the spherical harmonic coefficients will be upward or downward continued under the assumption that the reference radius is exterior to the body. """ if lmax is None: lmax = self.lmax clm = self.pad(lmax) if gm is not None and gm != self.gm: clm.coeffs *= self.gm / gm clm.gm = gm if self.errors is not None: clm.errors *= self.gm / gm if r0 is not None and r0 != self.r0: for l in _np.arange(lmax+1): clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**l if self.errors is not None: clm.errors[:, l, :l+1] *= (self.r0 / r0)**l clm.r0 = r0 return clm
python
def change_ref(self, gm=None, r0=None, lmax=None): """ Return a new SHGravCoeffs class instance with a different reference gm or r0. Usage ----- clm = x.change_ref([gm, r0, lmax]) Returns ------- clm : SHGravCoeffs class instance. Parameters ---------- gm : float, optional, default = self.gm The gravitational constant time the mass that is associated with the gravitational potential coefficients. r0 : float, optional, default = self.r0 The reference radius of the spherical harmonic coefficients. lmax : int, optional, default = self.lmax Maximum spherical harmonic degree to output. Description ----------- This method returns a new class instance of the gravitational potential, but using a difference reference gm or r0. When changing the reference radius r0, the spherical harmonic coefficients will be upward or downward continued under the assumption that the reference radius is exterior to the body. """ if lmax is None: lmax = self.lmax clm = self.pad(lmax) if gm is not None and gm != self.gm: clm.coeffs *= self.gm / gm clm.gm = gm if self.errors is not None: clm.errors *= self.gm / gm if r0 is not None and r0 != self.r0: for l in _np.arange(lmax+1): clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**l if self.errors is not None: clm.errors[:, l, :l+1] *= (self.r0 / r0)**l clm.r0 = r0 return clm
[ "def", "change_ref", "(", "self", ",", "gm", "=", "None", ",", "r0", "=", "None", ",", "lmax", "=", "None", ")", ":", "if", "lmax", "is", "None", ":", "lmax", "=", "self", ".", "lmax", "clm", "=", "self", ".", "pad", "(", "lmax", ")", "if", "...
Return a new SHGravCoeffs class instance with a different reference gm or r0. Usage ----- clm = x.change_ref([gm, r0, lmax]) Returns ------- clm : SHGravCoeffs class instance. Parameters ---------- gm : float, optional, default = self.gm The gravitational constant time the mass that is associated with the gravitational potential coefficients. r0 : float, optional, default = self.r0 The reference radius of the spherical harmonic coefficients. lmax : int, optional, default = self.lmax Maximum spherical harmonic degree to output. Description ----------- This method returns a new class instance of the gravitational potential, but using a difference reference gm or r0. When changing the reference radius r0, the spherical harmonic coefficients will be upward or downward continued under the assumption that the reference radius is exterior to the body.
[ "Return", "a", "new", "SHGravCoeffs", "class", "instance", "with", "a", "different", "reference", "gm", "or", "r0", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L1563-L1612
train
203,893
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravcoeffs.py
SHGravCoeffs.expand
def expand(self, a=None, f=None, lmax=None, lmax_calc=None, normal_gravity=True, sampling=2): """ Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the gravity field, the gravity disturbance, and the gravitational potential, and return as a SHGravGrid class instance. Usage ----- grav = x.expand([a, f, lmax, lmax_calc, normal_gravity, sampling]) Returns ------- grav : SHGravGrid class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree, which determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. normal_gravity : optional, bool, default = True If True, the normal gravity (the gravitational acceleration on the ellipsoid) will be subtracted from the total gravity, yielding the "gravity disturbance." This is done using Somigliana's formula (after converting geocentric to geodetic coordinates). sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps of the three components of the gravity field, the total field, and the gravitational potential, and return these as an SHGravGrid class instance. Each map is stored as an SHGrid class instance using Driscoll and Healy grids that are either equally sampled (n by n) or equally spaced (n by 2n) in latitude and longitude. All grids use geocentric coordinates, the output is in SI units, and the sign of the radial components is positive when directed upwards. If the optional angular rotation rate omega is specified in the SHGravCoeffs instance, the potential and radial gravitational acceleration will be calculated in a body-fixed rotating reference frame. If normal_gravity is set to True, the normal gravity will be removed from the total field, yielding the gravity disturbance. The gravitational potential is given by V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, and the gravitational acceleration is B = Grad V. The coefficients are referenced to the radius r0, and the function is computed on a flattened ellipsoid with semi-major axis a (i.e., the mean equatorial radius) and flattening f. To convert m/s^2 to mGals, multiply the gravity grids by 10^5. """ if a is None: a = self.r0 if f is None: f = 0. if normal_gravity is True: ng = 1 else: ng = 0 if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) rad, theta, phi, total, pot = _MakeGravGridDH( coeffs, self.gm, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling, omega=self.omega, normal_gravity=ng) return _SHGravGrid(rad, theta, phi, total, pot, self.gm, a, f, self.omega, normal_gravity, lmax, lmax_calc)
python
def expand(self, a=None, f=None, lmax=None, lmax_calc=None, normal_gravity=True, sampling=2): """ Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the gravity field, the gravity disturbance, and the gravitational potential, and return as a SHGravGrid class instance. Usage ----- grav = x.expand([a, f, lmax, lmax_calc, normal_gravity, sampling]) Returns ------- grav : SHGravGrid class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree, which determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. normal_gravity : optional, bool, default = True If True, the normal gravity (the gravitational acceleration on the ellipsoid) will be subtracted from the total gravity, yielding the "gravity disturbance." This is done using Somigliana's formula (after converting geocentric to geodetic coordinates). sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps of the three components of the gravity field, the total field, and the gravitational potential, and return these as an SHGravGrid class instance. Each map is stored as an SHGrid class instance using Driscoll and Healy grids that are either equally sampled (n by n) or equally spaced (n by 2n) in latitude and longitude. All grids use geocentric coordinates, the output is in SI units, and the sign of the radial components is positive when directed upwards. If the optional angular rotation rate omega is specified in the SHGravCoeffs instance, the potential and radial gravitational acceleration will be calculated in a body-fixed rotating reference frame. If normal_gravity is set to True, the normal gravity will be removed from the total field, yielding the gravity disturbance. The gravitational potential is given by V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, and the gravitational acceleration is B = Grad V. The coefficients are referenced to the radius r0, and the function is computed on a flattened ellipsoid with semi-major axis a (i.e., the mean equatorial radius) and flattening f. To convert m/s^2 to mGals, multiply the gravity grids by 10^5. """ if a is None: a = self.r0 if f is None: f = 0. if normal_gravity is True: ng = 1 else: ng = 0 if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) rad, theta, phi, total, pot = _MakeGravGridDH( coeffs, self.gm, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling, omega=self.omega, normal_gravity=ng) return _SHGravGrid(rad, theta, phi, total, pot, self.gm, a, f, self.omega, normal_gravity, lmax, lmax_calc)
[ "def", "expand", "(", "self", ",", "a", "=", "None", ",", "f", "=", "None", ",", "lmax", "=", "None", ",", "lmax_calc", "=", "None", ",", "normal_gravity", "=", "True", ",", "sampling", "=", "2", ")", ":", "if", "a", "is", "None", ":", "a", "="...
Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the gravity field, the gravity disturbance, and the gravitational potential, and return as a SHGravGrid class instance. Usage ----- grav = x.expand([a, f, lmax, lmax_calc, normal_gravity, sampling]) Returns ------- grav : SHGravGrid class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree, which determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. normal_gravity : optional, bool, default = True If True, the normal gravity (the gravitational acceleration on the ellipsoid) will be subtracted from the total gravity, yielding the "gravity disturbance." This is done using Somigliana's formula (after converting geocentric to geodetic coordinates). sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps of the three components of the gravity field, the total field, and the gravitational potential, and return these as an SHGravGrid class instance. Each map is stored as an SHGrid class instance using Driscoll and Healy grids that are either equally sampled (n by n) or equally spaced (n by 2n) in latitude and longitude. All grids use geocentric coordinates, the output is in SI units, and the sign of the radial components is positive when directed upwards. If the optional angular rotation rate omega is specified in the SHGravCoeffs instance, the potential and radial gravitational acceleration will be calculated in a body-fixed rotating reference frame. If normal_gravity is set to True, the normal gravity will be removed from the total field, yielding the gravity disturbance. The gravitational potential is given by V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, and the gravitational acceleration is B = Grad V. The coefficients are referenced to the radius r0, and the function is computed on a flattened ellipsoid with semi-major axis a (i.e., the mean equatorial radius) and flattening f. To convert m/s^2 to mGals, multiply the gravity grids by 10^5.
[ "Create", "2D", "cylindrical", "maps", "on", "a", "flattened", "and", "rotating", "ellipsoid", "of", "all", "three", "components", "of", "the", "gravity", "field", "the", "gravity", "disturbance", "and", "the", "gravitational", "potential", "and", "return", "as"...
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L1615-L1706
train
203,894
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravcoeffs.py
SHGravCoeffs.tensor
def tensor(self, a=None, f=None, lmax=None, lmax_calc=None, degree0=False, sampling=2): """ Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the gravity "gradient" tensor in a local north-oriented reference frame, and return an SHGravTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHGravTensor class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. degree0 : optional, default = False If True, include the degree-0 term when calculating the tensor. If False, set the degree-0 term to zero. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps for the 9 components of the gravity 'gradient' tensor and return an SHGravTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The gravitational potential is defined as V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the gravitational acceleration is B = Grad V. The components of the gravity tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of Eotvos (10^-9 s^-2). References ---------- Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006. """ if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) if degree0 is False: coeffs[0, 0, 0] = 0. vxx, vyy, vzz, vxy, vxz, vyz = _MakeGravGradGridDH( coeffs, self.gm, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHGravTensor(1.e9*vxx, 1.e9*vyy, 1.e9*vzz, 1.e9*vxy, 1.e9*vxz, 1.e9*vyz, self.gm, a, f, lmax, lmax_calc)
python
def tensor(self, a=None, f=None, lmax=None, lmax_calc=None, degree0=False, sampling=2): """ Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the gravity "gradient" tensor in a local north-oriented reference frame, and return an SHGravTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHGravTensor class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. degree0 : optional, default = False If True, include the degree-0 term when calculating the tensor. If False, set the degree-0 term to zero. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps for the 9 components of the gravity 'gradient' tensor and return an SHGravTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The gravitational potential is defined as V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the gravitational acceleration is B = Grad V. The components of the gravity tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of Eotvos (10^-9 s^-2). References ---------- Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006. """ if a is None: a = self.r0 if f is None: f = 0. if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) if degree0 is False: coeffs[0, 0, 0] = 0. vxx, vyy, vzz, vxy, vxz, vyz = _MakeGravGradGridDH( coeffs, self.gm, self.r0, a=a, f=f, lmax=lmax, lmax_calc=lmax_calc, sampling=sampling) return _SHGravTensor(1.e9*vxx, 1.e9*vyy, 1.e9*vzz, 1.e9*vxy, 1.e9*vxz, 1.e9*vyz, self.gm, a, f, lmax, lmax_calc)
[ "def", "tensor", "(", "self", ",", "a", "=", "None", ",", "f", "=", "None", ",", "lmax", "=", "None", ",", "lmax_calc", "=", "None", ",", "degree0", "=", "False", ",", "sampling", "=", "2", ")", ":", "if", "a", "is", "None", ":", "a", "=", "s...
Create 2D cylindrical maps on a flattened ellipsoid of the 9 components of the gravity "gradient" tensor in a local north-oriented reference frame, and return an SHGravTensor class instance. Usage ----- tensor = x.tensor([a, f, lmax, lmax_calc, sampling]) Returns ------- tensor : SHGravTensor class instance. Parameters ---------- a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grids, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. degree0 : optional, default = False If True, include the degree-0 term when calculating the tensor. If False, set the degree-0 term to zero. sampling : optional, integer, default = 2 If 1 the output grids are equally sampled (n by n). If 2 (default), the grids are equally spaced in degrees (n by 2n). Description ----------- This method will create 2-dimensional cylindrical maps for the 9 components of the gravity 'gradient' tensor and return an SHGravTensor class instance. The components are (Vxx, Vxy, Vxz) (Vyx, Vyy, Vyz) (Vzx, Vzy, Vzz) where the reference frame is north-oriented, where x points north, y points west, and z points upward (all tangent or perpendicular to a sphere of radius r, where r is the local radius of the flattened ellipsoid). The gravitational potential is defined as V = GM/r Sum_{l=0}^lmax (r0/r)^l Sum_{m=-l}^l C_{lm} Y_{lm}, where r0 is the reference radius of the spherical harmonic coefficients Clm, and the gravitational acceleration is B = Grad V. The components of the gravity tensor are calculated according to eq. 1 in Petrovskaya and Vershkov (2006), which is based on eq. 3.28 in Reed (1973) (noting that Reed's equations are in terms of latitude and that the y axis points east): Vzz = Vrr Vxx = 1/r Vr + 1/r^2 Vtt Vyy = 1/r Vr + 1/r^2 /tan(t) Vt + 1/r^2 /sin(t)^2 Vpp Vxy = 1/r^2 /sin(t) Vtp - cos(t)/sin(t)^2 /r^2 Vp Vxz = 1/r^2 Vt - 1/r Vrt Vyz = 1/r^2 /sin(t) Vp - 1/r /sin(t) Vrp where r, t, p stand for radius, theta, and phi, respectively, and subscripts on V denote partial derivatives. The output grids are in units of Eotvos (10^-9 s^-2). References ---------- Reed, G.B., Application of kinematical geodesy for determining the short wave length components of the gravity field by satellite gradiometry, Ohio State University, Dept. of Geod. Sciences, Rep. No. 201, Columbus, Ohio, 1973. Petrovskaya, M.S. and A.N. Vershkov, Non-singular expressions for the gravity gradients in the local north-oriented and orbital reference frames, J. Geod., 80, 117-127, 2006.
[ "Create", "2D", "cylindrical", "maps", "on", "a", "flattened", "ellipsoid", "of", "the", "9", "components", "of", "the", "gravity", "gradient", "tensor", "in", "a", "local", "north", "-", "oriented", "reference", "frame", "and", "return", "an", "SHGravTensor",...
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L1708-L1815
train
203,895
SHTOOLS/SHTOOLS
pyshtools/shclasses/shgravcoeffs.py
SHGravCoeffs.geoid
def geoid(self, potref, a=None, f=None, r=None, omega=None, order=2, lmax=None, lmax_calc=None, grid='DH2'): """ Create a global map of the height of the geoid and return an SHGeoid class instance. Usage ----- geoid = x.geoid(potref, [a, f, r, omega, order, lmax, lmax_calc, grid]) Returns ------- geoid : SHGeoid class instance. Parameters ---------- potref : float The value of the potential on the chosen geoid, in m2 / s2. a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. r : optional, float, default = self.r0 The radius of the reference sphere that the Taylor expansion of the potential is calculated on. order : optional, integer, default = 2 The order of the Taylor series expansion of the potential about the reference radius r. This can be either 1, 2, or 3. omega : optional, float, default = self.omega The angular rotation rate of the planet. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grid, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, or 'DH2' for an equidistant lat/lon grid with nlon=2*nlat. Description ----------- This method will create a global map of the geoid height, accurate to either first, second, or third order, using the method described in Wieczorek (2007; equation 19-20). The algorithm expands the potential in a Taylor series on a spherical interface of radius r, and computes the height above this interface to the potential potref exactly from the linear, quadratic, or cubic equation at each grid point. If the optional parameters a and f are specified, the geoid height will be referenced to a flattened ellipsoid with semi-major axis a and flattening f. The pseudo-rotational potential is explicitly accounted for by using the angular rotation rate omega of the planet in the SHGravCoeffs class instance. If omega is explicitly specified for this method, it will override the value present in the class instance. Reference ---------- Wieczorek, M. A. Gravity and topography of the terrestrial planets, Treatise on Geophysics, 10, 165-206, 2007. """ if a is None: a = self.r0 if f is None: f = 0. if r is None: r = self.r0 if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if grid.upper() in ('DH', 'DH1'): sampling = 1 elif grid.upper() == 'DH2': sampling = 2 else: raise ValueError( "grid must be 'DH', 'DH1', or 'DH2'. " "Input value was {:s}".format(repr(grid))) if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) if omega is None: omega = self.omega geoid = _MakeGeoidGridDH(coeffs, self.r0, self.gm, potref, lmax=lmax, omega=omega, r=r, order=order, lmax_calc=lmax_calc, a=a, f=f, sampling=sampling) return _SHGeoid(geoid, self.gm, potref, a, f, omega, r, order, lmax, lmax_calc)
python
def geoid(self, potref, a=None, f=None, r=None, omega=None, order=2, lmax=None, lmax_calc=None, grid='DH2'): """ Create a global map of the height of the geoid and return an SHGeoid class instance. Usage ----- geoid = x.geoid(potref, [a, f, r, omega, order, lmax, lmax_calc, grid]) Returns ------- geoid : SHGeoid class instance. Parameters ---------- potref : float The value of the potential on the chosen geoid, in m2 / s2. a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. r : optional, float, default = self.r0 The radius of the reference sphere that the Taylor expansion of the potential is calculated on. order : optional, integer, default = 2 The order of the Taylor series expansion of the potential about the reference radius r. This can be either 1, 2, or 3. omega : optional, float, default = self.omega The angular rotation rate of the planet. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grid, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, or 'DH2' for an equidistant lat/lon grid with nlon=2*nlat. Description ----------- This method will create a global map of the geoid height, accurate to either first, second, or third order, using the method described in Wieczorek (2007; equation 19-20). The algorithm expands the potential in a Taylor series on a spherical interface of radius r, and computes the height above this interface to the potential potref exactly from the linear, quadratic, or cubic equation at each grid point. If the optional parameters a and f are specified, the geoid height will be referenced to a flattened ellipsoid with semi-major axis a and flattening f. The pseudo-rotational potential is explicitly accounted for by using the angular rotation rate omega of the planet in the SHGravCoeffs class instance. If omega is explicitly specified for this method, it will override the value present in the class instance. Reference ---------- Wieczorek, M. A. Gravity and topography of the terrestrial planets, Treatise on Geophysics, 10, 165-206, 2007. """ if a is None: a = self.r0 if f is None: f = 0. if r is None: r = self.r0 if lmax is None: lmax = self.lmax if lmax_calc is None: lmax_calc = lmax if grid.upper() in ('DH', 'DH1'): sampling = 1 elif grid.upper() == 'DH2': sampling = 2 else: raise ValueError( "grid must be 'DH', 'DH1', or 'DH2'. " "Input value was {:s}".format(repr(grid))) if self.errors is not None: coeffs, errors = self.to_array(normalization='4pi', csphase=1) else: coeffs = self.to_array(normalization='4pi', csphase=1) if omega is None: omega = self.omega geoid = _MakeGeoidGridDH(coeffs, self.r0, self.gm, potref, lmax=lmax, omega=omega, r=r, order=order, lmax_calc=lmax_calc, a=a, f=f, sampling=sampling) return _SHGeoid(geoid, self.gm, potref, a, f, omega, r, order, lmax, lmax_calc)
[ "def", "geoid", "(", "self", ",", "potref", ",", "a", "=", "None", ",", "f", "=", "None", ",", "r", "=", "None", ",", "omega", "=", "None", ",", "order", "=", "2", ",", "lmax", "=", "None", ",", "lmax_calc", "=", "None", ",", "grid", "=", "'D...
Create a global map of the height of the geoid and return an SHGeoid class instance. Usage ----- geoid = x.geoid(potref, [a, f, r, omega, order, lmax, lmax_calc, grid]) Returns ------- geoid : SHGeoid class instance. Parameters ---------- potref : float The value of the potential on the chosen geoid, in m2 / s2. a : optional, float, default = self.r0 The semi-major axis of the flattened ellipsoid on which the field is computed. f : optional, float, default = 0 The flattening of the reference ellipsoid: f=(a-b)/a. r : optional, float, default = self.r0 The radius of the reference sphere that the Taylor expansion of the potential is calculated on. order : optional, integer, default = 2 The order of the Taylor series expansion of the potential about the reference radius r. This can be either 1, 2, or 3. omega : optional, float, default = self.omega The angular rotation rate of the planet. lmax : optional, integer, default = self.lmax The maximum spherical harmonic degree that determines the number of samples of the output grid, n=2lmax+2, and the latitudinal sampling interval, 90/(lmax+1). lmax_calc : optional, integer, default = lmax The maximum spherical harmonic degree used in evaluating the functions. This must be less than or equal to lmax. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, or 'DH2' for an equidistant lat/lon grid with nlon=2*nlat. Description ----------- This method will create a global map of the geoid height, accurate to either first, second, or third order, using the method described in Wieczorek (2007; equation 19-20). The algorithm expands the potential in a Taylor series on a spherical interface of radius r, and computes the height above this interface to the potential potref exactly from the linear, quadratic, or cubic equation at each grid point. If the optional parameters a and f are specified, the geoid height will be referenced to a flattened ellipsoid with semi-major axis a and flattening f. The pseudo-rotational potential is explicitly accounted for by using the angular rotation rate omega of the planet in the SHGravCoeffs class instance. If omega is explicitly specified for this method, it will override the value present in the class instance. Reference ---------- Wieczorek, M. A. Gravity and topography of the terrestrial planets, Treatise on Geophysics, 10, 165-206, 2007.
[ "Create", "a", "global", "map", "of", "the", "height", "of", "the", "geoid", "and", "return", "an", "SHGeoid", "class", "instance", "." ]
9a115cf83002df2ddec6b7f41aeb6be688e285de
https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L1817-L1913
train
203,896
toidi/hadoop-yarn-api-python-client
yarn_api_client/node_manager.py
NodeManager.node_application
def node_application(self, application_id): """ An application resource contains information about a particular application that was run or is running on this NodeManager. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """ path = '/ws/v1/node/apps/{appid}'.format(appid=application_id) return self.request(path)
python
def node_application(self, application_id): """ An application resource contains information about a particular application that was run or is running on this NodeManager. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """ path = '/ws/v1/node/apps/{appid}'.format(appid=application_id) return self.request(path)
[ "def", "node_application", "(", "self", ",", "application_id", ")", ":", "path", "=", "'/ws/v1/node/apps/{appid}'", ".", "format", "(", "appid", "=", "application_id", ")", "return", "self", ".", "request", "(", "path", ")" ]
An application resource contains information about a particular application that was run or is running on this NodeManager. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
[ "An", "application", "resource", "contains", "information", "about", "a", "particular", "application", "that", "was", "run", "or", "is", "running", "on", "this", "NodeManager", "." ]
d245bd41808879be6637acfd7460633c0c7dfdd6
https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/node_manager.py#L58-L69
train
203,897
toidi/hadoop-yarn-api-python-client
yarn_api_client/node_manager.py
NodeManager.node_container
def node_container(self, container_id): """ A container resource contains information about a particular container that is running on this NodeManager. :param str container_id: The container id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """ path = '/ws/v1/node/containers/{containerid}'.format( containerid=container_id) return self.request(path)
python
def node_container(self, container_id): """ A container resource contains information about a particular container that is running on this NodeManager. :param str container_id: The container id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """ path = '/ws/v1/node/containers/{containerid}'.format( containerid=container_id) return self.request(path)
[ "def", "node_container", "(", "self", ",", "container_id", ")", ":", "path", "=", "'/ws/v1/node/containers/{containerid}'", ".", "format", "(", "containerid", "=", "container_id", ")", "return", "self", ".", "request", "(", "path", ")" ]
A container resource contains information about a particular container that is running on this NodeManager. :param str container_id: The container id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
[ "A", "container", "resource", "contains", "information", "about", "a", "particular", "container", "that", "is", "running", "on", "this", "NodeManager", "." ]
d245bd41808879be6637acfd7460633c0c7dfdd6
https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/node_manager.py#L83-L95
train
203,898
toidi/hadoop-yarn-api-python-client
yarn_api_client/resource_manager.py
ResourceManager.cluster_application_statistics
def cluster_application_statistics(self, state_list=None, application_type_list=None): """ With the Application Statistics API, you can obtain a collection of triples, each of which contains the application type, the application state and the number of applications of this type and this state in ResourceManager context. This method work in Hadoop > 2.0.0 :param list state_list: states of the applications, specified as a comma-separated list. If states is not provided, the API will enumerate all application states and return the counts of them. :param list application_type_list: types of the applications, specified as a comma-separated list. If application_types is not provided, the API will count the applications of any application type. In this case, the response shows * to indicate any application type. Note that we only support at most one applicationType temporarily. Otherwise, users will expect an BadRequestException. :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """ path = '/ws/v1/cluster/appstatistics' # TODO: validate state argument states = ','.join(state_list) if state_list is not None else None if application_type_list is not None: application_types = ','.join(application_type_list) else: application_types = None loc_args = ( ('states', states), ('applicationTypes', application_types)) params = self.construct_parameters(loc_args) return self.request(path, **params)
python
def cluster_application_statistics(self, state_list=None, application_type_list=None): """ With the Application Statistics API, you can obtain a collection of triples, each of which contains the application type, the application state and the number of applications of this type and this state in ResourceManager context. This method work in Hadoop > 2.0.0 :param list state_list: states of the applications, specified as a comma-separated list. If states is not provided, the API will enumerate all application states and return the counts of them. :param list application_type_list: types of the applications, specified as a comma-separated list. If application_types is not provided, the API will count the applications of any application type. In this case, the response shows * to indicate any application type. Note that we only support at most one applicationType temporarily. Otherwise, users will expect an BadRequestException. :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response` """ path = '/ws/v1/cluster/appstatistics' # TODO: validate state argument states = ','.join(state_list) if state_list is not None else None if application_type_list is not None: application_types = ','.join(application_type_list) else: application_types = None loc_args = ( ('states', states), ('applicationTypes', application_types)) params = self.construct_parameters(loc_args) return self.request(path, **params)
[ "def", "cluster_application_statistics", "(", "self", ",", "state_list", "=", "None", ",", "application_type_list", "=", "None", ")", ":", "path", "=", "'/ws/v1/cluster/appstatistics'", "# TODO: validate state argument", "states", "=", "','", ".", "join", "(", "state_...
With the Application Statistics API, you can obtain a collection of triples, each of which contains the application type, the application state and the number of applications of this type and this state in ResourceManager context. This method work in Hadoop > 2.0.0 :param list state_list: states of the applications, specified as a comma-separated list. If states is not provided, the API will enumerate all application states and return the counts of them. :param list application_type_list: types of the applications, specified as a comma-separated list. If application_types is not provided, the API will count the applications of any application type. In this case, the response shows * to indicate any application type. Note that we only support at most one applicationType temporarily. Otherwise, users will expect an BadRequestException. :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
[ "With", "the", "Application", "Statistics", "API", "you", "can", "obtain", "a", "collection", "of", "triples", "each", "of", "which", "contains", "the", "application", "type", "the", "application", "state", "and", "the", "number", "of", "applications", "of", "...
d245bd41808879be6637acfd7460633c0c7dfdd6
https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L122-L159
train
203,899