### Install Kaira Python Library Source: https://github.com/ipc-lab/kaira/blob/main/docs/getting_started.rst Provides the command-line instruction to install the Kaira library using the pip package manager, ensuring the necessary dependencies are met for Kaira's functionalities. ```bash pip install pykaira ``` -------------------------------- ### Install Kaira from Source Repository Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Instructions to clone the Kaira repository from GitHub and install it locally from the source code, useful for accessing the latest features or contributing to the project. ```bash git clone https://github.com/ipc-lab/kaira.git cd kaira ``` ```bash pip install . ``` -------------------------------- ### Install Kaira via pip Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst The fastest way to install the Kaira library directly from PyPI using the pip package manager. ```bash pip install pykaira ``` -------------------------------- ### Install Kaira via pip Source: https://github.com/ipc-lab/kaira/blob/main/docs/introduction.rst This snippet demonstrates the primary method for installing the Kaira toolkit using the Python package manager, pip. This command will download and install the necessary packages to get started with Kaira. ```bash pip install pykaira ``` -------------------------------- ### Execute Kaira Example Scripts Source: https://github.com/ipc-lab/kaira/blob/main/examples/benchmarks/README.txt This command-line snippet provides instructions on how to run the various Kaira benchmarking example scripts directly from the terminal. It guides the user to navigate to the `examples/benchmarks` directory and execute each Python script, with results automatically saved to a local directory. ```bash cd examples/benchmarks python plot_basic_usage.py python plot_comparison_example.py python plot_demo_new_results_system.py python plot_visualization_example.py ``` -------------------------------- ### Install PyTorch with CUDA Support for Kaira GPU Acceleration Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Example command to install PyTorch with specific CUDA version support, a prerequisite for Kaira's GPU acceleration features. Users should verify the correct command on the PyTorch website for their specific system and CUDA version. ```bash pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 ``` -------------------------------- ### Build Kaira Example Gallery Documentation Source: https://github.com/ipc-lab/kaira/blob/main/examples/README.md Instructions to build the Sphinx-Gallery documentation for Kaira examples. This process compiles the example files into HTML documentation, making them accessible via a web browser. ```bash cd docs make html ``` -------------------------------- ### Install Kaira Python Package via pip Source: https://github.com/ipc-lab/kaira/blob/main/README.md This command installs the Kaira Python package directly from PyPI, making it available for use in your Python projects. It is the fastest and recommended way to get started with Kaira. ```Bash pip install pykaira ``` -------------------------------- ### Initialize Kaira BPGCompressor Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Python code demonstrating how to import and initialize the BPGCompressor class within Kaira, with options for setting image quality or maximum bits per image for BPG compression. ```python from kaira.models.image.compressors.bpg import BPGCompressor # Create BPG compressor with quality setting compressor = BPGCompressor(quality=30) # Or with target bits per image compressor = BPGCompressor(max_bits_per_image=1000) ``` -------------------------------- ### Makefile Usage Examples Source: https://github.com/ipc-lab/kaira/blob/main/docs/makefile.rst Demonstrates how to invoke Makefile targets from the command line, showing examples for displaying help information and running the test suite. ```bash # Display help information make help # Run the test suite make test ``` -------------------------------- ### Verify Kaira Installation Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst This command-line snippet checks if the Kaira library is successfully installed in your Python environment and prints its version. It's a quick way to confirm a correct setup. ```bash python -c "import kaira; print(f'Kaira version {kaira.__version__} successfully installed')" ``` -------------------------------- ### Verify BPG Command-Line Tools Installation Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Commands to test if the BPG encoder (bpgenc) and decoder (bpgdec) command-line tools are correctly installed and accessible in the system's PATH after installation. ```bash bpgenc bpgdec ``` -------------------------------- ### Run Kaira Examples for Testing Source: https://github.com/ipc-lab/kaira/blob/main/examples/README.md Commands to execute individual Kaira examples or all examples within a specific category for testing purposes. This ensures the examples run without errors and produce expected outputs. ```bash python examples/channels/plot_example.py ``` ```bash python -m pytest docs/auto_examples/channels/ -v ``` -------------------------------- ### Basic Kaira Communication System Simulation Source: https://github.com/ipc-lab/kaira/blob/main/docs/getting_started.rst Demonstrates a fundamental use case of Kaira by simulating a simple Additive White Gaussian Noise (AWGN) channel. It shows how to create a channel instance, generate random data using PyTorch, pass the data through the simulated channel, and print the shapes of the original and received data. ```python import torch import kaira # Create a simple AWGN channel channel = kaira.channels.AWGNChannel(snr_db=10.0) # Generate some random data to transmit data = torch.randn(100, 8) # Pass the data through the channel received_data = channel(data) print(f"Original data shape: {data.shape}") print(f"Received data shape: {received_data.shape}") ``` -------------------------------- ### Install Kaira in a Python Virtual Environment Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Recommended method for a clean installation of Kaira using a Python virtual environment, preventing conflicts with other system-wide packages. Includes commands for creating and activating the environment on different operating systems. ```bash # Create a virtual environment python -m venv kaira-env ``` ```bash # Activate the environment (Linux/macOS) source kaira-env/bin/activate ``` ```bash # Activate the environment (Windows) kaira-env\Scripts\activate ``` ```bash # Install Kaira pip install pykaira ``` -------------------------------- ### Verify CUDA Installation with PyTorch Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst This command-line snippet is used for troubleshooting GPU detection issues. It runs a Python command to check if PyTorch can detect an available CUDA device, indicating a proper CUDA setup. ```bash python -c "import torch; print(torch.cuda.is_available())" ``` -------------------------------- ### Install BPG Tools from Source on Linux Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Instructions to download, compile, and install the BPG (Better Portable Graphics) command-line tools from source on Linux (Ubuntu/Debian) systems, enabling BPG image compression support in Kaira. ```bash wget https://bellard.org/bpg/libbpg-0.9.8.tar.gz tar xzf libbpg-0.9.8.tar.gz cd libbpg-0.9.8 make sudo make install ``` -------------------------------- ### Kaira Integration with PyTorch for Deep Learning Source: https://github.com/ipc-lab/kaira/blob/main/docs/getting_started.rst Illustrates how Kaira can be seamlessly integrated into PyTorch deep learning workflows. This example defines a `SimpleAutoencoder` class that incorporates a Kaira channel within its `forward` method, demonstrating how to pass encoded data through a simulated channel before decoding. It sets up a model, channel, and dummy data, then performs a forward pass to show input and output tensor shapes. ```python import torch import torch.nn as nn import kaira # Define a simple autoencoder model class SimpleAutoencoder(kaira.models.BaseModel): def __init__(self, input_dim, latent_dim): super().__init__() self.encoder = nn.Sequential( nn.Linear(input_dim, 64), nn.ReLU(), nn.Linear(64, latent_dim) ) self.decoder = nn.Sequential( nn.Linear(latent_dim, 64), nn.ReLU(), nn.Linear(64, input_dim) ) def forward(self, x, channel): # Encode the input encoded = self.encoder(x) # Pass through the channel channel_out = channel(encoded) # Decode the channel output decoded = self.decoder(channel_out) return decoded # Create a model, channel, and some data model = SimpleAutoencoder(input_dim=28*28, latent_dim=16) channel = kaira.channels.AWGNChannel(snr_db=15.0) dummy_data = torch.randn(32, 28*28) # Batch of 32 images # Forward pass through the model and channel output = model(dummy_data, channel) print(f"Input shape: {dummy_data.shape}") print(f"Output shape: {output.shape}") ``` -------------------------------- ### Install Linux Build Tools for Kaira Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Command to install essential build tools and Python development headers on Ubuntu/Debian systems, which may be required for compiling certain Python packages during Kaira's installation. ```bash sudo apt-get install build-essential python3-dev ``` -------------------------------- ### Comprehensive Kaira Results Management Workflow Example Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst A full example demonstrating the complete workflow of setting up a `BenchmarkResultsManager`, configuring a `StandardRunner`, and running benchmark suites with automatic result organization. ```python # Create and configure results manager results_manager = BenchmarkResultsManager("example_results") # Run benchmarks with automatic result organization runner = StandardRunner(results_manager=results_manager) # Create and run benchmark suites suite = BenchmarkSuite("Performance Suite") # ... add benchmarks to suite results = runner.run_suite(suite, experiment_name="demo_experiment") # Results are automatically organized in structured directories ``` -------------------------------- ### Install BPG Tools on macOS using Homebrew Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst Instructions to install the BPG (Better Portable Graphics) command-line tools on macOS using Homebrew, including steps to install Homebrew, tap the core repository, and modify the libbpg formula to allow installation. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` ```bash brew tap homebrew/core --force ``` ```bash brew edit libbpg ``` ```bash HOMEBREW_NO_INSTALL_FROM_API=1 brew install libbpg ``` -------------------------------- ### Using the Kaira Benchmark CLI Tool Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst Provides examples of common command-line interface (CLI) commands for the `kaira-benchmark` tool, including listing available benchmarks, running single or multiple benchmarks, executing suites, and passing custom parameters. ```shell # List available benchmarks kaira-benchmark --list # Run a single benchmark kaira-benchmark --benchmark ber_simulation --config fast # Run multiple benchmarks in parallel kaira-benchmark --benchmark ber_simulation throughput_test --parallel # Run benchmark suite kaira-benchmark --suite --config comprehensive --output ./results # Custom parameters kaira-benchmark --benchmark ber_simulation --snr-range -5 10 --num-bits 50000 ``` -------------------------------- ### Define a Custom Kaira Benchmark Class Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst This example illustrates how to create a custom benchmark in Kaira by inheriting from `BaseBenchmark` and using the `@register_benchmark` decorator. It outlines the `setup` method for initialization and the `run` method for executing the benchmark logic and returning metrics. ```Python from kaira.benchmarks import BaseBenchmark, register_benchmark @register_benchmark("my_benchmark") class MyBenchmark(BaseBenchmark): def setup(self, **kwargs): super().setup(**kwargs) # Initialize benchmark def run(self, **kwargs): # Run benchmark and return metrics return {"success": True, "metric_value": 42} ``` -------------------------------- ### Manage Kaira Examples with Workflow Script Source: https://github.com/ipc-lab/kaira/blob/main/CONTRIBUTING.md Provides commands for previewing, syncing, and validating example galleries within the Kaira project using the `example_workflow.py` script. This script streamlines common development tasks related to example management. ```bash # Preview examples in a category python scripts/example_workflow.py preview --category modulation # Sync all example galleries python scripts/example_workflow.py sync # Validate example format python scripts/example_workflow.py validate --file examples/modulation/plot_new_example.py ``` -------------------------------- ### Set up Kaira Development Environment Source: https://github.com/ipc-lab/kaira/blob/main/docs/contributing.rst Commands to clone the Kaira repository, navigate into the project directory, install development dependencies using pip, and set up pre-commit hooks for automated code quality checks. ```bash git clone https://github.com/ipc-lab/kaira.git cd kaira pip install -r requirements-dev.txt pre-commit install ``` -------------------------------- ### Jinja2 Template for Example Gallery Layout Source: https://github.com/ipc-lab/kaira/blob/main/docs/_templates/gallery_header_template.html This template defines the main layout for a documentation page, extending `!layout.html`. It includes blocks for displaying page titles, descriptions, example counts, and navigation links. It also features sections for categorized examples, complete with thumbnails, titles, descriptions, and links to individual examples. Download buttons for archives and Binder links are also supported. ```Jinja2 {% extends "!layout.html" %} {% block content %} {{ title }} =========== {% if description %} {{ description }} {% endif %} {% if example_count %} {{ example_count }} examples {% endif %} {% if total_execution_time %} Total runtime: {{ "%.2f"|format(total_execution_time) }}s {% endif %} {% if sections %} {% for section in sections %} [{{ section.title }} ({{ section.example_count }})](#{{ section.id }}) {% endfor %} {% endif %} {% if download_buttons %} {% if zip_download_link %} [Download all examples]({{ zip_download_link }}) {% endif %} {% if binder_link %} [![Launch Binder](https://mybinder.org/badge_logo.svg) ]({{ binder_link }}){% endif %} {% endif %} {{ super() }} {% endblock %} {% block body %} {{ title }} =========== {{ content }} {% for category in gallery_categories %} {{ category.name }} ------------------- {{ category.description }} {% for example in category.examples %} [{% if example.thumbnail %} ![{{ example.title }} thumbnail]({{ example.thumbnail }}) {% else %} {% endif %} ### {{ example.title }} {{ example.description|truncate(100) }} ]({{ example.url }}) {% endfor %} {% endfor %} {% endblock %} ``` -------------------------------- ### Set Up Kaira Development Environment Source: https://github.com/ipc-lab/kaira/blob/main/CONTRIBUTING.md Commands to create and activate a Python virtual environment, then install Kaira's development dependencies using pip. This snippet provides two alternative methods for dependency installation. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -e ".[dev]" # Or alternatively: pip install -e . pip install -r requirements-dev.txt ``` -------------------------------- ### Manage Kaira Benchmarks via CLI Source: https://github.com/ipc-lab/kaira/blob/main/examples/benchmarks/README.txt This snippet showcases the command-line interface (CLI) for the Kaira benchmarking system, located at `scripts/kaira_benchmark.py`. It demonstrates how to list available benchmarks, run a single benchmark with a specific configuration, execute multiple benchmarks in parallel, and run a complete benchmark suite, providing a powerful way to control benchmarking operations. ```bash # List available benchmarks python scripts/kaira_benchmark.py --list # Run a single benchmark python scripts/kaira_benchmark.py --benchmark ber_simulation --config fast # Run multiple benchmarks in parallel python scripts/kaira_benchmark.py --benchmark ber_simulation throughput_test --parallel # Run a comprehensive benchmark suite python scripts/kaira_benchmark.py --suite --output ./my_results ``` -------------------------------- ### Jinja2/Sphinx Layout Extension for Example Pages Source: https://github.com/ipc-lab/kaira/blob/main/docs/_templates/layout.html This Jinja2 template extends the base Sphinx layout (`!layout.html`) to add custom content to the `extrahead`, `sidebarbottom`, and `footer` blocks. It conditionally displays example-specific metadata such as source filename, execution time, and line count. It also generates badges and links for launching examples in Binder or downloading them directly, primarily for pages under `auto_examples/`. ```Jinja2 {% extends "!layout.html" %} {% block extrahead %} {{ super() }} {% if pagename.startswith('auto_examples/') %} {% if title %} {% endif %} {% if meta and meta.description %} {% endif %} {% if meta and meta.image %} {% endif %} {% endif %} {% endblock %} {% block sidebarbottom %} {{ super() }} {% if pagename.startswith('auto_examples/') %} {% if meta and meta.filename %} #### Example Information Source: {{ meta.filename }} {% if meta.exec_time %} Execution time: {{ "%.2f"|format(meta.exec_time) }}s {% endif %} {% if meta.lines %} Lines: {{ meta.lines }} {% endif %} {% endif %} {% if meta and meta.binder_link %} [![Launch in Binder](https://mybinder.org/badge_logo.svg)]({{ meta.binder_link }}) {% endif %} {% if meta and meta.download_link %} [Download this example]({{ pathto(meta.download_link, 1) }}) {% endif %} {% endif %} {% endblock %} {% block footer %} {{ super() }} {% if pagename.startswith('auto_examples/') %} // Enable smooth scrolling for anchor links document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); const targetId = this.getAttribute('href').substring(1); const targetElement = document.getElementById(targetId); if (targetElement) { targetElement.scrollIntoView({ behavior: 'smooth' }); // Update URL without scrolling history.pushState(null, null, '#' + targetId); } }); }); {% endif %} {% endblock %} {% block document %} {% block body %}{{ super() }}{% endblock %} {% endblock %} ``` -------------------------------- ### Jinja2 Template for Project Example Listing Source: https://github.com/ipc-lab/kaira/blob/main/docs/_templates/sphinx_gallery_category_template.html This Jinja2 template defines the structure for a web page that extends a base layout. It dynamically displays a title, main content, and iterates through a list of 'examples'. Each example can include a thumbnail, title, truncated tooltip, and a URL. The template also conditionally renders download buttons for Python source, Jupyter notebooks, and a Binder launch link based on available data. ```Jinja2 {% extends "!layout.html" %} {% block content %} {{ title }} =========== {{ content }} {% for example in examples %} [{% if example.thumbnail %} ![{{ example.title }} thumbnail]({{ example.thumbnail }}) {% else %} {% endif %} ### {{ example.title }} {{ example.tooltip|truncate(100) }} ]({{ example.url }}) {% endfor %} {% if download_buttons %} {% if zip_download_link_py %} [Download all examples (Python source)]({{ zip_download_link_py }}) {% endif %} {% if zip_download_link_jupyter %} [Download all examples (Jupyter notebooks)]({{ zip_download_link_jupyter }}) {% endif %} {% if binder_link %} [![Launch Binder](https://mybinder.org/badge_logo.svg) ]({{ binder_link }}){% endif %} {% endif %} {{ super() }} {% endblock content %} ``` -------------------------------- ### Python Example Docstring Format Source: https://github.com/ipc-lab/kaira/blob/main/CONTRIBUTING.md Required docstring format for Kaira examples, including a clear and descriptive title, followed by a comprehensive explanation of the example's purpose, concepts, and expected outcomes. This format is crucial for the automated example gallery generation. ```python """ ========================================== Clear and Descriptive Title ========================================== Comprehensive description explaining what the example demonstrates, key concepts covered, and expected outcomes. Additional paragraphs can provide more detail about implementation specifics, theoretical background, or usage notes. """ ``` -------------------------------- ### Clone Kaira Repository Source: https://github.com/ipc-lab/kaira/blob/main/CONTRIBUTING.md Instructions to clone your forked Kaira repository from GitHub and navigate into its directory, initiating the local development setup. ```bash git clone https://github.com/YOUR-USERNAME/kaira.git cd kaira ``` -------------------------------- ### Run Kaira BER Simulation with StandardRunner Source: https://github.com/ipc-lab/kaira/blob/main/examples/benchmarks/README.txt This snippet demonstrates the fundamental steps to set up and execute a Bit Error Rate (BER) simulation using the Kaira benchmarking system. It shows how to define a benchmark, configure its parameters like SNR range and number of bits, run it with the `StandardRunner`, and automatically save the results to a structured directory. ```python from kaira.benchmarks import get_benchmark, StandardRunner, BenchmarkConfig # Create a benchmark ber_benchmark = get_benchmark("ber_simulation")(modulation="bpsk") # Configure the benchmark config = BenchmarkConfig( snr_range=list(range(-5, 11)), num_bits=100000 ) # Run the benchmark with automatic result organization runner = StandardRunner() result = runner.run_benchmark(ber_benchmark, **config.to_dict()) # Results are automatically organized in the structured directory system saved_files = runner.save_all_results(experiment_name="my_experiment") print(f"Results saved to: {saved_files}") ``` -------------------------------- ### Integrate Kaira Benchmarks with Custom Results Manager Source: https://github.com/ipc-lab/kaira/blob/main/examples/benchmarks/README.txt This example illustrates how to leverage Kaira's new results management system by creating a custom `BenchmarkResultsManager`. It demonstrates how to associate this manager with a `StandardRunner` to ensure all benchmark results are automatically organized into a specified directory structure, simplifying result retrieval and analysis. ```python from kaira.benchmarks import StandardRunner from kaira.benchmarks.results_manager import BenchmarkResultsManager # Create a custom results manager results_manager = BenchmarkResultsManager("my_results") # Use it with a runner runner = StandardRunner(results_manager=results_manager) # Run benchmarks - results are automatically organized result = runner.run_benchmark(ber_benchmark, **config.to_dict()) # Results are saved in organized directory structure: # my_results/benchmarks/experiment_name/benchmark_files.json ``` -------------------------------- ### Example Kaira BCH Code Decoding Source: https://github.com/ipc-lab/kaira/blob/main/docs/api_reference.rst Demonstrates how to initialize a BCH encoder and a Berlekamp-Massey decoder from the Kaira library. This snippet provides a practical example of setting up and performing a basic decoding operation on a received tensor using a specific FEC scheme. ```python 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) ``` -------------------------------- ### Run Kaira Tests with Pytest Source: https://github.com/ipc-lab/kaira/blob/main/docs/contributing.rst Examples of how to execute Kaira's test suite using pytest, demonstrating options to run all tests, specific test types (unit or integration), or exclude certain tests (e.g., slow ones) using markers. ```bash pytest tests/ pytest tests/ -m unit pytest tests/ -m integration pytest tests/ -m "not slow" ``` -------------------------------- ### Makefile Target: deploy Source: https://github.com/ipc-lab/kaira/blob/main/docs/makefile.rst The `deploy` target handles the process of packaging and deploying the Kaira project to PyPI. This makes the package available for installation via pip, facilitating distribution. ```make deploy: ## Deploy package to PyPI ./scripts/deploy.sh ``` -------------------------------- ### Kaira Benchmark Types and Configuration Options Source: https://github.com/ipc-lab/kaira/blob/main/examples/benchmarks/README.txt This section documents the available benchmark types within the Kaira system and the configurable options for the `BenchmarkConfig` class. It lists various simulation and testing benchmarks like BER, channel capacity, throughput, and latency, along with parameters such as SNR range, number of bits, device selection, and result saving preferences. ```APIDOC Available Benchmarks: - ber_simulation: Bit Error Rate simulation for various modulation schemes - channel_capacity: Channel capacity calculations - throughput_test: System throughput evaluation - latency_test: System latency measurement - model_complexity: Model computational complexity analysis BenchmarkConfig Class Options: - snr_range: Range of SNR values to test - num_bits: Number of bits for simulation - num_trials: Number of trial runs - device: Computation device ("auto", "cpu", "cuda") - verbose: Enable verbose output - save_results: Save benchmark results ``` -------------------------------- ### Combine Multiple Constraints for Signal Processing Source: https://github.com/ipc-lab/kaira/blob/main/docs/api_reference.rst This example demonstrates how to create individual constraints (TotalPowerConstraint, PAPRConstraint) and combine them into a single operation using `combine_constraints`. The combined constraint can then be applied to an input signal to ensure it meets multiple practical requirements simultaneously. ```python 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) ``` -------------------------------- ### Smooth Scrolling for Anchor Links Source: https://github.com/ipc-lab/kaira/blob/main/docs/_templates/layout.html This JavaScript snippet, embedded within the Jinja2 template's footer, enables smooth scrolling for all internal anchor links on pages related to auto-generated examples. It prevents the default jump behavior of anchor links, smoothly scrolls the target element into view, and updates the URL hash without causing a page reload or abrupt jump. ```JavaScript // Enable smooth scrolling for anchor links document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); const targetId = this.getAttribute('href').substring(1); const targetElement = document.getElementById(targetId); if (targetElement) { targetElement.scrollIntoView({ behavior: 'smooth' }); // Update URL without scrolling history.pushState(null, null, '#' + targetId); } }); }); ``` -------------------------------- ### Sphinx Autodoc Template for Class API Documentation Source: https://github.com/ipc-lab/kaira/blob/main/docs/_templates/autosummary/class.rst This reStructuredText and Jinja2 template defines the structure for generating API documentation for a Python class using Sphinx's `autoclass` and `autosummary` directives. It dynamically includes class members, methods, and attributes based on Jinja2 variables like `fullname`, `module`, `objname`, `methods`, and `attributes`. The template also includes a conditional block to link to example usage files for specific channel classes. ```reStructuredText {{ fullname | escape | underline}} .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} :members: :show-inheritance: {% block methods %} {% if methods %} .. rubric:: {{ _('Methods') }} .. autosummary:: :toctree: {% for item in methods %} ~{{ fullname }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% block attributes %} {% if attributes %} .. rubric:: {{ _('Attributes') }} .. autosummary:: :toctree: {% for item in attributes %} ~{{ fullname }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% if objname in ["AWGNChannel", "BaseChannel", "BinaryErasureChannel", "BinarySymmetricChannel", "BinaryZChannel", "ChannelRegistry", "FlatFadingChannel", "GaussianChannel", "IdealChannel", "IdentityChannel", "LambdaChannel", "LaplacianChannel", "NonlinearChannel", "PerfectChannel", "PhaseNoiseChannel", "PoissonChannel"] %} .. rubric:: {{ _('Examples using') }} ``{{ objname }}`` .. include:: ../gen_modules/backreferences/{{module}}.{{objname}}.examples :optional: {% endif %} ``` -------------------------------- ### Sphinx Autodoc Class Template for Python API Docs Source: https://github.com/ipc-lab/kaira/blob/main/docs/_templates/class.rst This Jinja2 template, combined with Sphinx and reStructuredText, defines the layout for generating API documentation pages for Python classes. It dynamically includes elements such as inheritance diagrams, lists of methods and attributes, and custom examples, based on the class's structure and provided documentation. It serves as a blueprint for creating standardized API reference pages. ```APIDOC {{ fullname | escape | underline}} .. currentmodule:: {{ module }} .. inheritance-diagram:: {{ objname }} :parts: 1 :private-bases: :caption: Inheritance diagram for {{ objname }} :top-classes: abc.ABC torch.nn.Module .. autoclass:: {{ objname }} :members: :show-inheritance: :inherited-members: :special-members: __call__, __add__, __mul__ :exclude-members: forward {% block methods %} {% if methods %} .. rubric:: {{ _('Methods') }} .. autosummary:: :nosignatures: {% for item in methods %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% block attributes %} {% if attributes %} .. rubric:: {{ _('Attributes') }} .. autosummary:: {% for item in attributes %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% if examples %} .. rubric:: {{ _('Examples') }} {{ examples }} {% endif %} {% block backreferences %} .. include:: ../gen_modules/backreferences/{{module}}.{{objname}}.examples {% endblock %} ``` -------------------------------- ### Uninstall Kaira Package Source: https://github.com/ipc-lab/kaira/blob/main/docs/installation.rst This command removes the Kaira Python package from your current environment using pip, the Python package installer. It's used when you need to completely remove Kaira. ```bash pip uninstall pykaira ``` -------------------------------- ### Loading and Analyzing Kaira Benchmark Results Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst Demonstrates how to load saved benchmark results from specified paths and iterate through them for analysis. It also shows how to create comparative reports from a selection of results. ```python # Load results using the results manager results_manager = BenchmarkResultsManager() result_paths = results_manager.list_results(category="benchmarks") for path in result_paths: result = results_manager.load_benchmark_result(path) print(f"Result: {result.name}, Time: {result.execution_time:.2f}s") # Create comparison reports comparison_path = results_manager.create_comparison_report( result_paths[:3], "algorithm_comparison" ) ``` -------------------------------- ### Run a Kaira Benchmark with Automatic Result Organization Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst This snippet demonstrates the basic workflow for running a benchmark using Kaira's `StandardRunner` and `BenchmarkConfig`. It shows how to create a benchmark, configure its parameters, execute it, and automatically save and access the results in an organized directory structure. ```Python from kaira.benchmarks import get_benchmark, StandardRunner, BenchmarkConfig # Create a benchmark ber_benchmark = get_benchmark("ber_simulation")(modulation="bpsk") # Configure the benchmark config = BenchmarkConfig( snr_range=list(range(-5, 11)), num_bits=100000 ) # Run the benchmark with automatic result organization runner = StandardRunner() result = runner.run_benchmark(ber_benchmark, **config.to_dict()) # Results are automatically saved to organized directory structure print(f"BER results: {result.metrics['ber_simulated']}") # Access saved results using the results manager saved_files = runner.save_all_results(experiment_name="ber_evaluation") print(f"Results saved to: {saved_files}") ``` -------------------------------- ### Makefile Target: help Source: https://github.com/ipc-lab/kaira/blob/main/docs/makefile.rst The `help` target scans the Makefile for lines with comments (using the `##` marker) and displays all available targets with their descriptions, providing a quick reference for users. ```make help: ## Show help @grep -E '^[.a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' ``` -------------------------------- ### Build HTML Documentation with Sphinx Source: https://github.com/ipc-lab/kaira/blob/main/docs/build_documentation.rst These commands execute the Sphinx build process to generate HTML documentation from the reStructuredText source files. The appropriate command should be used based on the operating system to compile the documentation into a web-viewable format. ```bash make html ``` ```bat make.bat html ``` -------------------------------- ### Run a Kaira Benchmark Suite Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst This snippet illustrates how to define and execute a `BenchmarkSuite` in Kaira, allowing users to group multiple benchmarks and run them together as a single suite for comprehensive evaluation. ```Python suite = BenchmarkSuite("My Suite") suite.add_benchmark(benchmark1) suite.add_benchmark(benchmark2) results = runner.run_suite(suite, **config.to_dict()) ``` -------------------------------- ### Perform a Kaira Benchmark Comparison Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst This snippet shows how to use the `ComparisonRunner` in Kaira to compare the performance of multiple benchmarks, providing a descriptive title for the comparison and passing common configuration parameters. ```Python runner = ComparisonRunner() results = runner.run_comparison( [benchmark1, benchmark2], "Algorithm Comparison", **config.to_dict() ) ``` -------------------------------- ### Build Documentation and Check Code Style Source: https://github.com/ipc-lab/kaira/blob/main/docs/contributing.rst Commands to build the project's documentation and ensure the codebase adheres to PEP8 style guidelines, crucial steps before committing changes or submitting a pull request. ```bash bash build_docs.sh bash lint.sh ``` -------------------------------- ### Kaira Common Development Checks and Release Preparation Source: https://github.com/ipc-lab/kaira/blob/main/docs/makefile.rst A set of `make` commands for maintaining code quality, running tests, and preparing for releases in the Kaira project. Includes commands for formatting, linting, comprehensive testing, and deployment steps. ```bash # Format code and run quick tests make format && make test # Checking code quality before committing make format && make lint # Comprehensive check before submitting a pull request make clean && make format && make lint && make test-full && make coverage # Preparing a new release make clean && make test-full && make coverage && make build-docs && make build-readme && make deploy ``` -------------------------------- ### Configuring Kaira Benchmarks for Reproducibility and Analysis Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst Demonstrates how to configure `BenchmarkConfig` parameters to ensure reproducible results (setting random seeds), save raw data for detailed analysis, calculate confidence intervals for statistical rigor, and monitor memory usage during large experiments. ```python config = BenchmarkConfig(seed=42) config = BenchmarkConfig(save_raw_data=True) config = BenchmarkConfig( calculate_confidence_intervals=True, confidence_level=0.95 ) config = BenchmarkConfig(memory_limit_mb=8192) ``` -------------------------------- ### Kaira Benchmarks API Reference Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst API documentation for the `kaira.benchmarks` module, detailing classes and their methods used for managing benchmark execution and results. ```APIDOC kaira.benchmarks.BenchmarkResultsManager: __init__(self, base_dir: str = 'results') base_dir: The base directory where results will be stored. save_benchmark_result(self, result: object, category: str, experiment_name: str) -> str result: The benchmark result object to save. category: A string categorizing the result (e.g., 'benchmarks'). experiment_name: The name of the experiment. Returns: The path where the result was saved. save_suite_results(self, results_list: list, suite_name: str, experiment_name: str) -> list results_list: A list of benchmark result objects from a suite. suite_name: The name of the benchmark suite. experiment_name: The name of the experiment. Returns: A list of paths where the suite results were saved. list_results(self, category: str = None, experiment_name: str = None) -> list category: Optional. Filter results by category. experiment_name: Optional. Filter results by experiment name. Returns: A list of paths to available results. load_benchmark_result(self, result_path: str) -> object result_path: The file path to the benchmark result. Returns: The loaded benchmark result object. create_comparison_report(self, result_paths: list, report_name: str) -> str result_paths: A list of paths to benchmark results to compare. report_name: The name for the comparison report. Returns: The path to the generated comparison report. archive_old_results(self, days_old: int) days_old: Results older than this many days will be archived. cleanup_empty_directories(self) kaira.benchmarks.StandardRunner: __init__(self, results_manager: BenchmarkResultsManager) results_manager: An instance of BenchmarkResultsManager for handling results. run_benchmark(self, benchmark: object, experiment_name: str) -> object benchmark: The benchmark object to run. experiment_name: The name of the experiment. Returns: The result object of the benchmark run. run_suite(self, suite: object, experiment_name: str) -> list suite: The benchmark suite object to run. experiment_name: The name of the experiment. Returns: A list of result objects from the suite run. kaira.benchmarks.BenchmarkConfig: __init__(self, seed: int = None, save_raw_data: bool = False, calculate_confidence_intervals: bool = False, confidence_level: float = None, memory_limit_mb: int = None) seed: An integer seed for reproducibility. save_raw_data: If True, raw data from the benchmark will be saved. calculate_confidence_intervals: If True, confidence intervals will be calculated. confidence_level: The confidence level for interval calculation (e.g., 0.95). memory_limit_mb: Maximum memory usage in megabytes for the benchmark process. ``` -------------------------------- ### Build README.rst from Template Source: https://github.com/ipc-lab/kaira/blob/main/docs/makefile.rst Executes the Python script to generate the `README.rst` file from its template, typically used during release preparation. ```bash python ./scripts/build_readme.py ``` -------------------------------- ### Execute a Kaira Benchmark Sequentially Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst This snippet shows how to run a single benchmark sequentially using the `StandardRunner` in Kaira, passing the benchmark object and configuration parameters for execution. ```Python runner = StandardRunner(verbose=True) result = runner.run_benchmark(benchmark, **config.to_dict()) ``` -------------------------------- ### Automated Benchmark Results Management with Kaira Source: https://github.com/ipc-lab/kaira/blob/main/docs/benchmarks.rst Demonstrates how to initialize `BenchmarkResultsManager` and `StandardRunner` to automatically save and organize benchmark results within a specified directory. Results are automatically structured by benchmark name, timestamp, and ID. ```python from kaira.benchmarks import StandardRunner, BenchmarkResultsManager # Create a results manager (uses 'results/' directory by default) results_manager = BenchmarkResultsManager("my_results") # Create a runner with the results manager runner = StandardRunner(results_manager=results_manager) # Run benchmarks - results are automatically saved and organized result = runner.run_benchmark(benchmark, experiment_name="my_experiment") # Results are automatically saved to: # my_results/benchmarks/my_experiment/benchmark_name_timestamp_id.json ``` -------------------------------- ### Navigate to Documentation Directory Source: https://github.com/ipc-lab/kaira/blob/main/docs/build_documentation.rst This command changes the current working directory to the 'docs' folder, which typically contains the source files for the Sphinx documentation. It is a necessary first step before initiating the documentation build process. ```bash cd docs ``` -------------------------------- ### BibTeX Citation for Kaira Source: https://github.com/ipc-lab/kaira/blob/main/README.md Standard BibTeX entry for citing the Kaira project in academic papers and research. This entry includes the software title, authors, publication year, URL, and version number. ```bibtex @software{kaira2025, title = {Kaira: A {PyTorch}-based toolkit for simulating communication systems}, author = {{Kaira Contributors}}, year = {2025}, url = {https://github.com/ipc-lab/kaira}, version = {0.1.0} } ```