Skip to content

Commit 681c2b5

Browse files
committed
Refactor Examples: Extract Plotting Code and Convert Print Statements to Comments #34
Enhance visualization and utility functions - Updated BenchmarkVisualizer to use custom color maps for throughput and execution time bar plots. - Refactored visualize_metrics_comparison to simplify bar plotting logic and improve error handling. - Improved SoftBitEnsembleThresholder to handle weight normalization more robustly. - Added validation for code_length and code_dimension in LDPCCodeEncoder, ensuring proper error messages for missing parameters. - Introduced PlottingUtils class for centralized plotting utilities, including functions for LDPC matrix comparison, BER performance, and more. - Added comprehensive plotting functions for signal analysis, channel effects, and capacity analysis.
1 parent 3619acd commit 681c2b5

30 files changed

+1053
-2739
lines changed

.pre-commit-config.yaml

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,19 @@ repos:
8282

8383
# Type checking with mypy (fixed)
8484
- repo: https://github.com/pre-commit/mirrors-mypy
85-
rev: v1.15.0
85+
rev: v1.16.0
8686
hooks:
8787
- id: mypy
8888
# Removed problematic types-all and added specific type stubs
8989
additional_dependencies:
90-
[types-requests, types-PyYAML, types-toml, types-setuptools]
90+
[
91+
types-requests,
92+
types-PyYAML,
93+
types-toml,
94+
types-setuptools,
95+
types-tqdm,
96+
types-seaborn,
97+
]
9198
exclude: "^tests/"
9299

93100
# Python security linter

docs/api_reference.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,7 @@ General utility functions for the Kaira library.
721721
:nosignatures:
722722

723723
CapacityAnalyzer
724+
PlottingUtils
724725

725726

726727
.. currentmodule:: kaira.utils
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
:orphan:
2+
3+
Example Utils
4+
=============
5+
6+
Examples for example utils.
7+
8+
.. raw:: html
9+
10+
<div class="sphx-glr-thumbnails">
11+
12+
.. raw:: html
13+
14+
<div class="sphx-glr-thumbcontainer" tooltip="This example demonstrates how to use the :class:`kaira.utils.CapacityAnalyzer` to analyze the capacity of various modulation schemes and channel models. Channel capacity is a fundamental concept in information theory that represents the maximum rate at which information can be reliably transmitted over a communication channel. It was first introduced by Claude Shannon :cite:`shannon1948mathematical`. .. note:: This example requires matplotlib for visualization and seaborn for enhanced styling. To run faster, set the FAST_MODE flag to True below.">
15+
16+
.. only:: html
17+
18+
.. image:: /auto_examples/example_utils/images/thumb/sphx_glr_plot_capacity_analyzer_thumb.png
19+
:alt: Channel Capacity Analysis with Kaira
20+
21+
:ref:`sphx_glr_auto_examples_example_utils_plot_capacity_analyzer.py`
22+
23+
.. raw:: html
24+
25+
<div class="sphx-glr-thumbnail-title">Channel Capacity Analysis with Kaira</div>
26+
</div>
27+
28+
.. raw:: html
29+
30+
</div>
31+
32+
33+
.. toctree:
34+
:hidden:
35+
36+
/auto_examples/example_utils/plot_capacity_analyzer

docs/examples/modulation/index.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,10 +159,10 @@ Digital modulation schemes and their characteristics in Kaira. These examples sh
159159

160160
.. only:: html
161161

162-
.. image:: /auto_examples/modulation/images/thumb/sphx_glr_plot_qam_modulation_thumb.png
162+
.. image:: /auto_examples/modulation/images/thumb/sphx_glr_plot_qam_modulation_refactored_thumb.png
163163
:alt: Quadrature Amplitude Modulation (QAM)
164164

165-
:ref:`sphx_glr_auto_examples_modulation_plot_qam_modulation.py`
165+
:ref:`sphx_glr_auto_examples_modulation_plot_qam_modulation_refactored.py`
166166

167167
.. raw:: html
168168

