API Reference

This section provides comprehensive documentation for all classes, methods, and functions in the QKD Simulation Platform.

Core Classes

Network Management

class simulation.Network.Network

Main network management class that handles nodes, connections, and end-to-end key establishment.

__init__()

Initialize an empty network.

add_node(node_id, avg_photon_number=0.2, detector_efficiency=0.9, dark_count_rate=1e-7, cow_monitor_pulse_ratio=0.1, cow_detection_threshold_photons=0, cow_extinction_ratio_db=20.0)

Add a new node to the network.

Parameters:
  • node_id (str) – Unique identifier for the node

  • avg_photon_number (float) – Average photon number per pulse (0 < μ < 1)

  • detector_efficiency (float) – Quantum efficiency of the detector (0-1)

  • dark_count_rate (float) – Dark count rate per nanosecond

  • cow_monitor_pulse_ratio (float) – COW monitoring pulse ratio (0-1)

  • cow_detection_threshold_photons (float) – COW detection threshold in photons

  • cow_extinction_ratio_db (float) – COW extinction ratio in dB

Returns:

The created Node instance

Return type:

simulation.Network.Node

connect_nodes(node1_id, node2_id, distance_km, attenuation_db_per_km=0.2)

Connect two nodes with an optical channel.

Parameters:
  • node1_id (str) – ID of the first node

  • node2_id (str) – ID of the second node

  • distance_km (float) – Distance between nodes in kilometers

  • attenuation_db_per_km (float) – Fiber attenuation in dB per kilometer

establish_end_to_end_raw_key(sender_id, receiver_id, path_nodes, num_pulses, pulse_repetition_rate_ns)

Establish end-to-end raw sifted key through trusted relay nodes (DPS-QKD).

Parameters:
  • sender_id (str) – ID of the sender node

  • receiver_id (str) – ID of the receiver node

  • path_nodes (list) – List of node IDs in the path from sender to receiver

  • num_pulses (int) – Number of pulses to generate per link

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

Returns:

Final end-to-end raw sifted key or None if failed

Return type:

list or None

establish_end_to_end_raw_key_cow(sender_id, receiver_id, path_nodes, num_pulses, pulse_repetition_rate_ns, monitor_pulse_ratio=0.1, detection_threshold_photons=0)

Establish end-to-end raw sifted key through trusted relay nodes (COW-QKD).

Parameters:
  • sender_id (str) – ID of the sender node

  • receiver_id (str) – ID of the receiver node

  • path_nodes (list) – List of node IDs in the path from sender to receiver

  • num_pulses (int) – Number of pulses to generate per link

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

  • monitor_pulse_ratio (float) – COW monitoring pulse ratio

  • detection_threshold_photons (float) – COW detection threshold

Returns:

Final end-to-end raw sifted key or None if failed

Return type:

list or None

establish_end_to_end_raw_key_bb84(sender_id, receiver_id, path_nodes, num_pulses, pulse_repetition_rate_ns)

Establish end-to-end raw sifted key through trusted relay nodes (BB84-QKD).

Parameters:
  • sender_id (str) – ID of the sender node

  • receiver_id (str) – ID of the receiver node

  • path_nodes (list) – List of node IDs in the path from sender to receiver

  • num_pulses (int) – Number of pulses to generate per link

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

Returns:

Final end-to-end raw sifted key or None if failed

Return type:

list or None

class simulation.Network.Node

Represents a network node that can act as sender, receiver, or trusted relay.

__init__(node_id, avg_photon_number=0.2, detector_efficiency=0.9, dark_count_rate=1e-7, cow_monitor_pulse_ratio=0.1, cow_detection_threshold_photons=0, cow_extinction_ratio_db=20.0)

Initialize a node with protocol-specific components.

Parameters:
  • node_id (str) – Unique identifier for the node

  • avg_photon_number (float) – Average photon number per pulse

  • detector_efficiency (float) – Quantum efficiency of the detector

  • dark_count_rate (float) – Dark count rate per nanosecond

  • cow_monitor_pulse_ratio (float) – COW monitoring pulse ratio

  • cow_detection_threshold_photons (float) – COW detection threshold

  • cow_extinction_ratio_db (float) – COW extinction ratio in dB

