pyharm.shc#
Module to work with spherical harmonic coefficients. Defines the Shc
class, including its methods that are designed to:
read/write spherical harmonic coefficients,
perform basic arithmetic operations with spherical harmonic coefficients such as addition, etc.,
rescale spherical harmonic coefficients, and
compute (difference) degree variances and amplitudes.
Note
This documentation is written for double precision version of PyHarm.
- pyharm.shc.WRITE_N: int = 0#
Ordering scheme to write spherical harmonic coefficients with the
pyharm.shc.Shc.to_file()method: harmonic degree varies fastest.- Type:
int
- pyharm.shc.WRITE_M: int = 1#
Ordering scheme to write spherical harmonic coefficients with the
pyharm.shc.Shc.to_file()method: harmonic order varies fastest.- Type:
int
- class pyharm.shc.Shc(nmax, mu, r, method)#
Class for spherical harmonic coefficients.
To create an
Shcclass instance, always use one of the following factory methods:Examples
>>> import pyharm as ph >>> shcs = ph.shc.Shc.from_garbage(10)
- Parameters:
nmax (integer) – Maximum spherical harmonic degree
mu (floating point) – Scaling parameter (not used with
from_copy())r (floating point) – Radius of the reference sphere (not used with
from_copy())method (None, 0 or tuple) –
Determines the way of initializing spherical harmonic coefficients:
Noneto not initialize spherical harmonic coefficients (mallocin C),0to set all spherical harmonic coefficients to zero (callocin C),(c, s)to define spherical harmonic coefficients based on two numpy floating point arrayscands, each of shape(((nmax + 2) * (nmax + 1)) // 2,). For ordering scheme of the coefficients in thecandsarrays, see thecandsproperties,(shcs, nmin, nmax)to create a copy of spherical harmonic coefficients inshcsstarting at degreenminand ending at degreenmax.
- property nmax#
Maximum harmonic degree of the spherical harmonic coefficients.
- property mu#
Scaling parameter \(\mu\) associated with the spherical harmonic coefficients, for instance, the geocentric gravitational constant. In case the coefficients are not associated with any scaling parameter (as it is, for instance, with planetary topographies), simply set this variable to
1.0(not to0.0!).
- property r#
Radius of the reference sphere \(R\), to which the spherical harmonic coefficients refer (are scaled). The value must be greater than zero. To get the unit sphere, as needed, for instance, when working with planetary topographies, set this variable to
1.0.
- property c#
The \(\bar{C}_{nm}\) spherical harmonic coefficients. A numpy array with the shape (((
nmax+ 2) * (nmax+ 1)) / 2,) and the array structure \(\bar{C}_{00}\), \(\bar{C}_{10}\), …, \(\bar{C}_{\mathrm{nmax},0}\), \(\bar{C}_{1,1}\), …, \(\bar{C}_{\mathrm{nmax},\mathrm{nmax}}\).
- property owner#
If
True, the memory associated with spherical harmonic coefficients is owned by CHarm and therefore it is automatically deallocated by CHarm when the user deletesShcclass instances or when the instances get out of scope, etc. Theownerattribute isTrueforShcinstances returned by all factory methods except for thefrom_arrays()method.Examples
>>> import pyharm as ph >>> shcs = ph.shc.Shc.from_garbage(10) >>> del shcs # Deletes "shcs" and properly deallocates all memory >>> # that is associated with "shcs"
If
False, neither CHarm nor PyHarm own the memory so neither CHarm nor PyHarm will ever deallocate it. This is the case ofShcclass instances returned by thefrom_arrays()factory method. This method buildsShcinstances from user-owned external numpy arrays, so it is the responsibility of the user to delete the original arrays (if needed) once theShcclass instance is deleted or got out of scope, etc.Examples
>>> import numpy as np >>> import pyharm as ph >>> nmax = 10 >>> ncs = ((nmax + 2) * (nmax + 1)) // 2 >>> c = np.random.randn(ncs) >>> s = np.random.randn(ncs) >>> shcs = ph.shc.Shc.from_arrays(nmax, c, s) >>> del shcs # Deletes "shcs" but not the original "c" and "s" arrays >>> # Here, you can still work with "c" and "s" >>> del c, s # Finally, release the memory associated with "c" and >>> # "s" if needed
- classmethod from_garbage(nmax, mu=np.float64(1.0), r=np.float64(1.0))#
Returns an
Shcclass instance with uninitialized spherical harmonic coefficients (mallocin C).
- classmethod from_zeros(nmax, mu=np.float64(1.0), r=np.float64(1.0))#
Returns an
Shcclass instance with all spherical harmonic coefficients initialized to zero (callocin C).
- classmethod from_arrays(nmax, c, s, mu=np.float64(1.0), r=np.float64(1.0))#
Returns an
Shcclass instance with spherical harmonic coefficients copied from thecandsinput arrays. The copy is shallow, meaning that thecandsattributes of the returnedShcclass instance share the memory space with the inputcandsarrays.- Parameters:
nmax (integer) – Maximum spherical harmonic degree
c (numpy array of floating points) – Spherical harmonic coefficients \(\bar{C}_{nm}\). For details on the structure of the array, see
c.s (numpy array of floating points) – Spherical harmonic coefficients \(\bar{S}_{nm}\). For details on the structure of the array, see
s.mu (floating point) – Scaling parameter, optional. Default is
1.0.r (floating point) – Radius of the reference sphere, optional. Default is
1.0.
- Returns:
out – An
Shcclass instance- Return type:
- classmethod from_copy(shcs, nmin=0, nmax=None, nmax_shcs_out=None)#
Creates a copy of spherical harmonic coefficients from
shcsstarting at degreenminand ending at degreenmax. The output class instance is allocated up to degreenmax_shcs_out, with all coefficients outside the rangenmintonmaxbeing zero.The following restrictions apply:
nminandnmaxmust both be smaller than or equal toshcs.nmax,nmaxcannot be smaller thannmin,nmin_shcs_outcannot be smaller thannmax,
- Parameters:
shcs (Shc) – Spherical harmonic coefficients to be copied.
nmin (integer) – Degree, at which the copying starts. Default is
0.nmax (integer) – Degree, at which the copying ends. Default is
None, which is here an alias forshcs.nmax.nmax_shcs_out (integer) – Maximum degree of the returned
Shcinstance. Default isNone, which is here an alias forshcs.nmax.
- Returns:
out – A copy of
shcs.- Return type:
- classmethod from_file(file_type, pathname, nmax=-1, epoch=None, encoding='utf-8')#
Reads spherical harmonic coefficients up to degree
nmaxfrom thepathnamefile of a givenfile_type. For time variable models stored in thegfcfile type,epochadditionally transforms the coefficients to a given epoch.Tip
To get the maximum harmonic degree stored in
pathname, usenmax_from_file().Tip
To print all supported file types, use
get_file_types():>>> import pyharm as ph >>> ph.shc.Shc.get_file_types()
For the structure of the file types, refer to charm_shc.
- Parameters:
file_type (str) – Type of the input file
pathname (str) – Input file path
nmax (integer) – Maximum harmonic degree to read the spherical harmonic coefficients. If negative, all coefficients are read. Default value is
-1.epoch (str) –
Epoch, to which spherical harmonic coefficients from
gfcfile types are transformed in case of time variable gravity field models; optional. For the structure of the string, refer to charm_shc. This input parameter is used only iffile_typeisgfc. Default value isNone.encoding (str) –
Encoding of the
pathnameandepochstrings. In case you have special characters in yourpathnamestring, you may need to select proper encoding.The encoding does not apply to the content of the file. The file reading is done by CHarm, so the file content encoding depends on your operating system.
- Returns:
out – An
Shcclass instance- Return type:
- to_file(file_type, pathname, nmax=-1, formatting='%0.18e', ordering=0, encoding='utf-8')#
Writes an
Shcclass instance up to degreenmaxto a filepathnameof a givenfile_type. Iffile_typerepresents a text file (dov,tblormtx),formattingspecifies the formatting for all floating point numbers. Iffile_typeisdovortbl,orderingdefines the ordering of spherical harmonic coefficients in the output file.Tip
To print all supported file types, use
get_file_types():>>> import pyharm as ph >>> ph.shc.Shc.get_file_types()
For the structure of the file types, refer to charm_shc.
- Parameters:
file_type (str) – Type of the input file
nmax (integer) – Maximum harmonic degree to write the spherical harmonic coefficients. If negative, all coefficients are written. Default value is
-1.pathname (str) – Output file path
formatting (str) – Formatting to write floating point numbers to text formats, optional. Default is
'%0.18e'.ordering (integer) – Scheme to sort spherical harmonic coefficients when
file_typeisdovortbl, optional. Accepted values arepyharm.shc.WRITE_Nandpyharm.shc.WRITE_M. Default ispyharm.shc.WRITE_N.encoding (str) –
Encoding of the
pathnameandformattingstrings. In case you have special characters in yourpathnamestring, you may need to select proper encoding.The encoding does not apply to the content of the file. The file writting is done by CHarm, so the file content encoding depends on your operating system.
- add(op2, nmin=0, nmax=None, inplace=True)#
Adds spherical harmonic coefficients of matching degrees and orders from
op2starting at degreenminand ending at degreenmax.Whenever user asks to perform an addition beyond the object’s degree
nmaxorop2.nmax, the non-existing coefficients are zero padded. For the full documentation, refer to charm_shc.Tip
To learn how
add()works, go thorough the following examples:>>> import pyharm as ph >>> import numpy as np >>> # Generate two instances of the "Shc" class with random >>> # coefficients >>> op1 = ph.shc.Shc.from_arrays(nmax=5, >>> c=np.random.randn(21), >>> s=np.random.randn(21)) >>> op2 = ph.shc.Shc.from_arrays(nmax=3, >>> c=np.random.randn(10), >>> s=np.random.randn(10)) >>> op1.add(op2) # In-place addition "op1 = op1 + op2". As >>> # the truncation degrees of "op1" and "op2" >>> # do not match, this command zero pads "op2" >>> # to degree "op1.nmax = 5" during the >>> # addition. The coefficients of "op1" are >>> # rewritten by the result of the addition. >>> op2.add(op1) # The addition is now performed only up to >>> # degree "op2.nmax = 3", as the truncation >>> # degree of the object, to which we add >>> # "op1", can store coefficients only to >>> # "op2.nmax = 3". >>> op1.add(op2, nmax=2) # In-place addition up to degree >>> # 2. Rewrites "op1", but only up >>> # to degree 2. >>> op1.add(op2, nmin=1, nmax=4) # In-place addition from >>> # degree 1 to degree 4. The >>> # coefficients of "op2" are >>> # zero-padded beyond degree >>> # 3. "op1" is rewritten due >>> # to the in-place addition, >>> # but only from degree 1 to >>> # degree 5. >>> op1.add(op1) # In-place addition "op1 + op1" up to degree >>> # "op1.nmax". >>> rop = op1.add(op2, inplace=False) # Out-of-place addition >>> # "rop = op1 + op2". >>> # The output "rop" is >>> # a new "Shc" instance >>> # with truncation >>> # degree "rop.nmax" >>> # being "max(op1.nmax, >>> # op2.nmax)". >>> # "op1" remains >>> # unmodified and "op2" >>> # is zero padded during >>> # the addition.
Tip
You can use
>>> rop = op1 + op2
as a useful alias for
>>> rop = op1.add(op2, inplace=False)
and
>>> op1 += op2
as an alias for
>>> op1.add(op2)
Importantly, however,
>>> op1 = op1 + op2
is generally not the same as
>>> op1 += op2
as the former rewrites
op1by returning a newShcclass instance calledop1with the truncation degree beingmax(op1.nmax, op2.nmax), while the latter updatesop1by adding the coefficients ofop2up to degreeop1.nmax(see the other tip).- Parameters:
op2 (Shc) – The second operand of the addition. The first operand is always
self.nmin (integer) – Spherical harmonic degree, at which the addition starts. Default is
0.nmax (integer) – Spherical harmonic degree, at which the addition ends. Default is
None, which is here an alias either for the object’snmaxattribute ifinplaceisTrueor for the largest ofnmaxandop2.nmaxifinplaceisFalse.inplace (bool) – Performs the addition in-place if
True(rewrites the coefficients ofself, no return) and out-of-place ifFalse(selfremains untouched, returnsShc).
- Returns:
None or out
- Return type:
Noneif in-place,Shcif out-of-place.
- sub(op2, nmin=0, nmax=None, inplace=True)#
The same as
add()but the coefficients ofop2are subtracted from the coefficients ofself.For the full documentation, refer to charm_shc.
- mul(op2, nmin=0, nmax=None, inplace=True)#
The same as
add()but the coefficients ofop2are multiplied by the coefficients ofself.For the full documentation, refer to charm_shc.
Note
Multiplying coefficients of matching degrees and orders from
selfandop2in the spectral domain is not equivalent to the multiplication the functions given byselfandop2in the spatial domain.
- mul_degree_wise(a, nmin=0, nmax=None)#
Multiplies spherical harmonic coefficients by degree-dependent factors
astarting at degreenminand ending atnmax.All spherical harmonic coefficients of degree
nminare multiplied bya[0], all coefficients of degreenmin + 1are multiplied bya[1]and so on.- Parameters:
a (numpy array of floating points) – Array of the degree-dependent factors. The size of
amust benmax - nmin + 1. Thea[0]element represents the multiplier for all coefficients of degreenmin,a[1]holds the multiplier for all coefficients of degreenmin + 1, etc.nmin (integer) – Spherical harmonic degree, at which the multiplication starts. Default is
0.nmax (integer) – Spherical harmonic degree, at which the multiplication ends. Default is
None, which is here an alias for the object’snmaxattribute.
- mul_order_wise(a, nmin=0, nmax=None)#
Multiplies spherical harmonic coefficients by order-dependent factors
astarting at degreenminand ending atnmax.- Parameters:
a (numpy array of floating points) – Array of the order-dependent factors. The size of
amust benmax + 1. Thea[0]element represents the multiplier for all coefficients of order0within degrees fromnmintonmax,a[1]holds the multiplier for all coefficients of order1within degrees fromnmintonmax, etc.,a[nmax]is the multiplier for coefficients of ordernmax.nmin (integer) – Spherical harmonic degree, at which the multiplication starts. Default is
0.nmax (integer) – Spherical harmonic degree, at which the multiplication ends. Default is
None, which is here an alias for the object’snmaxattribute.
- div(op2, nmin=0, nmax=None, inplace=True)#
The same as
add()but the coefficients ofop2are divided by the coefficients ofself.For the full documentation, refer to charm_shc.
Note
Dividing coefficients of matching degrees and orders from
selfandop2in the spectral domain is not equivalent to the division of the functions given byselfandop2in the spatial domain.
- div_degree_wise(a, nmin=0, nmax=None)#
The same as
mul_degree_wise(), but the coefficients are divided by the degree-dependent factor.
- div_order_wise(a, nmin=0, nmax=None)#
The same as
mul_order_wise(), but the coefficients are divided by the order-dependent factor.
- static get_file_types()#
Prints all file types supported by the
to_file()andfrom_file()methods of theShcclass.
- static nmax_from_file(file_type, pathname, encoding='utf-8')#
Returns the maximum harmonic degree of coefficients stored in the
pathnamefile that is of a givenfile_type.Tip
To print all supported file types, use
get_file_types():>>> import pyharm as ph >>> ph.shc.Shc.get_file_types()
For the structure of the file types, refer to charm_shc.
- Parameters:
file_type (str) – Type of the input file
pathname (str) – Input file path
encoding (str) –
Encoding of the
pathnamestring. In case you have special characters in yourpathnamestring, you may need to select proper encoding.The encoding does not apply to the content of the input file. The file reading is done by CHarm, so the file content encoding depends on your operating system.
- Returns:
out – Maximum harmonic degree of the model
- Return type:
integer
- get_coeffs(n=None, m=None)#
Returns spherical harmonic coefficients \(\bar{C}_{nm}\) and \(\bar{S}_{nm}\) of degree
nand orderm. If the returned variables are arrays, they are deep copies, meaning that they have their own memory space.The behaviour of the method depends on the type of the input variables
nandm.If both
nandmare integers, returned are two spherical harmonic coefficients \(\bar{C}_{nm}\) and \(\bar{S}_{nm}\), each of degreenand orderm. The two returned values are floating points.If
nis integer andmisNone, returned are two arrays of spherical harmonic coefficients \(\bar{C}_{nm}\) and \(\bar{S}_{nm}\) of degreenand all corresponding ordersm = 0, 1, ..., n.If
nisNoneandmis integer, returned are two arrays of spherical harmonic coefficients \(\bar{C}_{nm}\) and \(\bar{S}_{nm}\) of ordermand all corresponding degreesn = m, m + 1, ..., self.nmax.If
nandmare lists of equal size, returned are two arrays of spherical harmonic coefficients \(\bar{C}_{nm}\) and \(\bar{S}_{nm}\) of degrees taken from thenlist and orders taken from themlist.If
nandmare bothNone(default), returned are all spherical harmonic coefficients stored by the object, that is, copies of thecandsarrays. The coefficients in the output arrays are ordered as reported byget_degrees_orders().
Note
When the method returns numpy arrays, the output arrays are always deep copies of the original spherical harmonic coefficients.
Examples
>>> import numpy as np >>> import pyharm as ph >>> nmax = 10 >>> ncs = ((nmax + 2) * (nmax + 1)) // 2 >>> c = np.random.randn(ncs) >>> s = np.random.randn(ncs) >>> shcs = ph.shc.Shc.from_arrays(nmax, c, s) >>> shcs.get_coeffs(3, 2) # Returns "C3,2" and "S3,2" >>> shcs.get_coeffs(n=3) # Returns "C3,0", "C3,1", "C3,2", "C3,3" and >>> # "S3,0", "S3,1", "S3,2", "S3,3" >>> shcs.get_coeffs(m=8) # Returns "C8,8", "C9,8", "C10,8" and >>> # "S8,8", "S9,8", "S10,8" >>> n = [3, 5, 6] >>> m = [2, 4, 6] >>> shcs.get_coeffs(n, m) # Returns "C3,2", "C5,4", "C6,6" and "S3,2", >>> # "S5,4", "S6,6" >>> shcs.get_coeffs() # Returns all coefficients stored in "shcs"
- Parameters:
n (integer, list of integers, None) – Spherical harmonic degree, optional.
m (integer, list of integers, None) – Spherical harmonic order, optional.
- Returns:
c (floating point, numpy array of floating points) – Spherical harmonic coefficient(s) \(\bar{C}_{nm}\) of degree
nand orderms (floating point, numpy array of floating points) – The same as
cbut with the \(\bar{S}_{nm}\) coefficient(s)
- set_coeffs(n=None, m=None, c=None, s=None)#
Sets spherical harmonic coefficients \(\bar{C}_{nm}\) and \(\bar{S}_{nm}\) of degree
nand ordermto the values ofcands, respectively.If both
nandmare integers, sets the spherical harmonic coefficients \(\bar{C}_{nm}\) and/or \(\bar{S}_{nm}\) to the input parameterscand/ors, respectively.candsmust be floating point scalars.If
nis integer andmisNone, sets spherical harmonic coefficients of degreenand all corresponding harmonic ordersm = 0, 1, ..., nto the input parameterscand/ors.candsmust be numpy floating point arrays of shapes(n + 1,).If
nisNoneandmis integer, sets spherical harmonic coefficients of ordermand all corresponding harmonic degreesn = m, m + 1, ..., self.nmaxto the input parameterscand/ors.candsmust be numpy floating point arrays of shapes(self.nmax + 1 - m,).If
nandmare lists of equal size, sets spherical spherical harmonic coefficients of degrees and orders taken from thenandmlists, respectively, to the corresponding values taken from the input parameterscand/ors. The length of the input parameters must match.If
nandmare bothNone, sets all coefficients incandstocands, respectively. The lengths of all arrays must match. The coefficients incandsmust be ordered as reported byget_degrees_orders().
Note
If the object’s
ownerattribute isFalse, then by setting the spherical harmonic coefficients you also modify the original arrays, from which theShcclass instance was derived.Examples
>>> import numpy as np >>> import pyharm as ph >>> nmax = 10 >>> ncs = ((nmax + 2) * (nmax + 1)) // 2 >>> c = np.random.randn(ncs) >>> s = np.random.randn(ncs) >>> shcs = ph.shc.Shc.from_arrays(nmax, c, s) >>> # Set "C3,2" and "S3,2" >>> shcs.set_coeffs(3, 2, 3.4, 1.3) >>> # Set "S3,2" >>> shcs.set_coeffs(3, 2, s=5.3) >>> # Set "C3,0", "C3,1", "C3,2", "C3,3" and "S3,0", "S3,1", "S3,2", >>> #"S3,3" >>> shcs.set_coeffs(n=3, c=np.array([1.1, 1.2, 1.3, 1.4]), >>> s=np.array([0.0, 1.2, 1.3, 1.4])) >>> # Set "C8,8", "C9,8", "C10,8" and "S8,8", "S9,8", "S10,8" >>> shcs.set_coeffs(m=8, c=np.array([1.1, 1.2, 1.3]), >>> s=np.array([1.1, 1.2, 1.3])) >>> # Set "C3,2", "C5,4", "C6,6" and "S3,2", "S5,4", "S6,6" >>> shcs.set_coeffs(n=[3, 5, 6], m=[2, 4, 6], >>> c=np.array([1.1, 1.2, 1.3]), >>> s=np.array([1.1, 1.2, 1.3])) >>> # Set all coefficients of "shcs" >>> cnew = np.random.randn(ncs) >>> snew = np.random.randn(ncs) >>> shcs.set_coeffs(c=cnew, s=snew)
- Parameters:
n (integer, list of integers, None) – Spherical harmonic degree, optional.
m (integer, list of integers, None) – Spherical harmonic order, optional.
c (floating point, numpy array of floating points, None) – Spherical harmonic coefficient(s) \(\bar{C}_{nm}\), optional.
s (floating point, numpy array of floating points, None) – Spherical harmonic coefficient(s) \(\bar{S}_{nm}\), optional.
- get_degrees_orders()#
Returns arrays of spherical harmonic degrees and orders matching the spherical harmonic coefficients stored in
cands.
- rescale(mu=None, r=None)#
Rescales spherical harmonic coefficients to a new scaling parameter
muand/or a new radius of the reference spherer.
- dv(nmax=None)#
Computes degree variances up to degree
nmax.- Parameters:
nmax (integer) – Maximum spherical harmonic degree to compute the degree variances, optional. Default is
None, which is here an alias for the object’snmaxattribute.- Returns:
out – A numpy floating point array with the degree variances
- Return type:
numpy array of floating points
- da(nmax=None)#
Computes degree amplitudes up to degree
nmax.- Parameters:
nmax (integer) – Maximum spherical harmonic degree to compute the degree amplitudes, optional. Default is
None, which is here an alias for the object’snmaxattribute.- Returns:
out – A numpy floating point array with the degree amplitudes
- Return type:
numpy array of floating points
- ddv(shcs, nmax=None)#
Computes difference degree variances with respect to
shcsup to degreenmax.- Parameters:
- Returns:
out – A numpy floating point array with the difference degree variances
- Return type:
numpy array of floating points
- dda(shcs, nmax=None)#
Computes difference degree amplitudes with respect to
shcsup to degreenmax.- Parameters:
- Returns:
out – A numpy floating point array with the difference degree amplitudes
- Return type:
numpy array of floating points