blocksim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
blocksim/comm.py ADDED
@@ -0,0 +1,237 @@
1
+ """
2
+ Digital communications: modulation, a channel, and demodulation.
3
+
4
+ `QAMModulator` maps bits to complex symbols, `MultipathChannel` applies
5
+ flat Rayleigh or Rician fading and additive Gaussian noise, and
6
+ `QAMDemodulator` decides which symbol was sent. Wired in a line they are
7
+ the textbook link, and the reason to build one in a simulator rather than
8
+ in a loop is that the channel can then be driven by the rest of a diagram
9
+ -- a moving platform, an antenna whose pointing is a state.
10
+
11
+ The channel redraws its fading gain and noise on every clock tick when
12
+ bound to a clock, and on every evaluation when it is not. Bind it: an
13
+ unbound channel is re-randomised at whatever times the integrator happens
14
+ to probe, which is not a sample rate.
15
+
16
+ Baseband and symbol-rate
17
+ ------------------------
18
+ These blocks work at complex baseband: there is no carrier, and time is
19
+ measured in symbols rather than in cycles. That is what makes the model
20
+ runnable at all -- see `blocksim.radar` for what happens when a carrier is
21
+ represented literally.
22
+
23
+ What is not modelled
24
+ --------------------
25
+ No pulse shaping, no timing or carrier recovery, no coding, no
26
+ equalisation.
27
+
28
+ The fading is FLAT despite the block's name: one complex gain applied to
29
+ the whole signal, with no delay spread. That means no frequency
30
+ selectivity and therefore no inter-symbol interference, which is why no
31
+ equaliser is needed here and also why this channel cannot show you why
32
+ one would be. It has no Doppler spectrum either -- successive draws are
33
+ independent rather than correlated in time, so it is not a Jakes or
34
+ Clarke model and a fade lasts exactly one sample.
35
+
36
+ For anything where those matter -- BER curves against theory, coded
37
+ performance, realistic fading -- the specialist libraries do it properly:
38
+ `scikit-commpy` and `sdr` both have the modulation, channel and coding
39
+ chain, and `sionna` if the answer needs to be differentiable.
40
+ """
41
+
42
+ import numpy as np
43
+ from .core import Block
44
+
45
+ __all__ = ["MultipathChannel", "QAMDemodulator", "QAMModulator"]
46
+
47
+
48
+ class QAMModulator(Block):
49
+ """Discrete-time Square QAM Modulator block.
50
+ Maps an integer symbol [0, M-1] to a complex coordinate [I, Q].
51
+ Inputs:
52
+
53
+ [0]: symbol (integer)
54
+
55
+ Outputs:
56
+
57
+ [0]: I (in-phase component)
58
+ [1]: Q (quadrature component)
59
+ """
60
+
61
+ def __init__(self, M=16, name=None):
62
+ self.M = int(M)
63
+ self.L = int(np.sqrt(self.M))
64
+ assert self.L * self.L == self.M, (
65
+ "Constellation size M must be a square integer (e.g. 4, 16, 64)"
66
+ )
67
+
68
+ super().__init__(
69
+ num_inputs=1,
70
+ num_outputs=2,
71
+ name=name,
72
+ inputs=[("symbol", None)],
73
+ outputs=[("I", None), ("Q", None)],
74
+ )
75
+
76
+ def output(self, u):
77
+ symbol = int(np.clip(u[0], 0, self.M - 1))
78
+
79
+ # Grid index mapping
80
+ row = symbol % self.L
81
+ col = symbol // self.L
82
+
83
+ # Map to symmetric constellation coordinates (spacing of 2)
84
+ in_phase = 2.0 * row - (self.L - 1)
85
+ quadrature = 2.0 * col - (self.L - 1)
86
+ return np.array([in_phase, quadrature])
87
+
88
+
89
+ class QAMDemodulator(Block):
90
+ """Discrete-time Square QAM Demodulator block.
91
+ Maps complex coordinates [I, Q] to the nearest integer symbol [0, M-1].
92
+ Inputs:
93
+
94
+ [0]: I (in-phase component)
95
+ [1]: Q (quadrature component)
96
+
97
+ Outputs:
98
+
99
+ [0]: symbol (integer)
100
+ """
101
+
102
+ def __init__(self, M=16, name=None):
103
+ self.M = int(M)
104
+ self.L = int(np.sqrt(self.M))
105
+ assert self.L * self.L == self.M, (
106
+ "Constellation size M must be a square integer (e.g. 4, 16, 64)"
107
+ )
108
+
109
+ super().__init__(
110
+ num_inputs=2,
111
+ num_outputs=1,
112
+ name=name,
113
+ inputs=[("I", None), ("Q", None)],
114
+ outputs=[("symbol", None)],
115
+ )
116
+
117
+ def output(self, u):
118
+ in_phase, quadrature = u[0], u[1]
119
+
120
+ # Inverse mapping: row/col index
121
+ row = np.round((in_phase + (self.L - 1)) / 2.0)
122
+ col = np.round((quadrature + (self.L - 1)) / 2.0)
123
+
124
+ row = int(np.clip(row, 0, self.L - 1))
125
+ col = int(np.clip(col, 0, self.L - 1))
126
+
127
+ symbol = col * self.L + row
128
+ return np.array([symbol], dtype=float)
129
+
130
+
131
+ class MultipathChannel(Block):
132
+ """Flat fading and additive Gaussian noise on a complex baseband pair.
133
+
134
+ Inputs : [I_in, Q_in] Outputs : [I_out, Q_out]
135
+
136
+ (I_out + j Q_out) = h (I_in + j Q_in) + n
137
+
138
+ `fading="rayleigh"` draws `h` from a circularly symmetric complex
139
+ Gaussian of unit average power, `"rician"` adds a deterministic
140
+ component, and anything else (`"none"`) leaves `h = 1` for a pure
141
+ AWGN channel. `noise_std` is the standard deviation PER DIMENSION,
142
+ so the complex noise has variance `2 noise_std^2`.
143
+
144
+ Clocked or not, and why it matters
145
+ ----------------------------------
146
+ Pass `clock=` and the gain and noise are drawn once per tick and
147
+ held -- one draw per symbol, which is what a channel means. Leave it
148
+ out and they are redrawn on *every evaluation*, at whatever times the
149
+ integrator happens to probe; that is not a sample rate. Bind it.
150
+
151
+ A clocked block owns its held value on `self`, and `output()` returns
152
+ that, so it has no direct feedthrough and breaks algebraic loops --
153
+ see `Block`'s docstring for the contract. This block used to get it
154
+ wrong in both possible ways at once: it never called `clock.bind()`,
155
+ so `update()` was never reached, and it read the held value from an
156
+ `xd` argument that the engine always passes as `None`. A clocked
157
+ channel emitted NaN. Nothing caught it because nothing had clocked
158
+ one.
159
+
160
+ The fading is FLAT: one complex gain across the whole signal, no
161
+ delay spread, so no frequency selectivity and no inter-symbol
162
+ interference. Successive draws are independent rather than correlated
163
+ in time, so this is not a Jakes or Clarke model and a fade lasts
164
+ exactly one sample. And nothing here estimates `h` -- the demodulator
165
+ sees the rotated, scaled constellation as it arrives. The module
166
+ docstring says what to reach for when those matter.
167
+ """
168
+
169
+ def __init__(
170
+ self, fading="rayleigh", noise_std=0.0, seed=None, clock=None, name=None
171
+ ):
172
+ self.fading = fading.lower()
173
+ self.noise_std = float(noise_std)
174
+ self.rng = np.random.default_rng(seed)
175
+ self.clock = clock
176
+
177
+ num_discrete = 2 if clock else 0
178
+ super().__init__(
179
+ num_inputs=2,
180
+ num_outputs=2,
181
+ num_discrete=num_discrete,
182
+ clock=clock,
183
+ name=name,
184
+ inputs=[("I_in", None), ("Q_in", None)],
185
+ outputs=[("I_out", None), ("Q_out", None)],
186
+ discrete=[("I_hold", None), ("Q_hold", None)] if clock else None,
187
+ )
188
+ if clock:
189
+ # declaring a clock records it; binding is what makes the tick
190
+ # actually reach update()
191
+ self.clock.bind(self)
192
+ self.xd0 = np.zeros(2, dtype=float)
193
+ self.xd = np.copy(self.xd0)
194
+
195
+ @property
196
+ def has_direct_feedthrough(self):
197
+ """A held sample cannot depend on the input in the present
198
+ instant, so a clocked channel breaks algebraic loops. Unclocked,
199
+ the output is computed from `u` and it does not."""
200
+ return self.clock is None
201
+
202
+ def initialize(self):
203
+ super().initialize()
204
+ if self.clock:
205
+ self.xd = np.copy(self.xd0)
206
+
207
+ def _propagate(self, u):
208
+ """One draw of the channel, applied to the current input."""
209
+ in_phase, quadrature = float(u[0]), float(u[1])
210
+
211
+ if self.fading == "rayleigh":
212
+ gain_i = self.rng.normal(0.0, 1.0 / np.sqrt(2.0))
213
+ gain_q = self.rng.normal(0.0, 1.0 / np.sqrt(2.0))
214
+ elif self.fading == "rician":
215
+ # K-factor of 1: equal deterministic and diffuse power
216
+ gain_i = self.rng.normal(0.5, 0.5)
217
+ gain_q = self.rng.normal(0.5, 0.5)
218
+ else:
219
+ gain_i, gain_q = 1.0, 0.0
220
+
221
+ noise_i = self.rng.normal(0.0, self.noise_std)
222
+ noise_q = self.rng.normal(0.0, self.noise_std)
223
+
224
+ return np.array(
225
+ [
226
+ in_phase * gain_i - quadrature * gain_q + noise_i,
227
+ in_phase * gain_q + quadrature * gain_i + noise_q,
228
+ ]
229
+ )
230
+
231
+ def update(self, t, u):
232
+ # the engine DISCARDS what update() returns, so the held value has
233
+ # to be assigned on self -- the same pattern as DiscreteSpaceState
234
+ self.xd = self._propagate(u)
235
+
236
+ def output(self, t, u):
237
+ return np.copy(self.xd) if self.clock else self._propagate(u)