@@ -186,4 +186,4 @@ Digital modulation schemes and their characteristics in Kaira. These examples sh
186186
/auto_examples/modulation/plot_pam_modulation
187187
/auto_examples/modulation/plot_pi4qpsk_modulation
188188
/auto_examples/modulation/plot_psk_modulation
189-
/auto_examples/modulation/plot_qam_modulation
189+
/auto_examples/modulation/plot_qam_modulation_refactored

examples/benchmarks/plot_ldpc_codes_comparison.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import time
2222
from typing import Any, Dict, List, Tuple
2323

24+
import matplotlib.cm as cm
2425
import matplotlib.pyplot as plt
2526
import numpy as np
2627
import seaborn as sns
@@ -652,7 +653,7 @@ def simulate_ldpc_performance(ldpc_config: Dict[str, Any], snr_db_values: np.nda
652653
if standard_counts:
653654
standards = list(standard_counts.keys())
654655
counts = list(standard_counts.values())
655-
colors = plt.cm.get_cmap("Set3")(np.linspace(0, 1, len(standards)))
656+
colors = cm.get_cmap("Set3")(np.linspace(0, 1, len(standards)))
656657

657658
wedges, texts, autotexts = ax4.pie(counts, labels=standards, colors=colors, autopct="%1.0f", startangle=90)
658659
ax4.set_title("Professional: Standards\nCompliance", fontsize=12, fontweight="bold")
@@ -884,7 +885,7 @@ def simulate_ldpc_performance(ldpc_config: Dict[str, Any], snr_db_values: np.nda
884885
ax1 = fig_standards.add_subplot(gs_standards[0, 0])
885886
standards_names = list(standards_data.keys())
886887
standards_counts = [len(codes) for codes in standards_data.values()]
887-
colors = plt.cm.get_cmap("Set3")(np.linspace(0, 1, len(standards_names)))
888+
colors = cm.get_cmap("Set3")(np.linspace(0, 1, len(standards_names)))
888889

889890
wedges, texts, autotexts = ax1.pie(standards_counts, labels=standards_names, colors=colors, autopct="%1.0f", startangle=90)
890891
ax1.set_title("Standards Distribution\nin Benchmark", fontsize=12, fontweight="bold")

examples/channels/plot_awgn_channel.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,12 @@
1818
import numpy as np
1919
import torch
2020

21-
from examples.utils.plotting import (
22-
setup_plotting_style,
21+
from examples.example_utils.plotting import (
2322
plot_signal_noise_comparison,
2423
plot_snr_psnr_comparison,
2524
plot_snr_vs_mse,
26-
plot_noise_level_analysis
25+
setup_plotting_style,
2726
)
28-
2927
from kaira.channels import AWGNChannel
3028
from kaira.metrics.image import PSNR
3129
from kaira.metrics.signal import SNR
@@ -114,11 +112,10 @@
114112

115113
# Visualization: Signal Degradation with Noise
116114
# ============================================
117-
# Compare the original clean signal with signals processed through
115+
# Compare the original clean signal with signals processed through
118116
# AWGN channels at different SNR levels to observe noise effects.
119117

120-
fig = plot_signal_noise_comparison(t, signal, outputs, measured_metrics,
121-
"AWGN Channel Effects on Signal Transmission")
118+
fig = plot_signal_noise_comparison(t, signal, outputs, measured_metrics, "AWGN Channel Effects on Signal Transmission")
122119
fig.show()
123120

124121
# %%

examples/channels/plot_binary_channels.py

Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,13 @@
2121
import numpy as np
2222
import torch
2323

24-
from examples.utils.plotting import (
25-
setup_plotting_style,
24+
from examples.example_utils.plotting import (
2625
plot_binary_channel_comparison,
26+
plot_channel_capacity_analysis,
2727
plot_channel_error_rates,
2828
plot_transition_matrices,
29-
plot_channel_capacity_analysis
29+
setup_plotting_style,
3030
)
31-
3231
from kaira.channels import BinaryErasureChannel, BinarySymmetricChannel, BinaryZChannel
3332

3433
# Set random seed for reproducibility
@@ -75,7 +74,7 @@
7574

7675
bsc_outputs.append((p, output, error_rate))
7776
# BSC Channel Analysis Results
78-
# ===========================
77+
# ===========================
7978
# BSC (p={p}): Errors: {errors}/{num_bits}, Error rate: {error_rate:.4f}
8079

8180
# %%
@@ -152,7 +151,7 @@
152151
bsc_output = bsc(binary_data).numpy()[0]
153152
channel_outputs.append(("BSC", bsc_output, bsc_p))
154153

155-
# BEC output (high erasure probability for visibility)
154+
# BEC output (high erasure probability for visibility)
156155
bec_p = 0.2
157156
bec = BinaryErasureChannel(erasure_prob=bec_p)
158157
with torch.no_grad():
@@ -168,9 +167,7 @@
168167

169168
# Visualize channel effects
170169
original_data = binary_data[0].numpy()
171-
fig = plot_binary_channel_comparison(original_data, channel_outputs,
172-
segment_start, segment_length,
173-
"Binary Channel Effects Comparison")
170+
fig = plot_binary_channel_comparison(original_data, channel_outputs, segment_start, segment_length, "Binary Channel Effects Comparison")
174171
fig.show()
175172

176173
# %%
@@ -180,25 +177,23 @@
180177

181178
# Channel Error Rate Analysis
182179
# ===========================
183-
# Compare theoretical vs observed error rates across different
180+
# Compare theoretical vs observed error rates across different
184181
# channel types to validate the implementation accuracy.
185182

186183
# Prepare BSC error rate data
187184
theoretical_bsc = error_probs # Theoretical error rate equals p
188185
observed_bsc = [err_rate for _, _, err_rate in bsc_outputs]
189186

190187
# Plot BSC error rates
191-
fig1 = plot_channel_error_rates(error_probs, theoretical_bsc, observed_bsc,
192-
["BSC"], "Binary Symmetric Channel Error Rates")
188+
fig1 = plot_channel_error_rates(error_probs, theoretical_bsc, observed_bsc, ["BSC"], "Binary Symmetric Channel Error Rates")
193189
fig1.show()
194190

195-
# Prepare BEC erasure rate data
191+
# Prepare BEC erasure rate data
196192
theoretical_bec = erasure_probs # Theoretical erasure rate equals p
197193
observed_bec = [erasure_rate for _, _, erasure_rate in bec_outputs]
198194

199195
# Plot BEC erasure rates
200-
fig2 = plot_channel_error_rates(erasure_probs, theoretical_bec, observed_bec,
201-
["BEC"], "Binary Erasure Channel Erasure Rates")
196+
fig2 = plot_channel_error_rates(erasure_probs, theoretical_bec, observed_bec, ["BEC"], "Binary Erasure Channel Erasure Rates")
202197
fig2.show()
203198

204199
# Prepare Z-Channel error rate data
@@ -208,8 +203,7 @@
208203
observed_z = [err_rate * p_one for _, _, err_rate in z_outputs]
209204

210205
# Plot Z-Channel error rates
211-
fig3 = plot_channel_error_rates(z_error_probs, theoretical_z, observed_z,
212-
["Z-Channel"], "Z-Channel Error Rates")
206+
fig3 = plot_channel_error_rates(z_error_probs, theoretical_z, observed_z, ["Z-Channel"], "Z-Channel Error Rates")
213207
fig3.show()
214208

215209
# %%
@@ -234,11 +228,7 @@
234228
z_matrix = np.array([[1, 0], [p_z, 1 - p_z]])
235229

236230
# Plot transition matrices
237-
matrices = [
238-
("Binary Symmetric Channel", bsc_matrix, p_bsc),
239-
("Binary Erasure Channel", bec_matrix, p_bec),
240-
("Z-Channel", z_matrix, p_z)
241-
]
231+
matrices = [("Binary Symmetric Channel", bsc_matrix, p_bsc), ("Binary Erasure Channel", bec_matrix, p_bec), ("Z-Channel", z_matrix, p_z)]
242232

243233
fig4 = plot_transition_matrices(matrices, "Binary Channel Transition Matrices")
244234
fig4.show()
@@ -256,40 +246,39 @@
256246
# Parameter ranges for capacity analysis
257247
p_range = np.linspace(0, 1, 51)
258248

249+
259250
# Calculate capacities for each channel type
260251
def calculate_bsc_capacity(p):
261252
"""Calculate BSC capacity: C = 1 - H(p)"""
262253
if p == 0 or p == 1:
263254
return 1.0 if p == 0 else 0.0
264255
return 1 + p * np.log2(p) + (1 - p) * np.log2(1 - p)
265256

257+
266258
def calculate_bec_capacity(p):
267259
"""Calculate BEC capacity: C = 1 - p"""
268260
return 1 - p
269261

262+
270263
def calculate_z_capacity(p):
271-
"""Calculate Z-channel capacity"""
264+
"""Calculate Z-channel capacity."""
272265
if p == 0:
273266
return 1.0
274267
if p == 1:
275268
return 0.0
276269
# Z-channel capacity formula
277270
return 1 + (1 - p) * np.log2(1 - p) + p * np.log2(p)
278271

272+
279273
# Calculate capacities
280274
bsc_capacities = np.array([calculate_bsc_capacity(p) for p in p_range])
281275
bec_capacities = np.array([calculate_bec_capacity(p) for p in p_range])
282276
z_capacities = np.array([calculate_z_capacity(p) for p in p_range])
283277

284278
# Plot capacity analysis
285-
capacities = {
286-
"BSC": bsc_capacities,
287-
"BEC": bec_capacities,
288-
"Z-Channel": z_capacities
289-
}
290-
291-
fig5 = plot_channel_capacity_analysis(p_range, capacities,
292-
"Binary Channel Capacity Analysis")
279+
capacities = {"BSC": bsc_capacities, "BEC": bec_capacities, "Z-Channel": z_capacities}
280+
281+
fig5 = plot_channel_capacity_analysis(p_range, capacities, "Binary Channel Capacity Analysis")
293282
fig5.show()
294283

295284
# %%

examples/channels/plot_fading_channels.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,19 @@
1212
magnitude of fading.
1313
"""
1414

15+
import matplotlib.pyplot as plt
1516
import numpy as np
1617
import torch
1718
from scipy import signal
1819

20+
# Plotting imports
21+
from examples.example_utils.plotting import setup_plotting_style
1922
from kaira.channels import AWGNChannel, FlatFadingChannel, PerfectChannel
2023
from kaira.metrics.signal import BitErrorRate
2124
from kaira.modulations import QPSKModulator
2225
from kaira.modulations.utils import calculate_theoretical_ber
2326
from kaira.utils import snr_to_noise_power
2427

25-
# Plotting imports
26-
from examples.utils.plotting import setup_plotting_style
27-
import matplotlib.pyplot as plt
28-
2928
setup_plotting_style()
3029

3130
# %%
@@ -43,7 +42,7 @@
4342
# ------------------------------------
4443
# QPSK Signal Generation
4544
# =====================
46-
#
45+
#
4746
# Let's use Kaira's QPSKModulator to generate QPSK symbols.
4847

4948
# Create a QPSK modulator
@@ -90,7 +89,7 @@
9089
# ------------------------------------------
9190
# Channel Configuration and Setup
9291
# ===============================
93-
#
92+
#
9493
# We'll compare a perfect channel (no distortion), an AWGN channel (noise only),
9594
# and a flat fading channel (fading + noise).
9695

examples/constraints/plot_basic_constraints.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,18 @@
1212
# ----------------------------------------------------------
1313
# We start by importing the necessary modules and setting up the environment.
1414

15+
import matplotlib.pyplot as plt
1516
import numpy as np
1617
import torch
1718

18-
from kaira.constraints import AveragePowerConstraint, PAPRConstraint, TotalPowerConstraint
19-
from kaira.constraints.utils import measure_signal_properties
20-
2119
# Plotting imports
22-
from examples.utils.plotting import (
23-
setup_plotting_style,
20+
from examples.example_utils.plotting import (
2421
plot_constraint_comparison,
25-
plot_signal_properties_comparison
22+
plot_signal_properties_comparison,
23+
setup_plotting_style,
2624
)
27-
import matplotlib.pyplot as plt
25+
from kaira.constraints import AveragePowerConstraint, PAPRConstraint, TotalPowerConstraint
26+
from kaira.constraints.utils import measure_signal_properties
2827

2928
setup_plotting_style()
3029

0 commit comments

Comments
 (0)