π Ό oscfar.utils
- Functions
- π ΅ oscfar.utils.plot_colormaps
- π ΅ oscfar.utils.get_colormaps
- π ΅ oscfar.utils.make_json_serializable
- Classes
- π ² oscfar.utils.NpzReader
- π ² oscfar.utils.NpzWriter
- π ² oscfar.utils.Peaks
- π ² oscfar.utils.WaterFallImage
- π ² oscfar.utils.WaterFallAxes
- π ² oscfar.utils.WaterFallGrid
- π ² oscfar.utils.FitburstResultsReader
- π ² oscfar.utils.FitburstResultsWriter
Functions
π ΅ oscfar.utils.plot_colormaps
def plot_colormaps(gradient, cmap_category, category_name):
π ΅ oscfar.utils.get_colormaps
def get_colormaps():
Retrieves and categorizes available matplotlib colormaps, then plots them
by category for visual inspection.
This function fetches all registered colormaps in matplotlib, categorizes them based on common usage (perceptually uniform, sequential, diverging, qualitative, miscellaneous), and then uses `plot_colormaps` to display each category in separate figure windows.
Returns:
list[str]
: A sorted list of all available colormap names.
π ΅ oscfar.utils.make_json_serializable
def make_json_serializable(obj):
Recursively converts non-JSON serializable objects (primarily NumPy arrays)
within a data structure to their JSON serializable equivalents.
Parameters:
- obj: The object to convert. This can be a NumPy array, a dictionary, a list, or any other JSON serializable type.
Returns:
- A new object with NumPy arrays converted to lists, suitable for JSON serialization\
Classes
π ² oscfar.utils.NpzReader
class NpzReader(DataReader):
Class for reading .npz files containing spectrogram data.
Inherits from fitburst.backend.generic.DataReader.
Attributes:
- metadata (
dict
): Metadata associated with the data.
Functions:
π ΅ oscfar.utils.NpzReader.__init__
def __init__(self, fname):
Initializes the NpzReader with the given file and downsampling factor.
Parameters:
def __repr__(self):
Returns a string representation of the NpzReader object.
π ² oscfar.utils.NpzWriter
class NpzWriter(NpzReader):
Class for writing and manipulating .npz files containing spectrogram data.
Inherits from NpzReader.
Attributes:
- burst_parameters (
dict
): Parameters of the burst, such as amplitude, dispersion measure, scattering timescale, etc. - metadata (
dict
): Metadata associated with the data. - dm_index (
int
): Index for the dispersion measure parameter. - scattering_index (
int
): Index for the scattering index parameter. - spectral_index (
int
): Index for the spectral index parameter. - ref_freq (
float
): Reference frequency for spectral index calculations.
Functions:
π ΅ oscfar.utils.NpzWriter.__init__
def __init__(self, file_or_reader = None):
Initializes the NpzWriter with the given .npz file.
Parameters:
- file_or_reader (
str or NpzReader
): Path to the .npz file or NpzReader made for fileπ ΅ oscfar.utils.NpzWriter.set_data
def set_data(self, data, times, freqs, time_res, freq_res, bad_chans = []):
Sets the data and metadata for a new .npz file.
Parameters:
- data (
np.ndarray
): The spectrogram data (frequency x time). - times (
np.ndarray
): Array of time values for each time sample. - freqs (
np.ndarray
): Array of frequency values for each channel. - time_res (
float
): Time resolution of the data. - freq_res (
float
): Frequency resolution of the data. - bad_chans (
list
): List of indices of bad frequency channels. Defaults to [].π ΅ oscfar.utils.NpzWriter.remove_baseline
def remove_baseline(self, percent, step = 0.05, verbose = False, cutoff = 0.3):
Removes baseline from the start and end of the data based on SNR.
Iteratively reduces the percentage of data considered from the start and end until the SNR in those regions falls below a cutoff threshold. The arrival time parameter in burst_parameters is adjusted accordingly.
Parameters:
- percent (
float
): Initial percentage of data from the start and end to consider for baseline removal (between 0 and 1). - step (
float
): The step size by which the percentage is reduced in each iteration. Defaults to 0.05. - verbose (
bool
): If True, prints intermediate SNR values and percentages during the process. Defaults to False. - cutoff (
float
): The SNR threshold below which a region is considered baseline and removed. Defaults to 0.3.
Raises:
- RuntimeError: If the NpzWriter is set to create a new file but data has not been loaded using .set_data().
π ΅ oscfar.utils.NpzWriter.update_burst_parameters
def update_burst_parameters(self, **kwargs):
Updates the burst parameters with the provided keyword arguments.
Parameters:
- **kwargs: Keyword arguments representing burst parameters to update. Possible keys include:
- βamplitudeβ: Amplitude of the burst.
- βdmβ: Dispersion measure of the burst.
- βscattering_timescaleβ: Scattering timescale of the burst.
- βarrival_timeβ: Arrival time of the burst.
- βburst_widthβ: Intrinsic width of the burst.
- βspectral_runningβ: Spectral index of the burst.
π ΅ oscfar.utils.NpzWriter.save
def save(self, new_filepath: str):
Saves the processed data and burst parameters to a new .npz file.
Parameters:
class Peaks:
Class to hold results from OS-CFAR.
Attributes:
- peaks (
np.array
): First half of the OS-CFAR results containing the peaks resulting from the algorithm. - threshold (
np.array
): Second half of the OS-CFAR results containing the threshold used by the algorithm.
Functions:
π ΅ oscfar.utils.Peaks.__init__
def __init__(self, oscfar_result):
Initializes the Peaks object with the result from OS-CFAR.
Parameters:
- oscfar_result (
tuple
): A tuple containing the detected peak indices and the threshold array.π ² oscfar.utils.WaterFallImage
class WaterFallImage:
Base class for creating matplotlib figures and axes for waterfall plots.
Provides basic functionality for changing figure size, showing, and saving plots. Intended to be inherited by classes that create specific plot layouts.
Attributes:
- cmap (
str
): The default colormap to use for the spectrogram image. Defaults to βgist_yargβ.
Functions:
π ΅ oscfar.utils.WaterFallImage.__init__
def __init__(self):
π ΅ oscfar.utils.WaterFallImage.change_size
def change_size(self, width, height):
Changes the size of the figure containing the axes.
Parameters:
- width (
float
): The new width of the figure in inches. - height (
float
): The new height of the figure in inches.π ΅ oscfar.utils.WaterFallImage.show
def show(self, block = None):
Displays the plot.
Parameters:
- block (
bool
): Whether to block the execution until the plot window is closed. Defaults to None, which uses the matplotlib default.π ΅ oscfar.utils.WaterFallImage.save
def save(self, fname):
Saves the current plot to a file.
Parameters:
- fname (
str
): The filename (including path and extension) to save the plot to.π ² oscfar.utils.WaterFallAxes
class WaterFallAxes(WaterFallImage):
Class to create matplotlib axes for a single waterfall plot, including
optional time series and spectrum plots.
Inherits from WaterFallImage.
Attributes:
- im (
matplotlib.axes.Axes
): Axes object for the main spectrogram image. - ts (
matplotlib.axes.Axes or None
): Axes object for the time series plot, or None if show_ts is False. - spec (
matplotlib.axes.Axes or None
): Axes object for the spectrum plot, or None if show_spec is False. - show_ts (
bool
): Whether the time series plot is included. - show_spec (
bool
): Whether the spectrum plot is included. - _data (
NpzReader or None
): Stores the data reader object after plotting. - _time_series (
np.ndarray or None
): Stores the summed time series after plotting. - _freq_series (
np.ndarray or None
): Stores the summed frequency series after plotting.
Functions:
π ΅ oscfar.utils.WaterFallAxes.__init__
def __init__(self, width: float = 0.75, height: float = 0.75, bottom: float = 0.1, left: float = None, hratio: float = 1, vratio: float = 1, show_ts = True, show_spec = True, labels_on = [True, True]):
Initializes the WaterFallAxes object.
Parameters:
- width (
float
) (default:0.75
): Width of the main spectrogram plot. Defaults to 0.75. - height (
float
) (default:0.75
): Height of the main spectrogram plot. Defaults to 0.75. - bottom (
float
): Bottom position of the main spectrogram plot. - left (
float
): Left position of the main spectrogram plot. Defaults to the value of βbottomβ. - hratio (
float
) (default:1
): Horizontal ratio for plot dimensions. Defaults to 1. - vratio (
float
) (default:1
): Vertical ratio for plot dimensions. Defaults to 1. - show_ts (
bool
) (default:True
): Whether to show the time series plot. Defaults to True. - show_spec (
bool
) (default:True
): Whether to show the spectrum plot. Defaults to True. - labels_on (
list
): List of two booleans indicating whether to show labels on the x and y axes, respectively. Defaults to [True, True].π ΅ oscfar.utils.WaterFallAxes.plot
def plot(self, data: NpzReader, title = '', readjust_title = 0):
Plots the spectrogram, time series, and spectrum on the created axes.
Parameters:
- data (
NpzReader
): DataReader object containing the spectrogram data. - title (
str
) (default:""
): Title of the plot. Defaults to ββ. - readjust_title (
int
) (default:0
): Vertical adjustment for the title position. Defaults to 0.π ΅ oscfar.utils.WaterFallAxes.plot_time_peaks
def plot_time_peaks(self, peaks: Peaks, color, show_thres = False):
Plots vertical lines on the spectrogram at the time indices of the detected peaks.
Also plots the peaks on the time series plot if it is shown.
Parameters:
- peaks (
Peaks
): An object containing the peak indices and threshold. - color (
str
): Color for the vertical lines and scatter points. - show_thres (
bool
): Whether to show the threshold on the time series plot.π ² oscfar.utils.WaterFallGrid
class WaterFallGrid(WaterFallImage):
Class to create a grid of waterfall plots (spectrograms) with associated time series and spectra.
Inherits from WaterFallImage.
Attributes:
- nrows (
int
): Number of rows in the grid. - ncols (
int
): Number of columns in the grid. - axes (
np.ndarray
): A 2D array of WaterFallAxes objects, representing each subplot in the grid. - vs (
float
): Vertical spacing between plots. - hs (
float
): Horizontal spacing between plots.
Functions:
π ΅ oscfar.utils.WaterFallGrid.__init__
def __init__(self, nrows: int, ncols: int, vspacing = 0.1, hspacing = 0.1):
Initializes the WaterFallGrid object.
Parameters:
- nrows (
int
): Number of rows in the grid. - ncols (
int
): Number of columns in the grid. - vspacing (
float
) (default:0.1
): Vertical spacing between plots. Defaults to 0.1. - hspacing (
float
) (default:0.1
): Horizontal spacing between plots. Defaults to 0.1.π ΅ oscfar.utils.WaterFallGrid.plot
def plot(self, data: list, peaks: list, titles: list, color, labels = [True, False], adjust_t = 0, show_thres = False):
Plots the waterfall grid with the provided data, peaks, and titles.
Parameters:
- data (
list
): List of DataReader objects, one for each subplot. - peaks (
list
): List of Peaks objects, one for each subplot. - titles (
list
): List of titles for each subplot. - color (
str
): Color for the peak markers. - labels (
list
): List of two booleans indicating whether to show labels on the x and y axes, respectively. Defaults to [True, False]. - adjust_t (
int
) (default:0
): Vertical adjustment for the title position. Defaults to 0. - show_thres (
bool
): Whether to show the threshold on the time series plot.π ΅ oscfar.utils.WaterFallGrid.add_info
def add_info(self, info: pd.DataFrame):
Adds a table with additional information below the grid.
Parameters:
- info (
pd.DataFrame
): DataFrame containing the information to be displayed.π ² oscfar.utils.FitburstResultsReader
class FitburstResultsReader:
Class to read and access results from a fitburst JSON output file.
Attributes:
- filepath (
str
): Path to the fitburst JSON results file. - results (
dict
): Dictionary containing the loaded JSON data. - initial_dm (
float
): Initial DM used in the fit. - initial_time (
float
): Initial time used in the fit. - (various attributes): Attributes corresponding to keys in the βfit_statisticsβ section of the JSON, including best-fit parameters and their uncertainties as `uncertainties.ufloat` objects.
Functions:
π ΅ oscfar.utils.FitburstResultsReader.__init__
def __init__(self, filepath: str):
Initializes the FitburstResultsReader with the path to the JSON results file.
Parameters:
- filepath (
str
): Path to the JSON file containing fitburst results.π ΅ oscfar.utils.FitburstResultsReader.get_fit_statistics
def get_fit_statistics(self):
Returns the βfit_statisticsβ section of the fitburst results.
Returns:
dict
: A dictionary containing fit statistics.π ΅ oscfar.utils.FitburstResultsReader.get_model_parameters
def get_model_parameters(self):
Returns the βmodel_parametersβ section of the fitburst results.
Returns:
dict
: A dictionary containing model parameters.π ΅ oscfar.utils.FitburstResultsReader.get_fit_logistics
def get_fit_logistics(self):
Returns the βfit_logisticsβ section of the fitburst results.
Returns:
dict
: A dictionary containing fit logistics.
π ² oscfar.utils.FitburstResultsWriter
class FitburstResultsWriter:
Class to write and save results from a fitburst LSFitter object to a JSON file.
Attributes:
- info (
LSFitter
): The LSFitter object containing the fit results.
Functions:
π ΅ oscfar.utils.FitburstResultsWriter.__init__
def __init__(self, info: LSFitter):
Initializes the FitburstResultsWriter with an LSFitter object.
Parameters:
- info (
LSFitter
): An instance of the LSFitter class containing the results of a fitburst analysis.π ΅ oscfar.utils.FitburstResultsWriter.get_fit_statistics
def get_fit_statistics(self):
Returns the βfit_statisticsβ section from the LSFitter object.
Returns:
dict
: A dictionary containing fit statistics.π ΅ oscfar.utils.FitburstResultsWriter.get_model_parameters
def get_model_parameters(self):
Returns the βmodel_parametersβ section from the LSFitter objectβs model.
Returns:
dict
: A dictionary containing model parameters.π ΅ oscfar.utils.FitburstResultsWriter.get_fit_logistics
def get_fit_logistics(self):
Returns the βfit_logisticsβ section from the LSFitter object.
Returns:
def save(self, filepath: str):
Saves the fitburst results to a JSON file.
Parameters:
- filepath (
str
): The path to the JSON file where the results will be saved.