Kaira API Reference

Note

Kaira version 0.2.1 documentation. For older versions, please refer to the version selector above.

This documentation provides a comprehensive reference of Kaira’s components organized by functional category. Each component is documented with its parameters, methods, and usage examples.

Overview

Kaira is a modular toolkit for communication systems built on PyTorch. The library is organized into several key modules that handle different aspects of communication systems:

  • Channels: Model transmission mediums with various noise and distortion characteristics

  • Constraints: Enforce practical limitations on transmitted signals

  • Metrics: Evaluate quality and performance of communication systems

  • Models: Implement neural network architectures for encoding/decoding and end-to-end communication systems

  • Modulations: Implement digital modulation schemes for wireless transmission

  • Losses: Provide objective functions for training neural networks

  • Utilities: Helper functions and tools for common operations

Base Components

Base classes define the fundamental interfaces that all implementations must adhere to. These abstract classes establish the contract that derived classes must fulfill.

channels.BaseChannel

Base abstract class for communication channel models.

constraints.BaseConstraint

Abstract foundation for implementing signal constraints in PyTorch-compatible format.

metrics.BaseMetric

Base Metric Module.

models.BaseModel

Abstract base class for all models in the Kaira framework.

modulations.BaseModulator

Abstract base class for all modulators.

modulations.BaseDemodulator

Abstract base class for all demodulators.

losses.BaseLoss

Base class for all Kaira loss functions.

Channels

Channel models for communication systems.

This package provides various channel models for simulating communication systems, including analog and digital channels, with support for various noise models, distortions, and fading patterns.

AWGNChannel

Additive white Gaussian noise (AWGN) channel for signal transmission.

BaseChannel

Base abstract class for communication channel models.

BinaryErasureChannel

Binary Erasure Channel (BEC) with symbol erasure probability.

BinarySymmetricChannel

Binary Symmetric Channel (BSC) with symmetric bit flip probability.

BinaryZChannel

Z Channel (asymmetric binary channel) with one-sided error probability.

ChannelRegistry

A registry for channels in Kaira.

FlatFadingChannel

Flat fading channel with configurable distribution and coherence time.

GaussianChannel

alias of AWGNChannel

IdealChannel

alias of PerfectChannel

IdentityChannel

alias of PerfectChannel

LambdaChannel

Customizable channel that applies user-defined functions to signals.

LaplacianChannel

Channel with additive Laplacian (double-exponential) noise.

LogNormalFadingChannel

Log-normal fading channel with configurable shadowing standard deviation.

NonlinearChannel

General nonlinear channel with configurable transfer function.

PerfectChannel

Identity channel that passes signals through unchanged.

PhaseNoiseChannel

Channel that introduces random phase noise.

PoissonChannel

Channel with signal-dependent Poisson noise.

RayleighFadingChannel

Specialized channel for Rayleigh fading in wireless communications.

RicianFadingChannel

Rician fading channel with configurable K-factor and coherence time.

UplinkMACChannel

Uplink Multiple Access Channel (MAC) for modeling multi-user uplink communications.

Constraints

Constraints module for Kaira.

This module contains various constraints that can be applied to transmitted signals in wireless communication systems. These constraints ensure signals meet practical requirements such as power limitations, hardware capabilities, and regulatory specifications.

Available constraint categories: - Base constraint definitions: Abstract base classes for all constraints - Power constraints: Control total power, average power, and PAPR - Antenna constraints: Manage power distribution across multiple antennas - Signal constraints: Handle amplitude limitations and spectral properties - Constraint composition: Combine multiple constraints sequentially

The module also provides factory functions for creating common constraint combinations and utilities for testing and validating constraint effectiveness.

Example:
>>> from kaira.constraints import TotalPowerConstraint, PAPRConstraint
>>> from kaira.constraints.utils import combine_constraints
>>>
>>> # Create individual constraints
>>> power_constr = TotalPowerConstraint(total_power=1.0)
>>> papr_constr = PAPRConstraint(max_papr=4.0)
>>>
>>> # Combine constraints into a single operation
>>> combined = combine_constraints([power_constr, papr_constr])
>>>
>>> # Apply to a signal
>>> constrained_signal = combined(input_signal)