Add an optical channel link to a neighbor node.

Parameters:
  • neighbor_node_id (str) – ID of the neighbor node

  • channel_instance (OpticalChannel) – Optical channel instance

generate_and_share_key(target_node, num_pulses, pulse_repetition_rate_ns, phase_flip_prob=0.0)

Generate and share key using DPS-QKD protocol.

Parameters:
  • target_node (Node) – Target node for key generation

  • num_pulses (int) – Number of pulses to generate

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

  • phase_flip_prob (float) – Probability of phase flip noise

Returns:

Tuple of (alice_key, bob_key)

Return type:

tuple

generate_and_share_key_cow(target_node, num_pulses, pulse_repetition_rate_ns, monitor_pulse_ratio=0.1, detection_threshold_photons=0, phase_flip_prob=0.0, bit_flip_error_prob=0.0)

Generate and share key using COW-QKD protocol.

Parameters:
  • target_node (Node) – Target node for key generation

  • num_pulses (int) – Number of pulses to generate

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

  • monitor_pulse_ratio (float) – COW monitoring pulse ratio

  • detection_threshold_photons (float) – COW detection threshold

  • phase_flip_prob (float) – Probability of phase flip noise

  • bit_flip_error_prob (float) – Probability of bit flip error

Returns:

Tuple of (alice_key, bob_key)

Return type:

tuple

generate_and_share_key_bb84(target_node, num_pulses, pulse_repetition_rate_ns, phase_flip_prob=0.0)

Generate and share key using BB84-QKD protocol.

Parameters:
  • target_node (Node) – Target node for key generation

  • num_pulses (int) – Number of pulses to generate

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

  • phase_flip_prob (float) – Probability of phase flip noise

Returns:

Tuple of (alice_key, bob_key)

Return type:

tuple

get_raw_sifted_key_with_neighbor(neighbor_id)

Get the raw sifted key shared with a specific neighbor.

Parameters:

neighbor_id (str) – ID of the neighbor node

Returns:

Raw sifted key or None if not found

Return type:

list or None

relay_key_classically(sender_node_id, receiver_node_id, key_to_relay)

Relay a key classically between two nodes (for trusted relay networks).

Parameters:
  • sender_node_id (str) – ID of the sender node

  • receiver_node_id (str) – ID of the receiver node

  • key_to_relay (list) – Key to relay

Returns:

Relayed key

Return type:

list

Hardware Components

class simulation.Hardware.LightSource

Models a weak coherent pulse (WCP) light source with Poissonian photon statistics.

__init__(average_photon_number=0.2)

Initialize the light source.

Parameters:

average_photon_number (float) – Average photon number per pulse (0 < μ < 1)

Raises:

ValueError – If average_photon_number is not between 0 and 1

generate_single_pulse_photon_count(mu=None)

Generate photon count for a single pulse using Poissonian statistics.

Parameters:

mu (float) – Average photon number (uses instance value if None)

Returns:

Number of photons in the pulse

Return type:

int

get_initial_phase()

Get the initial phase of the light source.

Returns:

Initial phase in radians

Return type:

float

class simulation.Hardware.PhaseModulator

Models a phase modulator for phase encoding in QKD protocols.

modulate_phase(current_phase, desired_phase_shift)

Modulate the phase of an optical signal.

Parameters:
  • current_phase (float) – Current phase in radians

  • desired_phase_shift (float) – Desired phase shift in radians

Returns:

New phase in radians (modulo 2π)

Return type:

float

class simulation.Hardware.IntensityModulator

Models an intensity modulator with finite extinction ratio.

__init__(extinction_ratio_db=20.0)

Initialize the intensity modulator.

Parameters:

extinction_ratio_db (float) – Extinction ratio in dB

Raises:

ValueError – If extinction ratio is not positive

modulate(base_mu, state)

Modulate the intensity of an optical signal.

Parameters:
  • base_mu (float) – Base average photon number

  • state (str) – Modulation state (‘on’ or ‘off’)

Returns:

Modulated average photon number

Return type:

float

Raises:

