kaipy package
kaipy.cdaweb_utils module
- kaipy.cdaweb_utils.fetch_helio_spacecraft_HGS_trajectory(spacecraft, t_start, t_end, mjdc)
Fetches the HGS trajectory of a spacecraft in a time range.
Fetches the trajectory of a spacecraft in a time range, in the HGS frame. Data is fetched from CDAWeb.
- Parameters:
spacecraft (str) – CDAWeb-compliant spacecraft ID.
t_start (datetime.datetime) – Start datetime for trajectory fetch.
t_end (datetime.datetime) – End datetime for trajectory fetch.
- Returns:
Cartesian coordinates (x, y, z) of the spacecraft in the HGS frame.
- Return type:
Tuple[np.array, np.array, np.array]
- kaipy.cdaweb_utils.fetch_helio_spacecraft_trajectory(sc_id, t_start, t_end)
Fetches the trajectory of a spacecraft in a time range.
Fetches the trajectory of a spacecraft in a time range, in the default frame. Data is fetched from CDAWeb.
- Parameters:
spacecraft (str) – CDAWeb-compliant spacecraft ID.
t_start (datetime.datetime) – Start datetime for trajectory fetch.
t_end (datetime.datetime) – End datetime for trajectory fetch.
- Returns:
Cartesian coordinates (x, y, z) of the spacecraft in the HGS frame.
- Return type:
Tuple[np.array, np.array, np.array]
- kaipy.cdaweb_utils.fetch_satellite_SM_position(spacecraft, when)
Fetches the Solar Magnetic position of a satellite at a specified time.
Fetches the Solar Magnetic position of a satellite at a specified time, in SM cartesian coordinates. Data is fetched from CDAWeb. The first returned position is assumed to correspond to the requested value of “when”.
- Parameters:
spacecraft (str) – CDAWeb-compliant spacecraft ID.
when (datetime.datetime) – datetime for position fetch.
- Returns:
Cartesian SM coordinates of spacecraft (units of kilometers).
- Return type:
Tuple[float, float, float]
- kaipy.cdaweb_utils.fetch_satellite_geographic_position(spacecraft, when)
Fetch the geographic position of a satellite at a specified time.
Fetch the geographic position of a satellite at a specified time. Data is fetched from CDAWeb. The first returned position is assumed to correspond to the requested value of “when”.
- Parameters:
spacecraft (str) – CDAWeb-compliant spacecraft ID.
when (datetime.datetime) – datetime for position fetch.
- Returns:
Geographic longitude and latitude of spacecraft (degrees) and radius (km).
- Return type:
Tuple[float, float, float]
- kaipy.cdaweb_utils.fetch_satellite_magnetic_northern_footprint_position(spacecraft, when)
Fetch the position of the northern magnetic footprint.
Fetches the positions of the northern magnetic footprint for a spacecraft at a specified time. Data is fetched from CDAWeb. The first returned position is assumed to correspond to the requested value of “when”.
- Parameters:
spacecraft (str) – CDAWeb-compliant spacecraft ID.
when (datetime.datetime) – datetime for position fetch.
- Returns:
Geographic longitude and latitude (degrees) of northern magnetic footprint.
- Return type:
Tuple[float, float]
- kaipy.cdaweb_utils.fetch_satellite_magnetic_southern_footprint_position(spacecraft, when)
Fetch the position of the southern magnetic footprint.
Fetches the positions of the southern magnetic footprint for a spacecraft at a specified time. Data is fetched from CDAWeb. The first returned position is assumed to correspond to the requested value of “when”.
- Parameters:
spacecraft (str) – CDAWeb-compliant spacecraft ID.
when (datetime.datetime) – datetime for position fetch.
- Returns:
Geographic longitude and latitude (degrees) of southern magnetic footprint.
- Return type:
Tuple[float, float]
- kaipy.cdaweb_utils.fetch_spacecraft_SM_trajectory(spacecraft, t_start, t_end)
Fetch the Solar Magnetic trajectory of a spacecraft in a time range.
Fetches the trajectory of a spacecraft in a time range, in Solar Magnetic Cartesian coordinates. Data is fetched from CDAWeb.
- Parameters:
spacecraft (str) – CDAWeb-compliant spacecraft ID.
t_start (datetime.datetime) – Start datetime for trajectory fetch.
t_end (datetime.datetime) – End datetime for trajectory fetch.
- Returns:
Cartesian SM coordinates of spacecraft (units of kilometers).
- Return type:
Tuple[float, float, float]
- kaipy.cdaweb_utils.ingest_helio_spacecraft_trajectory(sc_id, sc_data, MJDc)
Ingests the heliospheric spacecraft trajectory data and converts the coordinates to the GH(MJDc) frame.
- Parameters:
sc_id (str) – The spacecraft ID.
sc_data (dict) – The spacecraft data containing the trajectory information.
MJDc (float) – The Modified Julian Date (MJD) for the desired frame.
- Returns:
The x-coordinate in the GH(MJDc) frame. y (dm.dmarray): The y-coordinate in the GH(MJDc) frame. z (dm.dmarray): The z-coordinate in the GH(MJDc) frame.
- Return type:
x (dm.dmarray)
kaipy.embiggenUtils module
- kaipy.embiggenUtils.Bvec2Global(B, vID, iH5, i, j, k, Ri, Rj, Rk, Nip, Njp, Nkp)
Convert a local B vector to the global B vector.
- Parameters:
B (ndarray) – The global B vector.
vID (int) – The ID of the vector.
iH5 (ndarray) – The local B vector.
i (int) – The i index.
j (int) – The j index.
k (int) – The k index.
Ri (float) – The Ri value.
Rj (float) – The Rj value.
Rk (float) – The Rk value.
Nip (int) – The Nip value.
Njp (int) – The Njp value.
Nkp (int) – The Nkp value.
- Returns:
None
- kaipy.embiggenUtils.CompRestarts(iStr, oStr, nRes, Ri, Rj, Rk)
Compare restart files and calculate the differences between corresponding variables.
- Parameters:
iStr (str) – Input file name pattern for the original restart files.
oStr (str) – Input file name pattern for the modified restart files.
nRes (int) – Number of restart files.
Ri (int) – Number of iterations in the i-direction.
Rj (int) – Number of iterations in the j-direction.
Rk (int) – Number of iterations in the k-direction.
- Returns:
None
- kaipy.embiggenUtils.Corner2Global(Q, vID, iH5, i, j, k, Ri, Rj, Rk, Nip, Njp, Nkp)
Transfers a corner of data from a local grid to the global grid.
- Parameters:
Q (ndarray) – Global grid.
vID (int) – Index of the corner data in iH5.
iH5 (ndarray) – Local grid.
i (int) – Index of the corner in the i-direction.
j (int) – Index of the corner in the j-direction.
k (int) – Index of the corner in the k-direction.
Ri (float) – Grid resolution in the i-direction.
Rj (float) – Grid resolution in the j-direction.
Rk (float) – Grid resolution in the k-direction.
Nip (int) – Number of points in the i-direction.
Njp (int) – Number of points in the j-direction.
Nkp (int) – Number of points in the k-direction.
- Returns:
None
- kaipy.embiggenUtils.Flux2Global(M, vID, iH5, i, j, k, Ri, Rj, Rk, Nip, Njp, Nkp)
Converts local flux data to global flux data and updates the global flux array.
- Parameters:
M (ndarray) – The global flux array with shape (Nd, NkT1, NjT1, NiT1).
vID (int) – The index of the local flux data in the iH5 array.
iH5 (ndarray) – The array containing the local flux data.
i (int) – The indices of the local flux data in the global flux array.
j (int) – The indices of the local flux data in the global flux array.
k (int) – The indices of the local flux data in the global flux array.
Ri (int) – The number of grid points in the i, j, k directions.
Rj (int) – The number of grid points in the i, j, k directions.
Rk (int) – The number of grid points in the i, j, k directions.
Nip (int) – The number of grid points in the i, j, k directions excluding ghost cells.
Njp (int) – The number of grid points in the i, j, k directions excluding ghost cells.
Nkp (int) – The number of grid points in the i, j, k directions excluding ghost cells.
- Returns:
None
- kaipy.embiggenUtils.Gas2Global(G, vID, iH5, i, j, k, Ri, Rj, Rk, Nip, Njp, Nkp)
Copies a local gas field to the corresponding global indices in a larger gas field.
- Parameters:
G (ndarray) – The larger gas field with shape (Ns, Nv, NkT, NjT, NiT).
vID (int) – The index of the local gas field to be copied.
iH5 (ndarray) – The local gas field with shape (Ns, Nv, Nk, Nj, Ni).
i (int) – The current i-index of the local gas field.
j (int) – The current j-index of the local gas field.
k (int) – The current k-index of the local gas field.
Ri (int) – The total number of i-indices in the larger gas field.
Rj (int) – The total number of j-indices in the larger gas field.
Rk (int) – The total number of k-indices in the larger gas field.
Nip (int) – The number of i-indices in the local gas field.
Njp (int) – The number of j-indices in the local gas field.
Nkp (int) – The number of k-indices in the local gas field.
- Returns:
None
- kaipy.embiggenUtils.MaxDiv(M)
Calculate the maximum divergence and mean divergence of a given 3D array.
- Parameters:
M (numpy.ndarray) – The input 3D array with shape (Nd, Nkc, Njc, Nic).
- Returns:
The divergence array with shape (Nk, Nj, Ni).
- Return type:
numpy.ndarray
- kaipy.embiggenUtils.PullRestartMPI(bStr, nRes, Ri, Rj, Rk)
Pulls and restarts MPI data from input files.
- Parameters:
bStr (str) – Base string for file names.
nRes (int) – Number of resolution levels.
Ri (int) – Number of blocks in the i-direction.
Rj (int) – Number of blocks in the j-direction.
Rk (int) – Number of blocks in the k-direction.
- Returns:
- A tuple containing the following arrays and variables:
X (ndarray): X-coordinate array.
Y (ndarray): Y-coordinate array.
Z (ndarray): Z-coordinate array.
nG (ndarray): Global gas array.
nM (ndarray): Global magnetic flux array.
nB (ndarray): Global magnetic field array.
oG (ndarray): Ghost gas array.
oM (ndarray): Ghost magnetic flux array.
oB (ndarray): Ghost magnetic field array.
G0 (ndarray): Initial gas array.
fIn0 (str): Initial input file name.
- Return type:
tuple
- kaipy.embiggenUtils.PushRestartMPI(outid, nRes, Ri, Rj, Rk, X, Y, Z, nG, nM, nB, oG, oM, oB, G0, f0, dtScl=1.0)
Pushes restart data to multiple output files in a parallel MPI simulation.
- Parameters:
outid (int) – Output identifier.
nRes (int) – Number of restarts.
Ri (int) – Number of MPI processes in the i-direction.
Rj (int) – Number of MPI processes in the j-direction.
Rk (int) – Number of MPI processes in the k-direction.
X (ndarray) – Array of X-coordinates.
Y (ndarray) – Array of Y-coordinates.
Z (ndarray) – Array of Z-coordinates.
nG (ndarray) – Array of cell-centered values.
nM (ndarray) – Array of face fluxes.
nB (ndarray) – Array of cell-centered magnetic field values.
oG (ndarray) – Array of old cell-centered values.
oM (ndarray) – Array of old face fluxes.
oB (ndarray) – Array of old cell-centered magnetic field values.
G0 (ndarray) – Array of initial cell-centered values.
f0 (str) – File path of the input file.
dtScl (float, optional) – Scaling factor for the time step. Defaults to 1.0.
- kaipy.embiggenUtils.Volume(Xg, Yg, Zg)
Calculate the volume of a grid.
- Parameters:
Xg (ndarray) – X coordinates of the grid.
Yg (ndarray) – Y coordinates of the grid.
Zg (ndarray) – Z coordinates of the grid.
- Returns:
Volume of the grid.
- Return type:
dV (ndarray)
Note
The function calculates the volume of a grid by performing a convex hull calculation on each grid cell. The grid is assumed to have LFM-like symmetry.
- kaipy.embiggenUtils.ccL2G(i, Ri, Nip)
Convert local indices to global indices.
- Parameters:
i (int) – The local index.
Ri (int) – The total number of local indices.
Nip (int) – The number of indices per process.
- Returns:
A tuple containing the start and end indices for the local and global indices.
- Return type:
tuple
- kaipy.embiggenUtils.upCCMag(B, dV0, dVu, vID='Bxyz')
Upscales the given magnetic field data by a factor of 2 in each dimension.
- Parameters:
B (numpy.ndarray) – The input magnetic field data with shape (Nv, Nk, Nj, Ni).
dV0 (numpy.ndarray) – The cell volume data with shape (Nk, Nj, Ni).
dVu (float) – The upscaled cell volume.
vID (str, optional) – The identifier for the variable being upscaled. Default is “Bxyz”.
- Returns:
The upscaled magnetic field data with shape (Nv, 2*Nk, 2*Nj, 2*Ni).
- Return type:
Bu (numpy.ndarray)
- kaipy.embiggenUtils.upFlux(M)
Upscales the face fluxes of a given input array.
- Parameters:
M (numpy.ndarray) – The input array representing the face fluxes.
- Returns:
The upscaled face fluxes.
- Return type:
Mu (numpy.ndarray)
- kaipy.embiggenUtils.upGas(G, dV0, dVu, vID='Gas')
Upscales the given gas variables.
- Parameters:
G (numpy.ndarray) – The gas variables to be upscaled.
dV0 (numpy.ndarray) – The volume of each cell in the original grid.
dVu (numpy.ndarray) – The volume of each cell in the upscaled grid.
vID (str, optional) – Identifier for the gas variables. Default is “Gas”.
- Returns:
The upscaled gas variables.
- Return type:
Gu (numpy.ndarray)
- kaipy.embiggenUtils.upGrid(X, Y, Z)
Upscales a grid by embedding old points into a new grid.
- Parameters:
X (ndarray) – 3D array representing the X-coordinates of the original grid.
Y (ndarray) – 3D array representing the Y-coordinates of the original grid.
Z (ndarray) – 3D array representing the Z-coordinates of the original grid.
- Returns:
Upscaled X-coordinates of the new grid. ndarray: Upscaled Y-coordinates of the new grid. ndarray: Upscaled Z-coordinates of the new grid.
- Return type:
ndarray
- kaipy.embiggenUtils.upVarCC(Q, dV0, dVu)
Upscale a variable defined on a coarse grid to a finer grid using conservative interpolation.
- Parameters:
Q (ndarray) – Variable defined on the coarse grid.
dV0 (ndarray) – Volumes of the coarse grid cells.
dVu (ndarray) – Volumes of the finer subgrid cells.
- Returns:
Upscaled variable on the finer grid.
- Return type:
ndarray
Note
The function loops over the coarse grid and calculates the weighted contribution of each subcell on the finer grid. It then scales back the density to obtain the upscaled variable. The conservation of the variable is tested by comparing the total values before and after the upscaling process.
kaipy.kJobs module
- kaipy.kJobs.OMPJob(fOut, ComX, inStr, Nthz=None, mod='kaiju', doArray=True)
- kaipy.kJobs.addXBlk(bStr, bDic, bStrs, bDics)
- kaipy.kJobs.genXBlk(rStr, bStrs, bDicts, doHeader=False)
- kaipy.kJobs.xml2str(xIn, doHeader=False)
kaipy.kaiH5 module
- kaipy.kaiH5.CheckDirOrMake(fdir)
Check if the given directory exists. If not, create the directory.
- Parameters:
fdir (str) – The directory path to check or create.
- Returns:
None
- kaipy.kaiH5.CheckOrDie(fname)
Check if a file exists, and exit the program if it doesn’t.
- Parameters:
fname (str) – The file name or path to check.
- Raises:
SystemExit – If the file doesn’t exist, the program will exit with an error message.
- kaipy.kaiH5.GetBranch(fname)
Retrieves the Git branch associated with the given file.
- Parameters:
fname (str) – The path to the file.
- Returns:
The Git branch name.
- Return type:
str
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
- kaipy.kaiH5.GetHash(fname)
Retrieves the GITHASH attribute value from an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
- Returns:
The value of the GITHASH attribute as a string.
- Return type:
str
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
- class kaipy.kaiH5.H5Info(h5fname: str, noSubsec: bool = True, useTAC=True, useBars=True)
Bases:
objectClass to hold model data information from h5 output files
- Parameters:
h5fname (str) – .h5 filename to scrape info from
noSubsec (bool) – Whether or not UTs should include subseconds (optional, default: True)
- fname
.h5 filename the rest of the info came from
- Type:
str
- steps
list of step numbers
- Type:
List[int]
- stepStrs
list of step strings in Step#X h5.Group format
- Type:
List[str]
- Nt
Number of time steps
- Type:
int
- times
List of times corresponding to each step Units: Unchanged from file, likely seconds
- Type:
List[float]
- MJDs
List of MJDs corresponding to each step
- Type:
List[float]
- UTs
List of UTs corresponding to each step May or may not include subseconds based on constructor args
- Type:
List[float]
- printStepInfo() None
Prints a summary of step info for the contained data
Args: None
Returns: None
- kaipy.kaiH5.LocDT(items, pivot)
Locates the index of the item in the given list that is closest to the specified pivot value.
- Parameters:
items (list) – A list of items to search through.
pivot (datetime) – The pivot value to compare against.
- Returns:
The index of the item in the list that is closest to the pivot value.
- Return type:
int
- kaipy.kaiH5.MageStep(T0, inFile)
Identify the step number closest to the given datetime.
- Parameters:
T0 – The datetime to compare against.
inFile – The input file.
- Returns:
The step number closest to the given datetime.
- Return type:
nStp
- kaipy.kaiH5.PullAtt(fname, vID, s0=None, a0=None)
Retrieve an attribute from an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
vID (str) – The name of the attribute to retrieve.
s0 (int, optional) – The step number. If provided, the attribute will be retrieved from the group corresponding to the step number.
- Returns:
The value of the attribute.
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
KeyError – If the specified attribute or group does not exist.
- kaipy.kaiH5.PullVar(fname, vID, s0=None, slice=())
Pull variable data from HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
vID (str) – The variable ID to pull from the file.
s0 (int, optional) – The step number. If provided, the variable will be pulled from the specified step group. If not provided, the variable will be pulled from the root group.
slice (tuple, optional) – The slice to apply to the variable data. Defaults to an empty tuple, which means no slicing will be applied.
- Returns:
The pulled variable data.
- Return type:
numpy.ndarray
Raises: CheckOrDieError: If the file does not exist or is not readable.
- kaipy.kaiH5.PullVarLoc(fname, vID, s0=None, slice=(), loc=None)
Pull variable data from HDF5 file and pass through (i, j, k) MPI rank loc
- Parameters:
fname (str) – The path to the HDF5 file.
vID (str) – The variable ID to pull data from.
s0 (int or None) – The starting index of the data to pull. Defaults to None.
slice (tuple or None) – The slice object to apply to the data. Defaults to ().
loc (tuple or None) – The (i, j, k) MPI rank location to pass the data through. Defaults to None.
- Returns:
A tuple containing the variable data (V) and the MPI rank location (loc).
- Return type:
tuple
- kaipy.kaiH5.StampBranch(fname)
Adds the current Git branch name as an attribute to an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
- Returns:
None
- kaipy.kaiH5.StampHash(fname)
Adds the git hash of the current commit to the given HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
- Returns:
None
- class kaipy.kaiH5.TPInfo(fname: str, noSubsec: bool = True)
Bases:
H5InfoExtension of H5Info for test particle files
- Ntp
Number of test particles
- Type:
int
- id2idxMap (Dict{int
}): Dict to help map TP id to its index
- kaipy.kaiH5.cntSteps(fname, doTryRecover=True, s0=0, useTAC=True, useBars=True)
Count the number of steps and retrieve the step IDs from an h5 file.
- Parameters:
fname (str) – The path to the h5 file.
doTryRecover (bool) – Whether to try recovering unreadable steps. Default is True.
s0 (int) – The starting step ID when recovering unreadable steps. Default is 0.
- Returns:
The total number of steps. sIds (ndarray): An array of step IDs.
- Return type:
nSteps (int)
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
ValueError – If the steps are unreadable and doTryRecover is False.
- kaipy.kaiH5.cntX(fname, gID=None, StrX='/Step#')
Count the number of steps and return sorted step IDs from an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
gID (str, optional) – The group ID within the HDF5 file. If None, all groups will be considered.
StrX (str, optional) – The string pattern to search for in the group names.
- Returns:
The number of steps found. sIds (numpy.ndarray): An array of sorted step IDs.
- Return type:
nSteps (int)
- Example usage:
nSteps, sIds = cntX(‘/path/to/file.h5’, gID=’group1’, StrX=’/Step#’)
- kaipy.kaiH5.genName(bStr, i, j, k, Ri, Rj, Rk, nRes=None)
Generate a filename based on the given parameters.
- Parameters:
bStr (str) – The base string for the filename.
i (int) – The value of i.
j (int) – The value of j.
k (int) – The value of k.
Ri (int) – The value of Ri.
Rj (int) – The value of Rj.
Rk (int) – The value of Rk.
nRes (int, optional) – The value of nRes. Defaults to None.
- Returns:
The generated filename.
- Return type:
str
- kaipy.kaiH5.genNameOld(bStr, i, j, k, Ri, Rj, Rk, nRes=None)
Generate a file name based on the given parameters.
- Parameters:
bStr (str) – Base string for the file name.
i (int) – Value of i for this segment.
j (int) – Value of j for this segement.
k (int) – Value of k for this segement.
Ri (int) – Value of Ri Ri for the overall decomposition.
Rj (int) – Value of Rj Ri for the overall decomposition.
Rk (int) – Value of Rk Ri for the overall decomposition.
nRes (int, optional) – Value of nRes for restart. Defaults to None.
- Returns:
Generated file name.
- Return type:
str
- kaipy.kaiH5.getDims(fname, vID='X', doFlip=True)
Get the dimensions of a dataset in an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
vID (str, optional) – The ID of the dataset to retrieve the dimensions from. Default is “X”.
doFlip (bool, optional) – Whether to flip the dimensions. Default is True.
- Returns:
The dimensions of the dataset.
- Return type:
numpy.ndarray
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
- kaipy.kaiH5.getRootVars(fname)
Retrieves the root variables from an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
- Returns:
A list of root variable names, excluding coordinates.
- Return type:
list
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
- kaipy.kaiH5.getTs(fname, sIds=None, aID='time', aDef=0.0, useTAC=True, useBars=True)
Retrieve time series data from an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
sIds (list, optional) – List of step IDs to retrieve time series data for. If None, all steps will be used.
aID (str, optional) – The attribute ID to retrieve. Default is “time”.
aDef (float, optional) – The default value to use if the attribute is not found. Default is 0.0.
- Returns:
An array containing the time series data.
- Return type:
numpy.ndarray
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
KeyError – If the specified attribute ID is not found in the HDF5 file.
- kaipy.kaiH5.getVars(fname, smin)
Retrieve variable IDs from an HDF5 file for a given step number.
- Parameters:
fname (str) – The path to the HDF5 file.
smin (int) – The step number.
- Returns:
A list of variable IDs.
- Return type:
list
- Raises:
FileNotFoundError – If the specified file does not exist.
- kaipy.kaiH5.tStep(fname, nStp=0, aID='time', aDef=0.0)
Retrieve the value of a specific attribute from a given HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
nStp (int) – The step number.
aID (str) – The attribute ID to retrieve. Defaults to “time”.
aDef (float) – The default value to return if the attribute is not found.
- Returns:
The value of the specified attribute.
- Return type:
float
- Raises:
CheckOrDieError – If the file does not exist or is not readable.
kaipy.kaiTools module
- kaipy.kaiTools.GetSymH(fBC)
Retrieve symh data from an HDF5 file.
- Parameters:
fBC (str) – The path to the HDF5 file.
- Returns:
Array of UT data. tData (numpy.ndarray): Array of T data. dstData (numpy.ndarray): Array of symh data.
- Return type:
utData (numpy.ndarray)
- kaipy.kaiTools.L_to_bVol(L, bsurf_nT=29617.37)
Calculates the flux tube volume [Rp/nT] from the given L shell [Rp].
- Parameters:
L (float) – L shell [Rp].
bsurf_nT (float, optional) – Surface field [nT]. Default is Earth’s surface field.
- Returns:
Flux tube volume [Rp/nT].
- Return type:
float
- kaipy.kaiTools.MJD2UT(mjd)
Convert Modified Julian Date (MJD) to Coordinated Universal Time (UTC).
- Parameters:
mjd – A single value or a list of MJD values.
- Returns:
If given a single value, returns a single datetime.datetime object representing the corresponding UTC time. If given a list of values, returns a list of datetime.datetime objects representing the corresponding UTC times.
- kaipy.kaiTools.burtonDst(secs, n, vx, vy, vz, bx, by, bz)
Given time in seconds, density in cm^-3, velocity in km/s and magnetic field in nT, this function will return Dst computed from the Burton 1975 (doi: 10.1029/ja080i031p04204) model.
- Parameters:
secs (array-like) – Time in seconds.
n (array-like) – Density in cm^-3.
vx (array-like) – Velocity in km/s (x-component).
vy (array-like) – Velocity in km/s (y-component).
vz (array-like) – Velocity in km/s (z-component).
bx (array-like) – Magnetic field in nT (x-component).
by (array-like) – Magnetic field in nT (y-component).
bz (array-like) – Magnetic field in nT (z-component).
- Returns:
Dst values computed from the Burton 1975 model.
- Return type:
dst (array-like)
Note
The input arrays should have the same length.
References
Burton, R. K., et al. (1975). “The Dst index: A measure of geomagnetic activity.” Journal of Geophysical Research, 80(31), 4204-4214. doi: 10.1029/ja080i031p04204
- kaipy.kaiTools.dipoleL(xyz)
- kaipy.kaiTools.dipoleShift(xyz, r)
- kaipy.kaiTools.getRunInfo(fdir, ftag)
Get information about the run.
- Parameters:
fdir (str) – The directory where the files are located.
ftag (str) – The file tag.
- Returns:
A tuple containing the file name, isMPI flag, Ri, Rj, and Rk values.
- Return type:
tuple
- Raises:
ValueError – If more than one parallel file is found or no MPI database is found.
- kaipy.kaiTools.interpTSC(gridX, gridY, x, y, var)
Conducts a Triangular Shaped Cloud (TSC) interpolation of a 2D variable.
- Paramters:
gridX/gridY: 3-element x & y grid vals (center value is closest grid point to desired interpolation point) x: dim1 of point of interest y: dim2 of point of interest var: 3x3 values of desired variable
- kaipy.kaiTools.interpTSCWeights(gridX, gridY, x, y)
Interpolates the weights for a 2D point of interest using a 3x3 grid.
- Parameters:
gridX (list) – A list of 3 x-coordinates of the grid points.
gridY (list) – A list of 3 y-coordinates of the grid points.
x (float) – The x-coordinate of the point of interest.
y (float) – The y-coordinate of the point of interest.
- Returns:
A 3x3 array of weights for the point of interest.
- Return type:
numpy.ndarray
- kaipy.kaiTools.newellcoupling(vx, vy, vz, bx, by, bz)
Given density in cm^-3, velocity in km/s, and magnetic field in nT, this function returns the Universal Coupling Function computed from the Newell 2007 (doi: 10.1029/2006ja012015).
- Parameters:
vx (float) – X-component of velocity in km/s.
vy (float) – Y-component of velocity in km/s.
vz (float) – Z-component of velocity in km/s.
bx (float) – X-component of magnetic field in nT.
by (float) – Y-component of magnetic field in nT.
bz (float) – Z-component of magnetic field in nT.
- Returns:
The computed Universal Coupling Function.
- Return type:
newcoup (float)
- kaipy.kaiTools.newellkp(secs, n, vx, vy, vz, bx, by, bz)
Given time in seconds, density in cm^-3, velocity in km/s, and magnetic field in nT, this function will return Kp computed from the Newell 2008 (doi: 10.1029/2007ja012825).
- Parameters:
secs (array-like) – Time in seconds.
n (array-like) – Density in cm^-3.
vx (array-like) – Velocity in km/s (x-component).
vy (array-like) – Velocity in km/s (y-component).
vz (array-like) – Velocity in km/s (z-component).
bx (array-like) – Magnetic field in nT (x-component).
by (array-like) – Magnetic field in nT (y-component).
bz (array-like) – Magnetic field in nT (z-component).
- Returns:
Kp values computed from the Newell 2008 model.
- Return type:
conextendkp (array-like)
Notes
Kp is a three-hour index, so the function computes a three-hour rolling average using convolution with the first and last value extended.
- kaipy.kaiTools.pntIdx_2D(X2D, Y2D, pnt)
Finds i, j, index within ‘X2D’ and ‘Y2D’ closest to ‘pnt’ Assumes cartesian coordinate system
- Parameters:
X2D (ndarray[float]) – 2D array of X values
Y2D (ndarray[float]) – 2D array of Y values
pnt (List[float]) – [x, y] point to find closest index to
- Returns:
Tuple of closest i, j index to point ‘pnt’
- kaipy.kaiTools.rtp2rt(r, theta, phi)
Convert spherical coordinates (r, theta, phi) to 2D polar (r, phi)
- Parameters:
r (float) – radial dimension
theta (float) – [rad] meridional/zenith direction
phi (float) – [rad] azimuthal direciton
- Returns:
radial dimension theta (float): [rad]azimuthal dimenison
- Return type:
r (float)
- kaipy.kaiTools.to_center1D(A)
- kaipy.kaiTools.to_center2D(A)
- kaipy.kaiTools.to_center3D(A)
- kaipy.kaiTools.utIdx(utList, ut)
Finds the index of the closest datetime within an array of datetimes
- Parameters:
utList (List[datetime.datetime]) – List of datetimes to find index within
ut (datetime.datetime) – datetime to find closest index to
- Returns:
Single integer value of the closest index within ‘utList’ to ‘ut’
- kaipy.kaiTools.xyz2rtp(phi, theta, Ax, Ay, Az)
Convert Cartesian coordinates (Ax, Ay, Az) to spherical coordinates (r, theta, phi).
- Parameters:
phi (float) – The azimuthal angle in radians.
theta (float) – The polar angle in radians.
Ax (float) – The x-coordinate in Cartesian coordinates.
Ay (float) – The y-coordinate in Cartesian coordinates.
Az (float) – The z-coordinate in Cartesian coordinates.
- Returns:
The radial component in spherical coordinates. At (float): The azimuthal component in spherical coordinates. Ap (float): The polar component in spherical coordinates.
- Return type:
Ar (float)
kaipy.kaiViz module
- kaipy.kaiViz.DrawCut(Rin=2.5, ax=None)
Draw a cut using matplotlib.patches.Wedge.
- Parameters:
Rin (float) – The inner radius of the cut. Default is 2.5.
ax (matplotlib.axes.Axes, optional) – The axes on which to draw the cut. If not provided, the current axes will be used.
- Returns:
The created Wedge object representing the cut.
- Return type:
matplotlib.patches.Wedge
- class kaipy.kaiViz.MidpointNormalize(vmin=None, vmax=None, midpoint=None, clip=False)
Bases:
NormalizeCustom normalization class that maps values to the range [0, 1] with a specified midpoint.
- Parameters:
vmin (float, optional) – The minimum value of the input range. If not provided, the minimum value of the input data will be used.
vmax – (float, optional): The maximum value of the input range. If not provided, the maximum value of the input data will be used.
midpoint (float, optional) – The midpoint value that will be mapped to 0.5 in the output range. If not provided, the average of vmin and vmax will be used.
clip (bool, default False) – If True, values outside the range [vmin, vmax] will be clipped to vmin or vmax.
- Returns:
The normalized value(s) within the range [0, 1].
- Return type:
normalized_value (numpy.ma.masked_array)
Examples: >>> norm = MidpointNormalize(vmin=0, vmax=10, midpoint=5) >>> normalized_value = norm(7) >>> print(normalized_value) # Output: 0.7
- kaipy.kaiViz.SetAx(xyBds=[-1, 1, -1, 1], ax=None, Adj='box')
Set axis plot bounds and aspect ratio.
Ensure that the plot has an equal aspect ratio and that the axis limits are set to the specified values.
- Parameters:
xyBds – list of 4 float, optional, default [-1, 1, -1, 1] Axis limits for x and y as (xmin, xmax, ymin, ymax).
ax – matplotlib.Axes, optional, default None Axes object to modify.
Adj – str, optional, default ‘box Specify what aspect of the plot to adjust to achieve equal aspect ratio.
- Returns:
None
- kaipy.kaiViz.SetAxDate(Ax, fmt='%H:%M \n%Y-%m-%d')
Set the x-axis of the given Axes object to display dates.
- Parameters:
Ax – The Axes object to set the x-axis date format for.
fmt – The date format string to use. Defaults to ‘%H:%M%Y-%m-%d’.
- Returns:
None
- kaipy.kaiViz.SetAxLabs(Ax, xLab, yLab, doBot=True, doLeft=True, fs='medium')
Set axis plot bounds and aspect ratio.
Ensure that the plot has an equal aspect ratio and that the axis limits are set to the specified values.
- Parameters:
xyBds – list of 4 float, optional, default [-1, 1, -1, 1] Axis limits for x and y as (xmin, xmax, ymin, ymax).
ax – matplotlib.Axes, optional, default None Axes object to modify.
Adj – str, optional, default ‘box Specify what aspect of the plot to adjust to achieve equal aspect ratio.
- Returns:
None
- kaipy.kaiViz.ShaveX(fName)
ShaveX function crops an image file by removing one pixel from the right side.
- Parameters:
fName (str) – The file name of the image to be cropped.
- Returns:
fName file is cropped by one pixel on the right side.
- kaipy.kaiViz.ShaveY(fName)
Shave one pixel from the top of the image.
- Parameters:
fName (str) – The file name of the image.
- Returns:
fName file is cropped by one pixel on the top.
- kaipy.kaiViz.addEarth2D(Re=1, angle=-90, ax=None)
Adds a 2D representation of Earth to the given matplotlib axes.
- Parameters:
Re (float) – Radius of the Earth. Default is 1.
angle (float) – Angle at which the Earth is rotated. Default is -90.
ax (matplotlib.axes.Axes) – The axes to which the Earth will be added. If None, the current axes will be used.
- Returns:
A list containing the two Wedge objects representing the Earth.
- Return type:
list
- kaipy.kaiViz.compPlot(plotname, scId, data)
Generate a composite plot with multiple subplots based on the given data.
- Parameters:
plotname (str) – The title of the composite plot.
scId (str) – The identifier for the subplot legend.
data (dict) – A dictionary containing the data to be plotted.
- Returns:
Image file saved to disk.
- kaipy.kaiViz.genCB(AxCB, vN, cbT='Title', cM='viridis', doVert=False, cbSz='medium', Ntk=None)
Generate a colorbar using matplotlib.
- Parameters:
AxCB (Axes object) – The axes object where the colorbar will be drawn.
vN (Normalize object) – The normalization object used to map data values to colors.
cbT (str, optional) – The title of the colorbar. Default is “Title”.
cM (str, optional) – The name of the colormap to use. Default is “viridis”.
doVert (bool, optional) – Whether to display the colorbar vertically. Default is False.
cbSz (str, optional) – The size of the colorbar labels and title. Default is “medium”.
Ntk (int, optional) – The number of ticks to display on the colorbar. Default is None.
- Returns:
The generated colorbar object.
- Return type:
cb (Colorbar object)
- kaipy.kaiViz.genNorm(vMin, vMax=None, doLog=False, doSymLog=False, midP=None, linP=1.0)
Generate a matplotlib color normalization object based on the given parameters.
- Parameters:
vMin (float) – the minimum value of the data range
vMax (float) – optional, the maximum value of the data range (default: None)
doLog (bool, optional) – whether to use logarithmic normalization (default: False)
doSymLog (bool, optional) – whether to use symmetric logarithmic normalization (default: False)
midP (float, optional) – the midpoint value for midpoint normalization (default: None)
linP (float, optional) – the linear threshold for symmetric logarithmic normalization (default: 1.0)
- Returns:
the color normalization object
- Return type:
vN (matplotlib.colors.Normalize)
Note
If vMax is not provided, the absolute value of vMin is used as both vMin and vMax. If midP is not provided, midpoint normalization is not used. If doLog is True, logarithmic normalization is used. If doSymLog is True, symmetric logarithmic normalization is used. If none of the above conditions are met, linear normalization is used.
- kaipy.kaiViz.get_aspect(ax)
Get the current aspect ratio of the given ax.
- Parameters:
ax – The matplotlib Axes object.
- Returns:
The aspect ratio of the Axes object.
- kaipy.kaiViz.helioCompPlot_new(plot_file_path, sc_id, sc_data)
Create comparison plots for heliospheric results.
Create comparison plots for heliospheric results and save the plots to a file. The plots will compare simulation results to measured spacecraft data. The compared variables are radial velocity, radial magnetic field, number density, and temperature.
- Parameters:
plotname (str) – Path to file to hold plot image.
scId (str) – ID string for spacecraft.
data (spacepy.datamodel.SpaceData) – The current spacecraft and model data
- Return type:
None
- kaipy.kaiViz.helioItemPlot_new(Ax, sc_id, data, key, plotNum, numPlots, show_zero=False)
Plot a single variable for the comparison plot.
Plot a single variable for the comparison plot.
- Parameters:
Ax (matplotlib.axes._subplots.AxesSubplot) – Matplotlib axis for plot.
data (spacepy.datamodel.SpaceData) – Object containing the measured spacecraft data.
key (str) – Name of variable to plot.
plotNum (int) – Position of plot in sequence of plots.
numPlots (int) – Number of plots in sequence.
show_zero (bool, default False) – Set to True to show a black dashed line at the 0 level for the variable.
- Returns:
None
- kaipy.kaiViz.helioTrajPlot(plot_file_path, sc_id, sc_data)
Create a set of trajectory plots for a heliospheric spacecraft.
Create a set of trajectory plots for a heliospheric spacecraft. These plots are created in the original spacecraft frame.
- Parameters:
plot_name (str) – Path to plot file.
scId (str) – Name of spacecraft.
data (spacepy.datamodel.SpaceData) – Object containing spacecraft data.
- Return type:
None
- kaipy.kaiViz.helio_labelStr(data, key, vecComp)
Returns the label for a given data key in the heliocentric coordinate system.
- Parameters:
data (dict) – A dictionary containing the data.
key (str) – The key for which the label is needed.
vecComp (str) – The vector component for which the label is needed.
- Returns:
The label for the specified data key and vector component.
- Return type:
str
- kaipy.kaiViz.itemPlot(Ax, data, key, plotNum, numPlots, vecComp=-1)
Plot the data for a specific item.
- Parameters:
Ax (matplotlib.axes.Axes) – The axes object to plot on.
data (dict) – The data dictionary containing the data to plot.
key (str) – The key representing the item to plot.
plotNum (int) – The plot number.
numPlots (int) – The total number of plots.
vecComp (int, optional) – The vector component to plot. Defaults to -1.
- Returns:
None
- kaipy.kaiViz.labelStr(data, key, vecComp)
Generate a label string based on the given data, key, and vector component.
- Parameters:
data (dict) – A dictionary containing the data.
key (str) – The key used to access the data.
vecComp (int) – The vector component.
- Returns:
The generated label string.
- Return type:
str
- kaipy.kaiViz.picSz(fName)
Get the size of an image.
- Parameters:
fName (str) – The file path of the image.
- Returns:
A tuple containing the width and height of the image.
- Return type:
tuple
- kaipy.kaiViz.reWrap(V)
Re-wraps a 2D array by adding an extra column at the end, where the values in the new column are the same as the values in the first column.
- Parameters:
V (numpy.ndarray) – The input 2D array.
- Returns:
The re-wrapped 2D array with an extra column.
- Return type:
numpy.ndarray
- kaipy.kaiViz.savePic(fOut, dpiQ=300, doTrim=True, bLenX=20, bLenY=None, doClose=False, doEps=False, saveFigure=None)
Save a matplotlib figure to a file.
- Parameters:
fOut (str) – The output file path.
dpiQ (int) – The resolution of the saved figure in dots per inch (default: 300).
doTrim (bool) – Whether to trim the saved figure (default: True).
bLenX (int) – The length of the x-axis trim boundary (default: 20).
bLenY (int) – The length of the y-axis trim boundary (default: None).
doClose (bool) – Whether to close all figures after saving (default: False).
doEps (bool) – Whether to save the figure in EPS format (default: False).
saveFigure (matplotlib figure) – A predefined figure to plot into (default: None).
- Returns:
Image File saved to disk.
- kaipy.kaiViz.setBndsByAspect(ax, bnds, axis='x', aspect=1)
Given bounds of one axis, set the other bounds of Axes object such that aspect ratio and Axes box size is perserved
- Parameters:
ax – Axes object to set bounds for
bnds (List[float]) – [axMin, axMax] min/max bounds for fixed axis
axis (str) – (‘x’ or ‘y’) axis that fixed bounds are applied to
aspect – x:y aspect ratio to preserve
- kaipy.kaiViz.trajPlot(plotname, scId, data, toRe)
Plot the trajectory of a spacecraft.
- Parameters:
lotname (str) – The name of the plot.
scId (str) – The spacecraft ID.
data (dict) – A dictionary containing the spacecraft’s ephemeris data.
toRe (float) – The conversion factor from meters to Re (Earth radii).
- Returns:
Image file saved to disk.
- kaipy.kaiViz.trimFig(fName, bLenX=20, bLenY=None, doEven=True)
Trims the figure image file by removing the borders and resizing it to have even dimensions.
- Parameters:
fName (str) – The file name of the figure image.
bLenX (int) – The length of the border to be added on the X-axis. Default is 20.
bLenY (int) – The length of the border to be added on the Y-axis. If not provided, it will be set to bLenX.
doEven (bool) – Flag indicating whether to resize the image to have even dimensions. Default is True.
- Returns:
Image file saved to disk.
kaipy.kaijson module
- class kaipy.kaijson.CustomEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
Bases:
JSONEncoderCustom JSON encoder that extends the functionality of the base JSONEncoder class.
- default(obj)
Override the default method to handle custom encoding for specific object types. Extends the base JSONEncoder class to handle encoding of datetime objects, numpy arrays, and numpy base variable types.
- Parameters:
obj – The object to be encoded.
- Returns:
The encoded representation of the object.
- Raises:
TypeError – If the object cannot be encoded.
- kaipy.kaijson.customhook(dct)
Custom hook function for JSON decoding.
This function is used as a hook for the json.loads function to customize the decoding process. It handles specific cases for datetime objects, numpy arrays, and numpy base variable types. Assumes formatting defined in CustomEncoder.
- Parameters:
dct (dict) – The dictionary representing the JSON object being decoded.
- Returns:
The modified dictionary after applying the custom decoding logic.
- Return type:
dict
- kaipy.kaijson.dump(fname, data, action='w')
Store data [dict] in file fname.
- Parameters:
fname (str) – The file name or path where the data will be stored.
data (dict) – The data to be stored in the file.
action (str, optional) – The action to perform on the file. Defaults to ‘w’ (write).
- Raises:
FileNotFoundError – If the specified file path does not exist.
- kaipy.kaijson.dumps(data, noIndent=False)
Returns a string with the given dictionary in JSON format.
- Parameters:
data – The dictionary to be converted to JSON.
noIndent – Optional parameter to specify whether to include indentation in the JSON string. Default is False.
- Returns:
A string representing the dictionary in JSON format.
- kaipy.kaijson.load(fname)
Load JSON data from a file.
- Parameters:
fname (str) – The path to the JSON file.
- Returns:
The loaded JSON data as a dictionary.
- Return type:
dict
- Raises:
FileNotFoundError – If the specified file doesn’t exist.
- kaipy.kaijson.loads(dataString)
Parses a string containing JSON data and returns a dictionary.
- Parameters:
dataString (str) – The string containing JSON data.
- Returns:
A dictionary representing the parsed JSON data.
- Return type:
dict
kaipy.kaixdmf module
- kaipy.kaixdmf.AddDI(elt, h5F, nStp, cDims, vId)
Adds a DataItem element to the given element.
- Parameters:
elt – The parent element to which the DataItem element will be added.
h5F – The HDF file path.
nStp – The step number.
cDims – The dimensions of the DataItem.
vId – The variable ID.
- Returns:
None
- kaipy.kaixdmf.AddData(Grid, fname, vID, vLoc, xDims, s0=None)
AddData function adds data to the given Grid xdmf element.
- Parameters:
Grid – The parent element to which the data will be added.
fname – The file name or path.
vID – The ID of the attribute.
vLoc – The location of the attribute.
xDims – The dimensions of the data item.
s0 – The step number (integer, optional). If not provided, will point to data in root of h5 file.
- Returns:
None
- kaipy.kaixdmf.AddGrid(fname, Geom, iDims, coordStrs)
Add a grid to the given Geometry xdmf element.
- Parameters:
fname (str) – The file name.
Geom (Element) – The geometry xdmf element to add the grid to.
iDims (str) – The dimensions of the grid.
coordStrs (list) – A list of coordinate strings.
- Returns:
None
- kaipy.kaixdmf.AddVectors(Grid, fname, vIds, cDims, vDims, Nd, nStp)
Adds vector attributes to the given Grid element based on the provided parameters.
- Parameters:
Grid – The Grid element to which the vector attributes will be added.
fname – The file name.
vIds – A list of vector identifiers.
cDims – The cell dimensions.
vDims – The vector dimensions.
Nd – The number of dimensions.
nStp – The step number.
- Returns:
None
- kaipy.kaixdmf.addHyperslab(Grid, vName, dSetDimStr, vdimStr, startStr, strideStr, numStr, origDSetDimStr, fileText)
Add a hyperslab to the given Grid element.
- Parameters:
Grid – The parent element to which the hyperslab will be added.
vName – The name of the attribute.
dSetDimStr – The dimensions of the hyperslab.
vdimStr – The dimensions of the cut.
startStr – The start position of the hyperslab.
strideStr – The stride of the hyperslab.
numStr – The number of elements in the hyperslab.
origDSetDimStr – The dimensions of the original dataset.
fileText – The text of the file.
- Returns:
None
- kaipy.kaixdmf.getLoc(gDims, vDims)
Determines the location type based on the given global dimensions and variable dimensions.
- Parameters:
gDims (list) – A list of integers representing the global dimensions.
vDims (list) – A list of integers representing the variable dimensions.
- Returns:
The location type, which can be “Cell”, “Node”, or “Other”.
- Return type:
str
Note
If the lengths of gDims and vDims are not equal, the function returns “Other”. The function checks each dimension and determines the location type based on the comparison between the global dimension and the variable dimension. If all dimensions have the same location type, the function returns that type. Otherwise, it returns “Other”.
- kaipy.kaixdmf.getRootVars(fname, gDims)
Retrieve the root variables from an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
gDims (list[int]) – The global dimensions of the data.
- Returns:
A tuple containing two lists - vIds and vLocs. vIds (list): A list of variable IDs. vLocs (list): A list of variable locations.
- Return type:
tuple
- kaipy.kaixdmf.getVars(fname, gId, gDims, recursive=False)
Retrieves the variable names and locations from the specified group ID in an HDF5 file.
- Parameters:
fname (str) – The path to the HDF5 file.
gId (str) – The group ID.
gDims (list[int]) – The dimensions of the group.
recursive (bool, optional) – Flag indicating whether to recursively retrieve variables from subgroups. Defaults to False.
- Returns:
A tuple containing two lists - the variable names and their corresponding locations.
- Return type:
tuple
- kaipy.kaixdmf.printVidAndLocs(vIds: list, vLocs: list)
Prints variable ids and their locations (cell vs node)
- Parameters:
vIds – List of variable IDs/names
vLocs – List of variable locations
- Returns:
None
kaipy.kdefs module
This module contains various constants used in the code.
- Helpful conversions:
G2nT: Conversion factor from Gauss to nanoTesla. kev2J: Conversion factor from keV to Joules. ev2J: Conversion factor from eV to Joules. erg2J: Conversion factor from erg to Joules.
- Physical Constants:
Mu0: Magnetic constant in Tesla meter per Ampere (Tm/A). Me_cgs: Electron mass in grams (g). Mp_cgs: Proton mass in grams (g). eCharge: Charge of an electron in Joules (J). dalton: Mass unit in kilograms (kg).
- Planetary Constants:
Re_cgs: Earth’s radius in centimeters (cm). EarthM0g: Earth’s magnetic field strength in Gauss. REarth: Earth’s radius in meters (m). RionE: Earth’s ionosphere radius in 1000 km. EarthPsi0: Corotation potential of Earth in kiloVolts (kV). SaturnM0g: Saturn’s magnetic field strength in Gauss. RSaturnXE: Saturn’s radius in terms of Earth’s radius. JupiterM0g: Jupiter’s magnetic field strength in Gauss. RJupiterXE: Jupiter’s radius in terms of Earth’s radius. MercuryM0g: Mercury’s magnetic field strength in Gauss. RMercuryXE: Mercury’s radius in terms of Earth’s radius. NeptuneM0g: Neptune’s magnetic field strength in Gauss. RNeptuneXE: Neptune’s radius in terms of Earth’s radius.
- Helio:
Rsolar: Solar radius in centimeters (cm). kbltz: Boltzmann constant in erg per Kelvin (erg/K). mp: Proton mass in grams (g). Tsolar: Siderial solar rotation period in days. Tsolar_synodic: Synodic solar rotation period in days. JD2MJD: Conversion factor from Julian Date (JD) to Modified Julian Date (MJD). Day2s: Conversion factor from days to seconds. vc_cgs: Speed of light in centimeters per second (cm/s).
- Output defaults:
barLen: Length of the progress bar. barLab: Length of the progress bar label. barDef: Default progress bar animation. grpTimeCache: Time attribute cache name for I/O.
kaipy.supermage module
- kaipy.supermage.CalculateSMRBins(mlt, B, mlat)
Calculate SMR and bins for a given mlt, B, and mlat Does the latitudinal scaling
- Parameters:
mlt (array) – Array of magnetic local time.
B (array) – Array of B.
mlat (array) – Array of magnetic latitudes.
- Returns:
- A tuple containing the following arrays:
SMR (array): Calculated SMR (SYMH equivalent).
SMR00 (array): 6-hour SMR bin for 00:00-06:00 MLT.
SMR06 (array): 6-hour SMR bin for 06:00-12:00 MLT.
SMR12 (array): 6-hour SMR bin for 12:00-18:00 MLT.
SMR18 (array): 6-hour SMR bin for 18:00-00:00 MLT.
- Return type:
tuple
- kaipy.supermage.EField1DCalculation(BX, BY, TD)
Calculates Ex and Ey using a resistive 1-D ground model.
This function assumes that it is given 60 second data.
WARNING and time-series with nans will return all nans for that location. I’m not sure what the best way to handle these are, probably a linear interpolation before calculating E-fields.
Also, be wary of FFT edge values at start and end of E-field calculation.
- Parameters:
BX (array) – Array of Bx(north) from SM functions (e.g., SM[‘dBn’]).
BY (array) – Array of By(east) from SM functions (e.g., SM[‘dBe’]).
TD (array) – Timedate array.
- Returns:
Array of Ex in mV/km, same shape as input Bx. EY (array): Array of Ey in mV/km, same shape as input By.
- Return type:
EX (array)
- kaipy.supermage.E_Field_1D(bx, by, resistivities, thicknesses, timestep=60.0, Z=None, calc_Z=True, pad=True, padnum=150)
Calculate horizontal E-field components given Bx, By, resistivities, and thicknesses.
- Parameters:
bx (array) – Array of Bx timeseries in nT.
by (array) – Array of By timeseries in nT.
resistivities (array or list) – Array or list of resistivity values in Ohm.m.
thicknesses (array or list) – Array or list of thicknesses in m. len(resistivities) must be len(thicknesses) + 1
timestep (float) – Time between samples (default is 60. for minute sampling).
Z (complex array) – Complex Z-tensor array. If not supplied, Z will be calculated from input resistivities and thicknesses.
calc_Z (bool) – Flag to calculate Z if not supplied (default is True).
pad (bool) – Flag to pad the input data (default is True).
padnum (int) – Number of points to pad at the beginning and end of the input data (default is 150).
- Returns:
Array of electric field components in mV/km. eyt (array): Array of electric field components in mV/km.
- Return type:
ext (array)
- kaipy.supermage.FetchSMData(user, start, numofdays, savefolder, badfrac=0.1, nanflags=True, ncpus=1)
Retrieve all available SuperMagnet data for a specified period. If data has not already been downloaded, fetches data from Supermag.
Parameters: user: str
Username for downloading SuperMag Data.
- start: datetime
Start day.
- numofdays: int
Number of days from start to download.
- savefolder: str
Folder where downloaded data will be saved as json. This function looks here first for saved data before downloading.
- badfrac: float, optional
Tolerable fraction of data that is 99999.0. Sites with more bad data than this fraction will be ignored. Default is 0.1.
- nanflags: bool, optional
If True, set 99999.0 values to NaNs. Default is True.
Returns: dict:
Dictionary which has the following data as keys: {‘td’, ‘sitenames’, ‘glon’, ‘glat’, ‘mlon’, ‘mlat’, ‘mcolat’, ‘BNm’, ‘BEm’, ‘BZm’, ‘BNg’, ‘BEg’, ‘BZg’, ‘MLT’, ‘DECL’, ‘SZA’}
- kaipy.supermage.FetchSMIndices(user, start, numofdays, wanted='ALL')
Retrieve SME, SML, SMU indices from SuperMag
- Parameters:
user (str) – Username for downloading SuperMag Data.
start (datetime) – Start day.
numofdays (int) – Number of days from start to download.
wanted (list, optional) – List of wanted attributes. Defaults to None.
- Returns:
Dictionary of wanted values as arrays + ‘td’ array.
- Return type:
dict
- kaipy.supermage.Float2Time(x)
Converts a float or an array of floats to datetime objects.
- Parameters:
x (float or array-like) – The input float or array of floats to be converted.
- Returns:
- If the input is a single float, returns a datetime object representing the corresponding timestamp.
If the input is an array of floats, returns an ndarray of datetime objects representing the corresponding timestamps.
- Return type:
datetime or ndarray
- kaipy.supermage.InterpolateSimData(SIM, SM)
Interpolates simulated data to SuperMag station coordinates, and calculates different indices (SME/U/L/R).
This function first interpolates sim data so that it is on the same timestamps as the SM data, then interpolates to the same geographic positions. Then it calculates SME/U/L/R for the SM interpolated data, + all simulated data (superSME/U/L/R).
- Parameters:
SIM (dict) – Dictionary of simulated data (from ReadSimData()).
SM (dict) – Dictionary of supermag data (from FetchSMData()).
- Returns:
- Dictionary containing the following keys:
td: Timestamps.
sitenames: Supermag site names.
glon: Supermag longitude coordinates.
glat: Supermag latitude coordinates.
mlon: Magnetic longitude coordinates.
mlat: Magnetic latitude coordinates.
dBn: Interpolated northward deflection (dot product of dB and minus thetheta unit vector)
dBt: Interpolated magnetic theta component.
dBp: Interpolated magnetic phi component.
dBr: Interpolated magnetic radial component.
mlt: Interpolated magnetic local time.
dBnsmall: Simulated data for all points, but limited to Supermag timestamps.
mltsmall: Simulated data for all points, but limited to Supermag timestamps.
SME: SME index at interpolated points.
SMU: SMU index at interpolated points.
SML: SML index at interpolated points.
SMR: SMR index at interpolated points.
superSME: SME index using all data.
superSMU: SMU index using all data.
superSML: SML index using all data.
superSMR: SMR index using all data.
SMRbins: List of 4 bins using interpolated data (SMR00/06/12/18).
superSMRbins: List of 4 bins using all data (SMR00/06/12/18).
- Return type:
dict
- kaipy.supermage.MJD2Str(m0)
Returns timestrings and datetime objects for simulation MJD
- Parameters:
m0 (float) – The simulation float representing the Modified Julian Date (MJD).
- Returns:
- A tuple containing the time string and datetime object.
tStr (str): The formatted time string in the format “HH:MM:SS MM/DD/YYYY”.
dtObj (datetime): The datetime object corresponding to the simulation float.
- Return type:
tuple
- kaipy.supermage.MakeContourPlots(SM, SMinterp, maxx='default', fignumber=1)
Makes hourly contour plots for SMU/SML
- Parameters:
SM (dict) – Dictionary containing SM data.
SMinterp (dict) – Dictionary containing interpolated SM data.
maxx (float, optional) – Absolute max value for colorbar. If left as ‘default’, will adapt to data. Defaults to ‘default’.
fignumber (int, optional) – Number of figure. Defaults to 1.
- Returns:
None
- kaipy.supermage.MakeIndicesPlot(SMI, SMinterp, fignumber=1)
Plot the indices using the given data.
- Parameters:
SMI (dict) – Dictionary containing the real indices data.
SMinterp (dict) – Dictionary containing the interpolated and super indices data.
fignumber (int) – Figure number for the plot (default is 1).
- Returns:
None
- kaipy.supermage.ReadSimData(filename, quiet=True)
Reads in all of the needed ground magnetic data from a .h5 file.
- Parameters:
filename (str) – The address of the .h5 delta-b object.
- Returns:
- A dictionary containing the following keys:
td (array): Time for each step.
glon (array): Geographic longitude.
glat (array): Geographic latitude.
mlt (array): Magnetic local time.
smlon (array): SM coordinates (longitude).
smlat (array): SM coordinates (latitude).
dBt (array): Btheta component (multiplied by -1).
dBp (array): Bphi component.
dBr (array): Bradius component.
dBn (array): Northward deflection (dot product of dB and minus thetheta unit vector).
- Return type:
dict
- kaipy.supermage.SMContourPlotPrep(mlt, td, bx)
Bins max and min Bn to make hourly SMU/SML contour plots
- Parameters:
mlt (array) – Magnetic local time array.
td (array) – Array of datetime.
bx (array) – Array of Bx (magnetic north component).
- Returns:
- Tuple containing:
hourbins (array): Array of 1.5*hour (24.5, 23.5…).
SMUbig (array): Array of binned SMU values.
SMLbig (array): Array of binned SML values.
- Return type:
tuple
- kaipy.supermage.SMdict_to_df(SM, sitenames=None, geo_names=['glat', 'glon', 'mlat', 'mlon', 'mcolat'], var_names=['BNm', 'BEm', 'BZm', 'BNg', 'BEg', 'BZg', 'mlt', 'decl', 'sza'])
Convert a dictionary of SuperMag magnetometer (SM) data to a pandas DataFrame.
- Parameters:
SM (dict) – Dictionary containing the solar wind magnetometer data.
sitenames (list or None) – List of site names. If None, the function will use the ‘sitenames’ key from the SM dictionary.
geo_names (list) – List of names for the geographic information columns in the resulting DataFrame.
var_names (list) – List of names for the variable columns in the resulting DataFrame.
- Returns:
DataFrame containing the combined data from the SM dictionary.
- Return type:
combined_data (pandas.DataFrame)
- kaipy.supermage.Time2Float(x)
Converts datetime to float, so that interpolation/smoothing can be performed
- Parameters:
x (datetime) – The datetime object to be converted to float
- Returns:
The float representation of the input datetime object
- Return type:
float
- kaipy.supermage.Z_Tensor_1D(resistivities, thicknesses, frequencies)
Calculate 1D Z-Tensor for given ground resistivity profile.
- Parameters:
resistivities (array or list) – Resistivity values in Ohm.m.
thicknesses (array or list) – Thicknesses in m. len(resistivities) must be len(thicknesses) + 1
frequencies (array or list) – Frequencies to get response of.
- Returns:
Z tensor values.
- Return type:
Z (complex array)
Taken from: http://www.digitalearthlab.com/tutorial/tutorial-1d-mt-forward/
- kaipy.supermage.doFetch(user, startstr, numofdays, smFlags, badfrac, iii)
Fetches data using SuperMAG API.
- Parameters:
user (str) – The user name.
startstr (str) – The start date in string format.
numofdays (int) – The number of days to fetch data for.
smFlags (str) – The flag string.
badfrac (float) – The fraction of bad values allowed.
iii (int) – The station number.
- Returns:
- A tuple containing the following elements:
status (bool): The status of the data fetch.
badindex (bool): Indicates if there are too many bad values.
master (list or str): The fetched data or ‘BAD’ if fetch failed.
- Return type:
tuple
- kaipy.supermage.interp_grid(values, tri, uv, d=2)
Perform grid interpolation for each connection.
This function is essentially what griddata does, but with the first part of the triangulation separated out (in interp_tri) so it can be performed just once for the E-field grid. Then this part is for finding the interpolated values for all the paths along each of the connections.
This approach provides a ~7x speed improvement for a uniform field.
- Parameters:
values (np.array) – Values for each point on the grid, i.e., the E-field values.
tri (scipy.spatial.qhull.Delaunay) – Triangulation object obtained from interp_grid.
uv (np.array) – New grid positions for interpolation, i.e., path steps along the connection.
d (scalar, optional) – Number of dimensions. Would be 3 for a 3D grid. Defaults to 2.
- Returns:
Interpolated values for the given grid positions.
- Return type:
np.array
- kaipy.supermage.interp_tri(xy)
Perform the first part of the griddata calculation, which only needs to be done once for the main grid. This function creates a Delaunay triangulation object based on the given points.
- Parameters:
xy (array-like) – The input points for the triangulation.
- Returns:
The Delaunay triangulation object.
- Return type:
Delaunay
References
Stack Overflow: https://stackoverflow.com/questions/20915502/
kaipy.transform module
This module provides coordinate transformations relevant to geospace modeling. Many of these transformations are wrappers to external C or Fortran libraries, using the NumPy vectorize() method to handle ndarray inputs when appropriate.
Note
This module is stripped down to only stuff that is currently used in kaipy. The few remaining routines only wrap spacepy.
#K: Ripped out everything
- Functions:
- x, y, z = SMtoGSM(x, y, z, dateTime)
Convert from solar magnetic to geocentric solar magnetospheric coordinates.
- x, y, z = GSMtoSM(x, y, z, dateTime)
Convert from geocentric solar magnetospheric to solar magnetic coordinates.
- x, y, z = GSEtoGSM(x, y, z, dateTime)
Convert from geocentric solar ecliptic to geocentric magnetospheric coordinates.
- kaipy.transform.GSEtoGSM(x, y, z, ut)
Convert coordinates from GSE (Geocentric Solar Ecliptic) to GSM (Geocentric Solar Magnetospheric) system.
- Parameters:
x (float) – X-coordinate in GSE system.
y (float) – Y-coordinate in GSE system.
z (float) – Z-coordinate in GSE system.
ut (datetime.datetime) – Universal Time (UT) for the conversion.
- Returns:
A tuple containing the converted X, Y, and Z coordinates in GSM system.
- Return type:
tuple
Examples
>>> GSEtoGSM(1, 2, 3, datetime.datetime(2009, 1, 27, 0, 0, 0)) (0.9999999999999998, 0.5403023058681398, 3.564718122410546)
Note
This function adapts code from scutils:convertGameraVec.
- kaipy.transform.GSMtoSM(x, y, z, ut)
Convert coordinates from GSM (Geocentric Solar Magnetospheric) system to SM (Solar Magnetic) system.
- Parameters:
x (float) – The x-coordinate in GSM system.
y (float) – The y-coordinate in GSM system.
z (float) – The z-coordinate in GSM system.
ut (datetime.datetime) – The universal time.
- Returns:
A tuple containing the converted x, y, and z coordinates in SM system.
- Return type:
tuple
Examples
>>> GSMtoSM(1, 2, 3, datetime.datetime(2009, 1, 27, 0, 0, 0)) (1.997..., 2.0, 2.451...)
- kaipy.transform.SMtoGSM(x, y, z, ut)
Convert coordinates from Solar Magnetic (SM) system to Geocentric Solar Magnetospheric (GSM) system.
- Parameters:
x (float) – The x-coordinate in SM system.
y (float) – The y-coordinate in SM system.
z (float) – The z-coordinate in SM system.
ut (datetime.datetime) – The Universal Time (UT) for the conversion.
- Returns:
A tuple containing the x, y, and z coordinates in GSM system.
- Return type:
tuple
Examples
>>> SMtoGSM(1, 2, 3, datetime.datetime(2009, 1, 27, 0, 0, 0)) (-0.126..., 2.0, 3.159...)