AveragePowerConstraint

Scales signal to achieve specified average power per sample.

BaseConstraint

Abstract foundation for implementing signal constraints in PyTorch-compatible format.

CompositeConstraint

Applies multiple constraints in sequence.

ConstraintRegistry

A registry for constraints in Kaira.

IdentityConstraint

Identity constraint that returns the input signal unchanged.

LambdaConstraint

Constraint that applies a user-defined function to the signal.

PAPRConstraint

Reduces peak-to-average power ratio using soft clipping to minimize signal distortion.

PeakAmplitudeConstraint

Enforces maximum signal amplitude by clipping values that exceed threshold.

PerAntennaPowerConstraint

Distributes power budget across multiple antennas to ensure per-antenna power limits.

SpectralMaskConstraint

Restricts signal frequency components to comply with regulatory spectral masks.

TotalPowerConstraint

Normalizes signal to achieve exact total power regardless of input signal power.

Utils

Utility functions for constraints.

This module provides helper functions for creating, testing, validating, and working with constraints in wireless communication systems. These utilities streamline the process of configuring common constraint combinations and verifying constraint effectiveness.

apply_constraint_chain

Apply a list of constraints in sequence and optionally print debug info.

combine_constraints

Combine multiple constraints into a single constraint.

create_mimo_constraints

Create constraints commonly used in MIMO systems.

create_ofdm_constraints

Create constraints commonly used in OFDM systems.

measure_signal_properties

Measure common signal properties for a given tensor.

verify_constraint

Verify that a constraint produces the expected property in the output.

Metrics

Metrics module for Kaira.

This module contains various metrics for evaluating the performance of communication systems.

BaseMetric

Base Metric Module.

CompositeMetric

A metric that combines multiple metrics with optional weighting.

MetricRegistry

A registry for metrics in Kaira.

Image

Image metrics module.

This module contains metrics for evaluating image quality.

LPIPS

alias of LearnedPerceptualImagePatchSimilarity

LearnedPerceptualImagePatchSimilarity

Learned Perceptual Image Patch Similarity (LPIPS) Module.

MultiScaleSSIM

Multi-Scale Structural Similarity Index Measure (MS-SSIM) Module.

PSNR

alias of PeakSignalNoiseRatio

PeakSignalNoiseRatio

Peak Signal-to-Noise Ratio (PSNR) Module.

SSIM

alias of StructuralSimilarityIndexMeasure

StructuralSimilarityIndexMeasure

Structural Similarity Index Measure (SSIM) Module.

Signal

Signal metrics module.

This module contains metrics for evaluating signal processing performance.

BER

alias of BitErrorRate

BLER

alias of BlockErrorRate

BitErrorRate

Bit Error Rate (BER) metric.

BlockErrorRate

Block Error Rate (BLER) metric.

EVM

alias of ErrorVectorMagnitude

ErrorVectorMagnitude

Error Vector Magnitude (EVM) metric.

FER

alias of BlockErrorRate

FrameErrorRate

alias of BlockErrorRate

SER

alias of BlockErrorRate

SNR

alias of SignalToNoiseRatio

SignalToNoiseRatio

Signal-to-Noise Ratio (SNR) metric.

SymbolErrorRate

alias of BlockErrorRate

Models

Models module for Kaira.

BaseModel

Abstract base class for all models in the Kaira framework.

ChannelCodeModel

A specialized model for Channel Code.

ConfigurableModel

Model that supports dynamically adding and removing steps.

DeepJSCCModel

Deep Joint Source-Channel Coding model.

FeedbackChannelModel

A model that models communication with a feedback channel.

ModelConfig

Base configuration class for Kaira models.

ModelRegistry

A registry for models in Kaira.

MultipleAccessChannelModel

A model simulating a Multiple Access Channel (MAC).

WynerZivModel

A model for Wyner-Ziv coding with decoder side information.

Forward Error Correction (FEC)

Forward Error Correction module for Kaira models.

This module provides comprehensive implementations for forward error correction, including both encoders and decoders for various coding schemes. The encoders and decoders are designed to work seamlessly together to provide robust error correction capabilities for communication systems.

Decoders

Forward Error Correction (FEC) decoders for Kaira.

