API Reference¶
Data loading is handled by the mojito package. This package provides utilities for loading, processing, and writing LISA Mojito L1 data.
I/O¶
- MojitoProcessor.io.read.load_file(paths, *, load_days=None)[source]¶
Load a raw Mojito L1 HDF5 file.
Uses the
mojitopackage to open the file and extracts TDI observables, light travel times, spacecraft orbits, noise estimates, and metadata into a flat dictionary suitable forprocess_pipeline().- Parameters:
paths (
str|Path|list[str|Path]) – Path(s) to the Mojito L1.h5file(s).load_days (
float|None) – Number of days to load from the start of the file (lazy slicing).Noneloads the full dataset.
- Return type:
dict- Returns:
data (dict) – Dictionary containing:
tdis— dict of TDI channel arrays (X, Y, Z, A, E, T)fs,dt,t_tdi— TDI sampling parameters and timestampsltts,ltt_derivatives,ltt_times— light travel timesorbits,velocities,orbit_times— spacecraft kinematicsnoise_estimates— frequency-domain noise covariance cubesmetadata— laser frequency and pipeline names
- MojitoProcessor.io.read.load_processed(path, *, segment_ids=None)[source]¶
Load processed segments from an HDF5 file written by
write().Reconstructs each
SignalProcessorfrom the stored channel arrays and metadata attributes. Per-segment orbit and LTT data (written under/raw/<segment_name>/) are returned alongside the segments in a raw data dict.- Parameters:
path (
str|Path) – Path to a.h5file previously written bywrite().segment_ids (
Optional[list]) – Indices of segments to load, e.g.[100, 101, 102]loads onlysegment100,segment101, andsegment102.None(default) loads all segments.
- Return type:
tuple[Dict[str,SignalProcessor],dict]- Returns:
segments (dict of SignalProcessor) – Dictionary mapping segment names to reconstructed
SignalProcessorobjects.raw_data (dict) – Auxiliary data dict. Top-level keys:
'orbits'— per-spacecraft position/velocity arrays (full span)'noise_estimates'— dict of noise covariance arrays (if present)'metadata'— dict withlaser_frequency/pipeline_names(if present)'<seg_name>_ltts'— one entry per segment containing LTT arrays:ltts,ltt_derivatives(if present),ltt_times
- Raises:
ValueError – If the file does not contain a
/processedgroup, indicating it was not written bywrite().
Examples
>>> from MojitoProcessor import write, load_processed >>> write("processed.h5", segments, raw_data=data) >>> segments, raw = load_processed("processed.h5") >>> sp = segments["segment0"] >>> orbit_positions = raw["segment0"]["orbits"]
- MojitoProcessor.io.write.write(output_path, segments, raw_data=None, *, segment_ids=None, filter_kwargs=None, downsample_kwargs=None, trim_kwargs=None, truncate_kwargs=None, window_kwargs=None)[source]¶
Write processed segments and raw auxiliary data to an HDF5 file.
- Return type:
None- Parameters:
output_path (str | Path)
segments (Dict[str, SignalProcessor])
raw_data (dict | None)
segment_ids (list | None)
filter_kwargs (dict | None)
downsample_kwargs (dict | None)
trim_kwargs (dict | None)
truncate_kwargs (dict | None)
window_kwargs (dict | None)
File layout¶
- /processed/
- <segment_name>/ one group per segment
<channel> processed time-domain array (e.g. X, Y, Z) t time array in seconds (TCB) attrs: fs, dt, N, T, t0, channels
- /pipeline_params/
filter/ attrs: highpass_cutoff, lowpass_cutoff, order, … downsample/ attrs: target_fs, kaiser_window trim/ attrs: fraction truncate/ attrs: days window/ attrs: window, alpha
- /raw/ only written when raw_data is provided
- orbits/ full-span orbit arrays
sc_position_1 spacecraft 1 positions (n_orbit, 3) [m] sc_position_2 sc_position_3 sc_velocity_1 spacecraft 1 velocities (n_orbit, 3) [m/s] sc_velocity_2 sc_velocity_3 times orbit sample timestamps (TCB) [s]
- noise_estimates/
xyz noise covariance cube (freq, ch, ch) aet noise covariance cube (freq, ch, ch)
- metadata/
attrs: laser_frequency, pipeline_names
- <segment_name>/ one group per segment
- ltts/
<link> light travel times sliced to segment window derivatives/
<link> LTT time-derivatives
times LTT sample timestamps for this segment
LTT data are sliced to each segment’s time window using the segment’s
t0and time array. Segments without a validt0(stored as NaN) are skipped for per-segment raw data.- param output_path:
Destination file path. Created (or overwritten) by this function.
- type output_path:
str|Path- param segments:
Output of
process_pipeline().- type segments:
Dict[str,SignalProcessor]- param raw_data:
Raw data dict returned by
load_file(). When provided, noise estimates and metadata are written under/raw/, and orbit/LTT data are written per-segment under/raw/<segment_name>/.- type raw_data:
Optional[dict]- param segment_ids:
Indices of segments to write, e.g.
[0, 17]writessegment0andsegment17.None(default) writes all segments.- type segment_ids:
Optional[list]- param filter_kwargs:
Pipeline parameter dicts, stored verbatim under
/pipeline_params/.- type filter_kwargs:
Optional[dict]- param downsample_kwargs:
Pipeline parameter dicts, stored verbatim under
/pipeline_params/.- type downsample_kwargs:
Optional[dict]- param trim_kwargs:
Pipeline parameter dicts, stored verbatim under
/pipeline_params/.- type trim_kwargs:
Optional[dict]- param truncate_kwargs:
Pipeline parameter dicts, stored verbatim under
/pipeline_params/.- type truncate_kwargs:
Optional[dict]- param window_kwargs:
Pipeline parameter dicts, stored verbatim under
/pipeline_params/.- type window_kwargs:
Optional[dict]
Signal Processing¶
- class MojitoProcessor.process.sigprocess.SignalProcessor(data, fs, t0=None)[source]¶
Bases:
objectSignal processor for multi-channel time series data.
Handles filtering, downsampling, trimming, and windowing while automatically tracking sampling parameters (fs, N, T, dt).
- Parameters:
data (
Dict[str,ndarray]) – Dictionary of channel data, e.g., {‘X’: array, ‘Y’: array, ‘Z’: array}fs (
float) – Sampling frequency in Hzt0 (float | None)
- data¶
Current processed data (updated after each operation). Includes a
't'key giving the time array[t0, t0+dt, ..., t0+(N-1)*dt]in seconds (or[0, dt, ..., (N-1)*dt]whent0isNone).- Type:
dict
- fs¶
Current sampling frequency in Hz
- Type:
float
- N¶
Current number of samples per channel
- Type:
int
- T¶
Current duration in seconds
- Type:
float
- dt¶
Current sampling period in seconds
- Type:
float
- t¶
Time array
[t0, t0+dt, ..., t0+(N-1)*dt]in seconds.- Type:
ndarray
- channels¶
List of channel names
- Type:
list
Example
>>> sp = SignalProcessor({'X': x_data, 'Y': y_data}, fs=4.0) >>> filtered = sp.filter(low=1e-4, high=1.0, order=6) >>> trimmed = sp.trim(fraction=0.02) # Trim 2% total (1% each end) >>> windowed = sp.apply_window(window='tukey', alpha=0.05) >>> t = sp.data['t'] # time array [t0, t0+dt, ..., t0+(N-1)*dt]
- property data: dict¶
Channel data as a dict, including a
't'key for the time array.The time array is
t0 + np.arange(N) * dt(seconds). Whent0isNone, the array starts from 0.- Returns:
dict – All channel arrays plus
't'.
- property t: ndarray¶
Time array
[t0, t0+dt, ..., t0+(N-1)*dt]in seconds.
- filter(*, low=None, high=None, order=2, filter_type='butterworth', zero_phase=True)[source]¶
Apply filter to all channels (auto-detects highpass/lowpass/bandpass).
Automatically determines filter type based on provided cutoff frequencies: - Only low set: highpass filter - Only high set: lowpass filter - Both low and high set: bandpass filter
- Parameters:
low (
Optional[float]) – Lower cutoff frequency in Hz (highpass)high (
Optional[float]) – Upper cutoff frequency in Hz (lowpass)order (
int) – Filter order (default: 6)filter_type (
str) – Filter type: ‘butterworth’, ‘chebyshev1’, ‘chebyshev2’, ‘bessel’ (default: ‘butterworth’)zero_phase (
bool) – Use zero-phase filtering (filtfilt) if True, else single-pass (default: True)
- Return type:
Dict[str,ndarray]- Returns:
filtered_data (dict) – Dictionary of filtered channel data
- Raises:
ValueError – If neither low nor high is provided
Examples
>>> # Highpass only >>> sp.filter(low=5e-6, order=2) >>> # Lowpass only >>> sp.filter(high=0.1, order=2) >>> # Bandpass >>> sp.filter(low=1e-4, high=0.1, order=6)
- downsample(target_fs, window=('kaiser', 31.0), padtype='line')[source]¶
Resample all channels to a target sampling rate using polyphase filtering.
Uses
scipy.signal.resample_polywhich applies a zero-phase FIR anti-aliasing filter via polyphase decomposition. Accepts arbitrary rational target rates (e.g., 4 Hz -> 0.4 Hz), unlikedecimatewhich requires an integer factor.- Parameters:
target_fs (
float) – Desired output sampling frequency in Hz. Must be positive and less than or equal to the current sampling frequency (this method is a downsampler).window (
tuple) – Window specification passed toscipy.signal.resample_polyfor FIR anti-aliasing filter design. Default('kaiser', 5.0)is scipy’s own default and gives good stopband attenuation.padtype (
str) – Edge-padding strategy. Options:'line'(default),'constant','mean','median','maximum','minimum'.'line'extends the signal linearly from each end, reducing edge transients for slowly-varying data such as LISA TDI channels.
- Return type:
Tuple[Dict[str,ndarray],float]- Returns:
resampled_data (dict) – Dictionary mapping channel names to resampled 1D arrays.
new_fs (float) – Actual output sampling frequency in Hz (exact rational result
self.fs * up / down).
- Raises:
ValueError – If
target_fsis not positive.ValueError – If
target_fsexceeds the current sampling frequency.ValueError – If the rational approximation of
target_fs / self.fsproducesup == 0.
Notes
The up/down integers are computed via:
ratio = Fraction(target_fs / self.fs).limit_denominator(10000) up, down = ratio.numerator, ratio.denominator
Common use cases from 4 Hz source data:
4 Hz -> 1 Hz: up=1, down=4
4 Hz -> 0.4 Hz: up=1, down=10
4 Hz -> 2 Hz: up=1, down=2
4 Hz -> 3 Hz: up=3, down=4
Examples
>>> sp = SignalProcessor({'X': x_data, 'Y': y_data}, fs=4.0) >>> sp.filter(low=5e-6, order=2) >>> sp.trim(fraction=0.022) # Trim 2.2% total >>> resampled, new_fs = sp.downsample(target_fs=1.0) >>> print(new_fs) # 1.0
- trim(fraction=None, *, n_samples=None)[source]¶
Trim data by removing samples from each end.
Exactly one of fraction or n_samples must be provided.
- Parameters:
fraction (
Optional[float]) – Total fraction of data to remove, split equally between both ends (e.g., 0.02 removes 1 % from each end). Must be in[0, 1).n_samples (
Optional[int]) – Exact number of samples to remove from each end (keyword-only). Use this when the trim should be based on filter settling time rather than a fixed fraction of the segment length.
- Return type:
Dict[str,ndarray]- Returns:
trimmed_data (dict) – Dictionary of trimmed channel data.
- Raises:
ValueError – If neither or both of fraction and n_samples are provided, if fraction is outside
[0, 1), if n_samples is negative, or if trimming would remove all data.
Examples
>>> sp.trim(fraction=0.02) # 2 % total — existing API >>> sp.trim(n_samples=27014) # exactly 27 014 samples per end
- apply_window(window='tukey', **window_params)[source]¶
Apply window function to all channels.
- Parameters:
window (
str) – Window type: ‘tukey’, ‘blackmanharris’, ‘hann’, ‘hamming’, ‘blackman’, ‘planck’ (default: ‘tukey’)**window_params – Additional parameters for the window function.
alpha(float, default 0.05) is accepted by ‘tukey’ and ‘planck’. Other windows ignore extra keyword arguments (a warning is emitted).
- Return type:
Dict[str,ndarray]- Returns:
windowed_data (dict) – Dictionary of windowed channel data
Examples
>>> sp.apply_window('tukey', alpha=0.05) >>> sp.apply_window('blackmanharris') >>> sp.apply_window('hann')
- periodogram()[source]¶
Compute the one-sided power spectral density for each channel.
The data is assumed to have already been windowed (e.g. by
apply_window()), so no additional window is applied here.Normalisation follows Parseval’s theorem: the integral of the one-sided PSD over positive frequencies equals the mean square of the signal.
- Return type:
Tuple[ndarray,Dict[str,ndarray]]- Returns:
freqs (ndarray) – Frequency array in Hz, shape
(N//2 + 1,).psds (dict) – Dictionary mapping channel names to one-sided PSD arrays (units²/Hz), each with the same shape as
freqs.
Examples
>>> freqs, psds = sp.periodogram() >>> plt.loglog(freqs[1:], psds['X'][1:])
- fft()[source]¶
Compute the one-sided complex FFT spectrum for each channel.
The data is assumed to have already been windowed (e.g. by
apply_window()), so no additional window is applied here. Returns raw complex amplitudes fromnumpy.fft.rfft.- Return type:
Tuple[ndarray,Dict[str,ndarray]]- Returns:
freqs (ndarray) – Frequency array in Hz, shape
(N//2 + 1,).ffts (dict) – Dictionary mapping channel names to complex FFT arrays, each with shape
(N//2 + 1,).
Examples
>>> freqs, ffts = sp.fft() >>> plt.loglog(freqs[1:], np.abs(ffts['X'][1:]))
- to_aet()[source]¶
Transform XYZ Michelson channels to noise-orthogonal AET channels.
Uses the standard equal-arm combination:
A = (Z - X) / sqrt(2) E = (X - 2Y + Z) / sqrt(6) T = (X + Y + Z) / sqrt(3)
Returns a new
SignalProcessorwith channels['A', 'E', 'T'], inheritingfs,t0, and all derived parameters from the original.- Return type:
- Returns:
SignalProcessor – New processor with AET channel data.
- Raises:
ValueError – If any of the channels
'X','Y','Z'are missing.
Examples
>>> sp_xyz = processed_segments['segment0'] >>> sp_aet = sp_xyz.to_aet() >>> freqs, psds = sp_aet.periodogram()
- MojitoProcessor.process.sigprocess.process_pipeline(data, channels=None, *, filter_kwargs=None, downsample_kwargs=None, trim_kwargs=None, truncate_kwargs=None, window_kwargs=None)[source]¶
Run the full TDI data processing pipeline on a MojitoData object.
Applies the following steps in order:
Filter — band-pass (if
lowpass_cutoffgiven) or high-pass onlyDownsample — polyphase resampling to
target_fs(optional)Trim — removes edge artefacts introduced by the filter from both ends
Truncate — selects the first
truncate_daysof the processed dataWindow — tapers edges to reduce spectral leakage
Pipeline progress is emitted at
logging.INFOlevel via theMojitoUtils.SigProcessinglogger.- Parameters:
data (
dict) – Loaded LISA L1 data dict (fromload_file()). Must containdata['tdis'](channel arrays) anddata['fs'](sampling rate in Hz).channels (
Optional[List[str]]) – TDI channels to process. Default['X', 'Y', 'Z'].filter_kwargs (
Optional[Dict]) – Filter parameters. Keys: -highpass_cutoff(float): High-pass cutoff in Hz (default: 5e-6) -lowpass_cutoff(float, optional): Low-pass cutoff for band-pass -order(int): Filter order (default: 2) -filter_type(str): Filter type (default: ‘butterworth’)downsample_kwargs (
Optional[Dict]) – Downsampling parameters. Keys: -target_fs(float): Target sampling rate in Hz -kaiser_window(float): Kaiser window beta parameter (default: 31.0)trim_kwargs (
Optional[Dict]) – Trimming parameters. Omit (or passNone) to skip trimming. Keys: -fraction(float): Fraction to trim from each end (default: 0.0)truncate_kwargs (
Optional[Dict]) – Segmentation parameters. Keys: -days(float): Segment length in days (default: 4.0) Dataset is split into non-overlapping segments of this length. Each segment is independently windowed. Set toNoneto disable segmentation (returns single segment with full dataset). Note: Remainder samples shorter than a full segment are discarded.window_kwargs (
Optional[Dict]) – Windowing parameters. Omit (or passNone) to skip windowing. Keys: -window(str): Window type - ‘tukey’, ‘hann’, etc. (default: ‘tukey’) -alpha(float): Taper fraction for Tukey window (default: 0.025)
- Return type:
dict- Returns:
segments (dict of SignalProcessor) – Dictionary mapping segment names (
'segment0','segment1', …) toSignalProcessorobjects. Each segment contains windowed data ready for FFT analysis. Access viasegments['segment0'].data,segments['segment0'].fs, etc.
Pipelines¶
Gap Handling¶
- MojitoProcessor.gaps.mask.apply_raw_mask(data, mask)[source]¶
Apply a gap mask to all TDI channels in a raw data dictionary.
Creates a deep copy of data before multiplying, so the original dict is never modified. Only channels present in the dict’s
"tdis"sub-dict are touched; all other entries (ltts, orbits, metadata, …) are preserved unchanged.- Parameters:
data (
dict) – Raw data dict as returned byload_file(). Must contain a"tdis"key whose value is a dict of 1-D numpy arrays.mask (
ndarray) – 1-D float array of lengthdata["tdis"]["X"].size(or whichever channel is present). Values should be in[0, 1].
- Return type:
dict- Returns:
data_masked (dict) – Deep copy of data with every TDI channel multiplied by mask.
Examples
>>> data_masked = apply_raw_mask(data, smoothed_mask)
- MojitoProcessor.gaps.extend.compute_extended_mask(smoothed_mask, sp, filter_kwargs, downsample_kwargs, trim_kwargs, *, fs_raw, contamination_threshold=0.0001, min_clean_hours=12.0, mask_fs=None)[source]¶
Compute an extended binary mask that accounts for Butterworth filter leakage.
Mirrors the downsampling and trimming steps applied to the data, then filters
1 − smoothed_maskwith the same Butterworth filter used in the pipeline. Samples where the absolute leakage exceeds contamination_threshold are flagged as contaminated and excluded from the mask alongside the original gap samples. Short clean intervals (shorter than min_clean_hours) between excluded regions are merged via binary closing.- Parameters:
smoothed_mask (
ndarray) – 1-D float array at the raw (pre-downsample) sampling rate. Values in[0, 1]:1= data present,0= gap. Typically the output oflisagap.GapWindowGenerator.sp (SignalProcessor) – Processed segment (post-downsample, post-trim) whose length
sp.Ndefines the target output length. The segment may represent only part of the full dataset (e.g. segment0 of many).filter_kwargs (
dict) – Must contain"highpass_cutoff"(Hz). Optionally"lowpass_cutoff"and"order". Must match the kwargs passed toprocess_pipeline().downsample_kwargs (
dict) – Must contain"target_fs"(Hz). Must match the kwargs passed toprocess_pipeline().trim_kwargs (
dict) – Must contain"fraction"(trimmed fraction from each end). Must match the kwargs passed toprocess_pipeline().fs_raw (
float) – Sampling frequency (Hz) of smoothed_mask — the raw rate before downsampling. Passdata["fs"]from the output ofload_file().contamination_threshold (
float) – Absolute amplitude of the filtered gap indicator above which a sample is considered contaminated. Default:1e-4.min_clean_hours (
float) – Short clean gaps (in hours) between excluded regions that are shorter than this value will be merged into the surrounding excluded region via binary closing. Default:12.0.mask_fs (
float|None) – Internal sampling rate (Hz) at which the mask extension is computed. IfNone(default), usestarget_fsfrom downsample_kwargs. Set to a value lower thantarget_fsto reduce memory use when the data is kept at a high sampling rate — the contamination zones span hours, so a rate of 0.2 Hz is more than sufficient. The result is upsampled back tosp.Nvia nearest-neighbour before returning.
- Return type:
Tuple[ndarray,ndarray]- Returns:
extended_mask_binary (ndarray) – Boolean-valued float array (
0.0or1.0) of lengthsp.N.1.0indicates samples that are clean and not contaminated.gap_contamination (ndarray) – Float array of length
sp.Ncontaining the raw filter-leakage signalfiltered(1 − smoothed_mask)after downsampling and trimming. Inspect this to tune contamination_threshold.
Examples
>>> extended_mask, gap_contamination = compute_extended_mask( ... smoothed_mask, sp_0, ... filter_kwargs, downsample_kwargs, trim_kwargs, ... fs_raw=data["fs"], ... contamination_threshold=1e-4, ... min_clean_hours=12.0, ... mask_fs=0.2, ... )
- MojitoProcessor.gaps.segment.extract_clean_segments(sp, mask, *, min_clean_hours=8.0, max_segment_days=None)[source]¶
Extract contiguous clean segments from a processed SignalProcessor.
Identifies contiguous runs of
1in mask, discards runs shorter than min_clean_hours, and returns each remaining stretch as its ownSignalProcessor. If max_segment_days is set, any clean run longer than that limit is split greedily from the front into chunks of at most max_segment_days days; the final remainder is kept if it meets min_clean_hours, otherwise it is discarded.- Parameters:
sp (
SignalProcessor) – Processed multi-channel time series (e.g.segment0fromprocess_pipeline()).mask (
ndarray) – Binary mask at the same sampling rate as sp. Typically theextended_maskreturned bycompute_extended_mask(). Values must be 0 or 1 (int or float).min_clean_hours (
float) – Minimum duration (hours) for a clean stretch (or sub-chunk after splitting) to be kept. Default 8.0.max_segment_days (
Optional[float]) – Maximum duration (days) of any returned segment. Clean runs longer than this are split into chunks of exactly max_segment_days from the front, with the final remainder kept if it meets min_clean_hours.None(default) applies no upper limit.
- Return type:
Dict[str,SignalProcessor]- Returns:
segments (dict of SignalProcessor) –
{"segment0": sp0, "segment1": sp1, ...}where each value is a newSignalProcessorcontaining only the clean data for that stretch. Thet0attribute of each segment is set so thatsp_i.tgives the correct absolute timestamps.- Raises:
ValueError – If mask length does not match
sp.N.