ValueError – If state is not ‘on’ or ‘off’

class simulation.Hardware.OpticalChannel

Models an optical fiber channel with distance-dependent attenuation.

__init__(distance_km, attenuation_db_per_km=0.2)

Initialize the optical channel.

Parameters:
  • distance_km (float) – Distance in kilometers

  • attenuation_db_per_km (float) – Attenuation in dB per kilometer

transmit_pulse(photon_count)

Transmit a pulse through the channel.

Parameters:

photon_count (int) – Number of photons to transmit

Returns:

Number of photons received after transmission

Return type:

int

class simulation.Hardware.MachZehnderInterferometer

Models a Mach-Zehnder interferometer for phase difference measurement.

__init__(ideal_split_ratio=0.5)

Initialize the Mach-Zehnder interferometer.

Parameters:

ideal_split_ratio (float) – Ideal beam splitter ratio (default 0.5)

interfere_pulses(phase_n_minus_1, phase_n)

Calculate interference probabilities for two consecutive pulses.

Parameters:
  • phase_n_minus_1 (float) – Phase of the previous pulse

  • phase_n (float) – Phase of the current pulse

Returns:

Tuple of (prob_dm1, prob_dm2) detection probabilities

Return type:

tuple

class simulation.Hardware.SinglePhotonDetector

Models a single-photon detector with quantum efficiency and dark counts.

__init__(quantum_efficiency=0.9, dark_count_rate_per_ns=1e-7, time_window_ns=1)

Initialize the single-photon detector.

Parameters:
  • quantum_efficiency (float) – Quantum efficiency (0-1)

  • dark_count_rate_per_ns (float) – Dark count rate per nanosecond

  • time_window_ns (float) – Detection time window in nanoseconds

detect(incident_photons)

Simulate photon detection.

Parameters:

incident_photons (int) – Number of incident photons

Returns:

True if a click occurs, False otherwise

Return type:

bool

class simulation.Hardware.SMF

Models a single-mode fiber with configurable parameters.

__init__(length_km=20.0, attenuation_db_per_km=0.2, fiber_type='single_mode_fiber')

Initialize the fiber.

Parameters:
  • length_km (float) – Fiber length in kilometers

  • attenuation_db_per_km (float) – Attenuation in dB per kilometer

  • fiber_type (str) – Type of fiber

total_attenuation_db()

Calculate total attenuation in dB.

Returns:

Total attenuation in dB

Return type:

float

transmission_probability()

Calculate photon transmission probability.

Returns:

Transmission probability (0-1)

Return type:

float

Protocol Implementations

DPS-QKD Sender

class simulation.Sender.SenderDPS

Implements the sender side of DPS-QKD protocol.

__init__(avg_photon_number=0.2)

Initialize the DPS sender.

Parameters:

avg_photon_number (float) – Average photon number per pulse

prepare_and_send_pulse(time_slot)

Prepare and send a single pulse with phase encoding.

Parameters:

time_slot (float) – Time slot for the pulse

Returns:

Tuple of (modulated_phase, photon_count)

Return type:

tuple

get_pulse_info(time_slot)

Get information about a sent pulse.

Parameters:

time_slot (float) – Time slot of the pulse

Returns:

Pulse information dictionary or None

Return type:

dict or None

COW-QKD Sender

class simulation.Sender.SenderCOW

Implements the sender side of COW-QKD protocol.

__init__(avg_photon_number=0.2, monitor_pulse_ratio=0.1, extinction_ratio_db=20.0)

Initialize the COW sender.

Parameters:
  • avg_photon_number (float) – Average photon number per pulse

  • monitor_pulse_ratio (float) – Ratio of monitoring pulses

  • extinction_ratio_db (float) – Extinction ratio in dB

Raises:

ValueError – If avg_photon_number is not between 0 and 1

prepare_pulse_train(num_total_pulses)

Prepare a complete pulse train with data and monitoring pulses.

Parameters:

num_total_pulses (int) – Total number of pulses to generate

Returns:

List of pulse information dictionaries

Return type:

list

get_sent_pulse_info(time_slot)

Get information about a sent pulse.

Parameters:

time_slot (float) – Time slot of the pulse