This module provides various decoder implementations for forward error correction codes. The decoders in this module are designed to work seamlessly with the corresponding encoders from the kaira.models.fec.encoders module.

Example Usage
>>> from kaira.models.fec.encoders import BCHCodeEncoder
>>> from kaira.models.fec.decoders import BerlekampMasseyDecoder
>>> encoder = BCHCodeEncoder(15, 7)
>>> decoder = BerlekampMasseyDecoder(encoder)
>>> # Example decoding
>>> received = torch.tensor([1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1])
>>> decoded = decoder(received)

BaseBlockDecoder

Base class for block code decoders.

BeliefPropagationDecoder

Belief propagation decoder for linear block codes and LDPC codes.

BeliefPropagationPolarDecoder

Decoder for Polar code using Belief Propagation (BP) method.

BerlekampMasseyDecoder

Berlekamp-Massey decoder for BCH and Reed-Solomon codes.

BruteForceMLDecoder

Brute Force Maximum Likelihood decoder for block codes.

MinSumLDPCDecoder

Min-Sum decoder for LDPC codes [Chen et al., 2005].

ReedMullerDecoder

Reed-Muller decoder using majority-logic decoding.

SuccessiveCancellationDecoder

Decoder for Polar code using Successive Cancellation (SC) method [Arıkan, 2009].

SyndromeLookupDecoder

Syndrome lookup decoder for linear block codes.

WagnerSoftDecisionDecoder

Wagner soft-decision decoder for single parity-check codes.

Encoders

Forward Error Correction encoders for Kaira.

This module provides various encoder implementations for forward error correction.These encoders can be used to add redundancy to data for enabling error detection and correction in communication systems, storage devices, and other applications requiring reliable data transmission over noisy channels.

BCHCodeEncoder

Encoder for BCH (Bose–Chaudhuri–Hocquenghem) codes.

BaseBlockCodeEncoder

Base class for block code encoders.

CyclicCodeEncoder

Encoder for cyclic codes.

GolayCodeEncoder

Encoder for binary Golay codes.

HammingCodeEncoder

Encoder for Hamming codes.

LDPCCodeEncoder

Encoder for LDPC code [Gallager, 1962], [Gallager, 1963].

LinearBlockCodeEncoder

Encoder for linear block coding.

PolarCodeEncoder

Encoder for Polar code [Arıkan, 2008].

ReedMullerCodeEncoder

Encoder for Reed-Muller codes.

ReedSolomonCodeEncoder

Encoder for Reed-Solomon (RS) codes.

RepetitionCodeEncoder

Encoder for repetition coding that extends LinearBlockCodeEncoder.

SingleParityCheckCodeEncoder

Encoder for single parity-check codes.

SystematicLinearBlockCodeEncoder

Encoder for systematic linear block coding.

Soft Bit Thresholding

Soft bit thresholding module for binary data processing.

This module provides various thresholding techniques for converting soft bit representations (probabilities, LLRs, etc.) to hard decisions. These thresholders can be used with soft decoders or as standalone components in signal processing pipelines.

Soft bit processing is crucial in modern communication systems to extract maximum information from the received signals. The techniques implemented here are based on established methods in communication theory.

AdaptiveThresholder

Adaptive thresholder for soft bit values.

DynamicThresholder

Thresholder with dynamically adjusting threshold for non-stationary signals.

FixedThresholder

Simple fixed threshold for soft bit values.

HysteresisThresholder

Thresholder with hysteresis for robust decision making in noisy environments.

InputType

Enumeration of supported input types for soft bit thresholders.

LLRThresholder

Specialized thresholder for Log-Likelihood Ratio (LLR) values.

MinDistanceThresholder

Thresholder based on minimum distance calculations.

OutputType

Enumeration of supported output types for soft bit thresholders.

RepetitionSoftBitDecoder

Enhanced decoder for repetition coding with flexible soft bit processing.

SoftBitEnsembleThresholder

Ensemble thresholder that combines decisions from multiple thresholders.

SoftBitThresholder

Base class for soft bit thresholding techniques.

WeightedThresholder

Thresholder that applies weights to input values before thresholding.

Components

Components module for Kaira models.

AFModule

AFModule: Attention-Feature Module [Xu et al., 2021].

ConvDecoder

Convolutional Neural Network (CNN) Decoder for image transmission systems.

ConvEncoder

Convolutional Neural Network (CNN) Encoder for image transmission systems.

MLPDecoder

Multi-Layer Perceptron (MLP) Decoder for communication systems.

MLPEncoder

Multi-Layer Perceptron (MLP) Encoder for communication systems.

Projection

Projection layer for dimensionality reduction in communication systems [Yilmaz et al., 2025, Yilmaz et al., 2025].

ProjectionType

Enum for different types of projections.

Generic

Generic model implementations for Kaira.

This module provides generic model implementations that can be used as building blocks for more complex models, such as sequential, parallel, and branching models.

BranchingModel

Model that routes inputs through different paths based on conditions.

IdentityModel

Identity Model.

LambdaModel

Lambda Model.

ParallelModel

A model that processes steps in parallel.

SequentialModel

A model that processes steps sequentially.

Image

Image model implementations for Kaira.

This module provides models specifically designed for image data transmission.

Bourtsoulatze2019DeepJSCCDecoder

DeepJSCC decoder model from [Bourtsoulatze et al., 2019].

Bourtsoulatze2019DeepJSCCEncoder

DeepJSCC encoder model from [Bourtsoulatze et al., 2019].

DeepJSCCFeedbackDecoder

Decoder network for DeepJSCC with Feedback [Kurka and Gündüz, 2020].

DeepJSCCFeedbackEncoder

Encoder network for DeepJSCC with Feedback [Kurka and Gündüz, 2020].

DeepJSCCFeedbackModel

Deep Joint Source-Channel Coding with Feedback implementation [Kurka and Gündüz, 2020].

Tung2022DeepJSCCQ2Decoder

DeepJSCCQ2 Decoder Module [Tung et al., 2022].

Tung2022DeepJSCCQ2Encoder

DeepJSCCQ2 Encoder Module [Tung et al., 2022].

Tung2022DeepJSCCQDecoder

DeepJSCCQ Decoder Module [Tung et al., 2022].

Tung2022DeepJSCCQEncoder

DeepJSCCQ Encoder Module [Tung et al., 2022].

Xie2023DTDeepJSCCDecoder

Discrete Task-Oriented Deep JSCC decoder [Xie et al., 2023].

Xie2023DTDeepJSCCEncoder

Discrete Task-Oriented Deep JSCC encoder [Xie et al., 2023].

Yilmaz2023DeepJSCCNOMADecoder

DeepJSCC-NOMA Decoder Module [Yilmaz et al., 2023].

Yilmaz2023DeepJSCCNOMAEncoder

DeepJSCC-NOMA Encoder Module [Yilmaz et al., 2023].

Yilmaz2023DeepJSCCNOMAModel

Distributed Deep Joint Source-Channel Coding over a Multiple Access Channel [Yilmaz et al., 2023].

Yilmaz2024DeepJSCCWZConditionalDecoder

DeepJSCC-WZ Conditional Decoder Module [Yilmaz et al., 2024].

Yilmaz2024DeepJSCCWZConditionalEncoder

DeepJSCC-WZ Conditional Encoder Module [Yilmaz et al., 2024].

Yilmaz2024DeepJSCCWZDecoder

DeepJSCC-WZ Decoder Module [Yilmaz et al., 2024].

Yilmaz2024DeepJSCCWZEncoder

DeepJSCC-WZ Encoder Module [Yilmaz et al., 2024].

Yilmaz2024DeepJSCCWZModel

A specialized Wyner-Ziv model for neural joint source-channel coding with side information.

Yilmaz2024DeepJSCCWZSmallDecoder

DeepJSCC-WZ-sm Decoder Module [Yilmaz et al., 2024].

Yilmaz2024DeepJSCCWZSmallEncoder

DeepJSCC-WZ-sm Encoder Module [Yilmaz et al., 2024].

Compressors

Image compressor models, including standard and neural network-based methods.

BPGCompressor

BPG (Better Portable Graphics) image compression based on bpgenc and bpgdec.

BaseImageCompressor

Abstract base class for image compression methods.