Returns:

Pulse information dictionary or None

Return type:

dict or None

get_intended_key_bits()

Get the intended key bits for data pulses.

Returns:

List of intended key bits

Return type:

list

BB84-QKD Sender

class simulation.Sender.SenderBB84

Implements the sender side of BB84-QKD protocol.

__init__(avg_photon_number=0.2)

Initialize the BB84 sender.

Parameters:

avg_photon_number (float) – Average photon number per pulse

Raises:

ValueError – If avg_photon_number is not between 0 and 1

prepare_and_send_pulse(time_slot)

Prepare and send a single pulse with basis and bit encoding.

Parameters:

time_slot (float) – Time slot for the pulse

Returns:

Tuple of (encoded_state, photon_count, chosen_bit, chosen_basis)

Return type:

tuple

get_pulse_info(time_slot)

Get information about a sent pulse.

Parameters:

time_slot (float) – Time slot of the pulse

Returns:

Pulse information dictionary or None

Return type:

dict or None

get_raw_key_bits()

Get the raw key bits.

Returns:

List of raw key bits

Return type:

list

get_chosen_bases()

Get the chosen measurement bases.

Returns:

List of chosen bases

Return type:

list

DPS-QKD Receiver

class simulation.Receiver.ReceiverDPS

Implements the receiver side of DPS-QKD protocol.

__init__(detector_efficiency=0.9, dark_count_rate=1e-7)

Initialize the DPS receiver.

Parameters:
  • detector_efficiency (float) – Quantum efficiency of detectors

  • dark_count_rate (float) – Dark count rate per nanosecond

receive_and_measure(time_slot, current_pulse_photons, current_pulse_phase, previous_pulse_photons, previous_pulse_phase)

Receive and measure a pulse using Mach-Zehnder interferometer.

Parameters:
  • time_slot (float) – Time slot of the pulse

  • current_pulse_photons (int) – Photons in current pulse

  • current_pulse_phase (float) – Phase of current pulse

  • previous_pulse_photons (int) – Photons in previous pulse

  • previous_pulse_phase (float) – Phase of previous pulse

Returns:

Tuple of (click_dm1, click_dm2, measured_phase_diff, bob_bit)

Return type:

tuple

COW-QKD Receiver

class simulation.Receiver.ReceiverCOW

Implements the receiver side of COW-QKD protocol.

__init__(detector_efficiency=0.9, dark_count_rate=1e-7, detection_threshold_photons=0)

Initialize the COW receiver.

Parameters:
  • detector_efficiency (float) – Quantum efficiency of detector

  • dark_count_rate (float) – Dark count rate per nanosecond

  • detection_threshold_photons (float) – Detection threshold in photons

measure_pulse(time_slot, incident_photons, pulse_type)

Measure a received pulse.

Parameters:
  • time_slot (float) – Time slot of the pulse

  • incident_photons (int) – Number of incident photons

  • pulse_type (str) – Type of pulse (‘data_first’, ‘data_second’, ‘monitor_first’, ‘monitor_second’)

Returns:

Tuple of (click, bob_inferred_bit, is_monitoring_click)

Return type:

tuple

get_received_pulse_info(time_slot)

Get information about a received pulse.

Parameters:

time_slot (float) – Time slot of the pulse

Returns:

Pulse information dictionary or None

Return type:

dict or None

get_all_received_info()

Get all received pulse information.

Returns:

List of all received pulse information

Return type:

list

BB84-QKD Receiver

class simulation.Receiver.ReceiverBB84

Implements the receiver side of BB84-QKD protocol.

__init__(detector_efficiency=0.9, dark_count_rate=1e-7)

Initialize the BB84 receiver.

Parameters:
  • detector_efficiency (float) – Quantum efficiency of detector

  • dark_count_rate (float) – Dark count rate per nanosecond

receive_and_measure(time_slot, incident_photons, encoded_state)

Receive and measure a pulse in a randomly chosen basis.

Parameters:
  • time_slot (float) – Time slot of the pulse

  • incident_photons (int) – Number of incident photons

  • encoded_state (str) – Encoded quantum state

Returns:

Tuple of (measured_bit, chosen_basis, click_occurred)

Return type:

tuple

get_measurement_info(time_slot)

Get information about a measurement.

Parameters:

time_slot (float) – Time slot of the measurement

Returns:

Measurement information dictionary or None

Return type:

dict or None

get_raw_measurements()

Get all raw measurement results.

Returns:

List of raw measurements

Return type:

list

get_chosen_bases()

Get all chosen measurement bases.

Returns:

List of chosen bases

Return type:

list

Analysis Functions

main.calculate_qber(alice_sifted_key, bob_sifted_key, dr=0.10, seed=None)

Calculate the Quantum Bit Error Rate (QBER) using a random sample.

Parameters:
  • alice_sifted_key (list) – Alice’s sifted key

  • bob_sifted_key (list) – Bob’s sifted key

  • dr (float) – Disclose rate for QBER estimation (0-1)

  • seed (int) – Random seed for reproducible results

Returns:

Tuple of (qber, num_errors)

Return type:

tuple

Raises:

ValueError – If keys have different lengths

main.postprocessing(raw_key_length, qber, dr=0.10, error_correction_efficiency=1.2, privacy_amplification_ratio=0.5)

Simulate QKD post-processing steps.

Parameters:
  • raw_key_length (int) – Length of raw sifted key

  • qber (float) – Quantum Bit Error Rate

  • dr (float) – Disclose rate for parameter estimation

  • error_correction_efficiency (float) – Error correction efficiency factor

  • privacy_amplification_ratio (float) – Privacy amplification compression ratio

Returns:

Tuple of (final_key_length, postprocessing_breakdown)

Return type:

tuple

Simulation Functions

main.run_point_to_point_simulation(num_pulses_per_link=10000, distance_km=20, mu=0.2, detector_efficiency=0.9, dark_count_rate_per_ns=1e-7, pulse_repetition_rate_ns=1)

Run a point-to-point QKD simulation.

Parameters:
  • num_pulses_per_link (int) – Number of pulses per link

  • distance_km (float) – Distance between nodes in kilometers

  • mu (float) – Average photon number per pulse

  • detector_efficiency (float) – Quantum efficiency of detector

  • dark_count_rate_per_ns (float) – Dark count rate per nanosecond

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

Returns:

Tuple of (final_key_length, qber)

Return type:

tuple

main.run_multi_node_trusted_relay_simulation(num_pulses_per_link=10000, link_distance_km=10, num_relays=1, mu=0.2, detector_efficiency=0.9, dark_count_rate_per_ns=1e-7, pulse_repetition_rate_ns=1)

Run a multi-node trusted relay QKD simulation.

Parameters:
  • num_pulses_per_link (int) – Number of pulses per link

  • link_distance_km (float) – Distance per link in kilometers

  • num_relays (int) – Number of relay nodes

  • mu (float) – Average photon number per pulse

  • detector_efficiency (float) – Quantum efficiency of detector

  • dark_count_rate_per_ns (float) – Dark count rate per nanosecond

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

Returns:

Final end-to-end raw sifted key

Return type:

list or None

main.run_point_to_point_cow_simulation(num_pulses_per_link=10000, distance_km=20, mu=0.1, detector_efficiency=0.9, dark_count_rate_per_ns=1e-7, pulse_repetition_rate_ns=1, cow_monitor_pulse_ratio=0.1, cow_detection_threshold_photons=0, cow_extinction_ratio_db=20.0, bit_flip_error_prob=0.05)

Run a point-to-point COW-QKD simulation.

Parameters:
  • num_pulses_per_link (int) – Number of pulses per link

  • distance_km (float) – Distance between nodes in kilometers

  • mu (float) – Average photon number per pulse

  • detector_efficiency (float) – Quantum efficiency of detector

  • dark_count_rate_per_ns (float) – Dark count rate per nanosecond

  • pulse_repetition_rate_ns (float) – Pulse repetition rate in nanoseconds

  • cow_monitor_pulse_ratio (float) – COW monitoring pulse ratio

  • cow_detection_threshold_photons (float) – COW detection threshold

  • cow_extinction_ratio_db (float) – COW extinction ratio in dB

  • bit_flip_error_prob (float) – Bit flip error probability