JPEG2000Compressor

JPEG 2000 image compressor using JPEG 2000 via PIL/Pillow.

JPEGCompressor

JPEG image compressor using libjpeg via PIL/Pillow.

JPEGXLCompressor

JPEG XL image compressor using JPEG XL via PIL/Pillow.

NeuralCompressor

Neural network-based image compression model.

PNGCompressor

PNG image compressor using libpng via PIL/Pillow.

WebPCompressor

WebP image compressor using WebP via PIL/Pillow.

Modulations

Digital modulation schemes for wireless communications.

This package provides implementations of common digital modulation and demodulation techniques used in modern communication systems, including PSK, QAM, PAM, and differential modulation schemes.

BPSKDemodulator

Binary Phase-Shift Keying (BPSK) demodulator.

BPSKModulator

Binary Phase-Shift Keying (BPSK) modulator.

BaseDemodulator

Abstract base class for all demodulators.

BaseModulator

Abstract base class for all modulators.

DBPSKDemodulator

Differential Binary Phase-Shift Keying (DBPSK) demodulator.

DBPSKModulator

Differential Binary Phase-Shift Keying (DBPSK) modulator.

DPSKDemodulator

Differential Phase-Shift Keying (DPSK) demodulator.

DPSKModulator

Differential Phase-Shift Keying (DPSK) modulator.

DQPSKDemodulator

Differential Quadrature Phase-Shift Keying (DQPSK) demodulator.

DQPSKModulator

Differential Quadrature Phase-Shift Keying (DQPSK) modulator.

IdentityDemodulator

Identity demodulator that passes input data through unchanged.

IdentityModulator

Identity modulator that passes input data through unchanged.

ModulationRegistry

A registry for modulations in Kaira.

OQPSKDemodulator

Offset Quadrature Phase-Shift Keying (OQPSK) demodulator.

OQPSKModulator

Offset Quadrature Phase-Shift Keying (OQPSK) modulator.

PAMDemodulator

Pulse Amplitude Modulation (PAM) demodulator.

PAMModulator

Pulse Amplitude Modulation (PAM) modulator.

PSKDemodulator

General M-ary Phase-Shift Keying (PSK) demodulator.

PSKModulator

General M-ary Phase-Shift Keying (PSK) modulator.

Pi4QPSKDemodulator

Π/4-QPSK demodulator.

Pi4QPSKModulator

Π/4-QPSK (π/4 shifted QPSK) modulator.

QAMDemodulator

Quadrature Amplitude Modulation (QAM) demodulator.

QAMModulator

Quadrature Amplitude Modulation (QAM) modulator.

QPSKDemodulator

Quadrature Phase-Shift Keying (QPSK) demodulator.

QPSKModulator

Quadrature Phase-Shift Keying (QPSK) modulator.

Utils

Utility functions for digital modulation schemes.

binary_array_to_gray

Convert binary array to Gray code.

binary_to_gray

Convert binary number to Gray code.

calculate_spectral_efficiency

Calculate spectral efficiency of a modulation scheme in bits/s/Hz.

calculate_theoretical_ber

Calculate theoretical Bit Error Rate (BER) for common modulations.

gray_array_to_binary

Convert Gray-coded array to binary.

gray_to_binary

Convert Gray code to binary number.

plot_constellation

Plot a constellation diagram.

Losses

Kaira Losses Package.

This package provides various loss functions for different modalities.

BaseLoss

Base class for all Kaira loss functions.

CompositeLoss

A loss that combines multiple loss functions with optional weighting.

LossRegistry

A registry for loss functions in Kaira.

Image

Losses module for Kaira.

This module contains various loss functions for training communication systems, including MSE loss, LPIPS loss, and SSIM loss. These loss functions are widely used in image processing and computer vision tasks [Wang and Bovik, 2009] [Zhang et al., 2018].

CombinedLoss

Combined Loss Module.

FocalLoss

Focal Loss Module for dealing with class imbalance.

GradientLoss

Gradient Loss Module.

L1Loss

L1 (Mean Absolute Error) Loss Module.

LPIPSLoss

Learned Perceptual Image Patch Similarity (LPIPS) Loss Module.

MSELPIPSLoss

MSELPIPSLoss Module.

MSELoss

Mean Squared Error (MSE) Loss Module.

MSSSIMLoss

Multi-Scale Structural Similarity Index Measure (MS-SSIM) Loss Module.

PSNRLoss

Peak Signal-to-Noise Ratio (PSNR) Loss Module.

SSIMLoss

Structural Similarity Index Measure (SSIM) Loss Module.

StyleLoss

Style Loss Module based on Gram matrices.

TotalVariationLoss

Total Variation Loss Module.

VGGLoss

VGG Perceptual Loss Module.

Data

Data utilities for Kaira.

This module provides simple and efficient dataset classes for communication systems and information theory experiments. All datasets are memory-efficient and generate data on-demand.

BinaryDataset

Dataset for binary tensor data with configurable probability.

CorrelatedDataset

Dataset for correlated data pairs.

FunctionDataset

Dataset that applies a custom function to generate data.

GaussianDataset

Dataset for Gaussian distributed tensor data.

ImageDataset

Simple wrapper for common image datasets.

UniformDataset

Dataset for uniformly distributed tensor data.

Datasets

Simple and efficient dataset implementations for Kaira.

This module provides dataset classes for communication systems and information theory experiments. All datasets generate data on-demand for memory efficiency and support PyTorch DataLoader.

BinaryDataset

Dataset for binary tensor data with configurable probability.

CorrelatedDataset

Dataset for correlated data pairs.

FunctionDataset

Dataset that applies a custom function to generate data.

GaussianDataset

Dataset for Gaussian distributed tensor data.

UniformDataset

Dataset for uniformly distributed tensor data.

Sample Data

Simple image dataset utilities for Kaira.

This module provides basic image dataset functionality for testing and examples.

ImageDataset

Simple wrapper for common image datasets.

Utils

General utility functions for the Kaira library.

PlottingUtils

A comprehensive plotting utility class with static methods for visualization.

add_noise_for_snr

Add Gaussian noise to achieve a target Signal-to-Noise Ratio.

calculate_num_filters_factor_image

Calculate the number of filters in an image based on the number of strided layers and bandwidth ratio.

calculate_snr

Calculate the SNR between original and noisy signals.

estimate_signal_power

Estimate the power of a signal.

noise_power_to_snr

Calculate SNR in dB given signal and noise power.

seed_everything

Seed all random number generators to make runs reproducible.

snr_db_to_linear

Convert Signal-to-Noise Ratio from decibel to linear scale.

snr_linear_to_db

Convert Signal-to-Noise Ratio from linear scale to decibels.

snr_to_noise_power

Convert SNR in dB to noise power given a signal power.

to_tensor

Convert an input data into a torch.Tensor, with an option to move it to a specific device.

Snr

Utility functions for Signal-to-Noise Ratio (SNR) calculations and conversions.

add_noise_for_snr

Add Gaussian noise to achieve a target Signal-to-Noise Ratio.

calculate_snr

Calculate the SNR between original and noisy signals.

estimate_signal_power

Estimate the power of a signal.

noise_power_to_snr

Calculate SNR in dB given signal and noise power.

snr_db_to_linear

Convert Signal-to-Noise Ratio from decibel to linear scale.

snr_linear_to_db

Convert Signal-to-Noise Ratio from linear scale to decibels.

snr_to_noise_power

Convert SNR in dB to noise power given a signal power.

Training

Kaira training module.

This module provides training infrastructure for communication models, including: - TrainingArguments: Flexible training arguments supporting multiple config systems - Trainer: Unified trainer for all communication models

Examples:

Basic usage with TrainingArguments: >>> from kaira.training import TrainingArguments, Trainer >>> args = TrainingArguments(output_dir=”./results”, num_train_epochs=10) >>> trainer = Trainer(model, args)

Using Hydra configurations: >>> args = TrainingArguments.from_hydra(hydra_config) >>> trainer = Trainer.from_hydra_config(hydra_config, model)

Direct dict configurations: >>> args = TrainingArguments.from_dict({“output_dir”: “./results”}) >>> trainer = Trainer(model, args)

Trainer

Unified trainer for all communication models.

TrainingArguments

Training arguments that support Hydra configuration management.