Returns:

Tuple of (final_key_length, qber)

Return type:

tuple

REST API

The platform provides a REST API for programmatic access to simulations.

Base URL

  • Development: http://127.0.0.1:8000

  • Production: Configure as needed

Endpoints

Data Models

class api.NodeModel

Pydantic model for node configuration.

id

Node identifier (int)

detector_efficiency

Quantum efficiency of detector (float, 0-1)

dark_count_rate

Dark count rate per nanosecond (float)

mu

Average photon number per pulse (float, 0-1)

num_pulses

Number of pulses to generate (int)

pulse_repetition_rate

Pulse repetition rate in nanoseconds (float)

class api.ChannelModel

Pydantic model for channel configuration.

id

Channel identifier (int)

from_

Source node ID (int, alias ‘from’)

to

Destination node ID (int)

fiber_length_km

Fiber length in kilometers (float)

fiber_attenuation_db_per_km

Fiber attenuation in dB per kilometer (float)

wavelength_nm

Operating wavelength in nanometers (int)

fiber_type

Type of fiber (str)

phase_flip_prob

Probability of phase flip noise (float, 0-1, default 0.05)

class api.SimParams

Pydantic model for simulation parameters.

protocol

QKD protocol to use (str: “dps”, “cow”, or “bb84”)

nodes

List of node configurations (List[NodeModel])

channels

List of channel configurations (List[ChannelModel])

cow_monitor_pulse_ratio

COW monitoring pulse ratio (float, 0-1)

cow_detection_threshold_photons

COW detection threshold in photons (float)

cow_extinction_ratio_db

COW extinction ratio in dB (float)

bit_flip_error_prob

Bit flip error probability (float, 0-1, default 0.05)

Error Handling

The API uses standard HTTP status codes:

  • 200 OK: Successful simulation

  • 400 Bad Request: Invalid parameters

  • 422 Unprocessable Entity: Validation errors

  • 500 Internal Server Error: Simulation errors

Error responses include detailed error messages:

{
  "detail": "Error message describing the issue"
}

CORS Support

The API includes CORS middleware to support web frontend integration:

  • Allowed Origins: http://localhost:3000, http://localhost:3001

  • Allowed Methods: All HTTP methods

  • Allowed Headers: All headers

  • Credentials: Supported

Frontend Components

React Components

class QKDForm

Protocol selection and parameter configuration component.

Props:

  • params (object): Current simulation parameters

  • onChange (function): Callback for parameter changes

Features:

  • Protocol selection (DPS, COW, BB84)

  • Protocol-specific parameter configuration

  • Real-time parameter validation

class QKDNetwork

Interactive network topology builder component.

Props:

  • onNetworkChange (function): Callback for network changes

Features:

  • Drag-and-drop node placement

  • Visual channel connections

  • Node and channel parameter editing

  • Undo/redo functionality

  • Network topology export/import

class Results

Simulation results display and analysis component.

Props:

  • results (array): Simulation results

  • loading (boolean): Loading state

Features:

  • Per-channel result display

  • QBER visualization

  • Key rate analysis

  • Theory compliance warnings

  • Detailed parameter breakdown

Configuration

Environment Variables

  • QKD_API_HOST: API host address (default: “127.0.0.1”)

  • QKD_API_PORT: API port (default: 8000)

  • QKD_FRONTEND_PORT: Frontend port (default: 3000)

  • QKD_LOG_LEVEL: Logging level (default: “INFO”)

Configuration Files

  • requirements.txt: Python dependencies

  • package.json: Node.js dependencies

  • conf.py: Sphinx documentation configuration

Performance Considerations

  • Memory Usage: Large simulations may require significant memory

  • CPU Usage: Multi-core processing for parallel simulations

  • Network I/O: API calls for real-time simulation control

  • Storage: Results caching and logging

Security Considerations

  • Input Validation: All parameters are validated before processing

  • Error Handling: Comprehensive error handling prevents information leakage

  • CORS: Proper CORS configuration for web integration

  • Rate Limiting: Consider implementing rate limiting for production use