Data types
Use this module to define the data types used in the library.
>>> from opticomlib.typing import binary_sequence, electrical_signal, optical_signal, eye, gv
Classes
Global Variables (gv) |
|
|
Binary Sequence |
|
Electrical Signal |
|
Optical Signal |
|
Eye Diagram Parameters. |
- class opticomlib.typing.global_variables[source]
Global Variables (gv)
This object stores the simulation-wide parameters required across the pipeline. It keeps track of the sampling frequency, slot rate, samples per slot, number of simulated slots, optical wavelength/frequency, preferred plotting style, and logging verbosity.
Note
A slot is taken as the smallest time unit representing a binary value of the signal. For example, in PPM a bit is not the same as a slot. However, in OOK a bit and a slot are the same.
This class doesn’t need to be instantiated; it is already exposed as
gv. Use the__call__()method (e.g.gv(**kwargs)) to refresh parameters, update Matplotlib’s style viaplt_styleor adjust the logger throughverbose.Attributes
Number of samples per slot,
16by default.Slot rate in Hz,
1e9by default.Sampling frequency in Samples/s,
R*sps=16e9by default.Optical communication central wavelength in meters,
1550e-9by default.Optical communication central frequency in Hz,
c/wavelength=193.4e12by default.Number of slots to simulate (128 by default).
Time step in seconds,
1/fs=62.5e-12by default.Time array in seconds
Frequency step in rad/s
Frequency array in rad/s
Matplotlib plot style,
"fast"by default.Logging verbosity level,
Noneby default.Methods
__call__([sps, R, fs, wavelength, N, ...])Configures the instance with the provided parameters.
print()Prints the global variables in a formatted manner
default()Return all parameters to default values.
Examples
>>> gv(R=10e9, sps=8, N=100).print()
------------------------------ *** Global Variables *** ------------------------------ sps : 8 R : 1.00e+10 fs : 8.00e+10 λ0 : 1.55e-06 f0 : 1.93e+14 N : 100 dt : 1.25e-11 t : [0.00e+00 1.25e-11 2.50e-11 ... 9.97e-09 9.99e-09 1.00e-08] dw : 6.28e+08 Config ------ plt_style : "fast" verbose : None
Also can be define new variables trough **kwargs. If at least two of this arguments (
sps,fsandR) are not provided a warning will be raised and the default values will be used.>>> gv(alpha=0.5, beta=0.3).print()
------------------------------ *** Global Variables *** ------------------------------ sps : 16 R : 1.00e+09 fs : 1.60e+10 λ0 : 1.55e-06 f0 : 1.93e+14 N : 128 dt : 6.25e-11 t : [0.00e+00 6.25e-11 1.25e-10 ... 1.28e-07 1.28e-07 1.28e-07] dw : 4.91e+07 Config ------ plt_style : "fast" verbose : None Custom ------ alpha : 0.5 beta : 0.3
- sps
Number of samples per slot,
16by default.
- R
Slot rate in Hz,
1e9by default.
- fs
Sampling frequency in Samples/s,
R*sps=16e9by default.
- dt
Time step in seconds,
1/fs=62.5e-12by default.
- wavelength
Optical communication central wavelength in meters,
1550e-9by default.
- f0
Optical communication central frequency in Hz,
c/wavelength=193.4e12by default.
- N
Number of slots to simulate (128 by default).
- t
Time array in seconds
- dw
Frequency step in rad/s
- w
Frequency array in rad/s
- plt_style
Matplotlib plot style,
"fast"by default.
- verbose
Logging verbosity level,
Noneby default. Can be set toDEBUGor 10,INFOor 20,WARNINGor 30.
- __call__(sps: int = None, R: float = None, fs: float = None, wavelength: float = 1.55e-06, N: int = None, plt_style: Literal['ggplot', 'bmh', 'dark_background', 'fast', 'default'] = 'fast', verbose=None, **kargs) Any[source]
Configures the instance with the provided parameters.
- Parameters:
sps (int, optional) – Samples per slot.
R (float, optional) – Rate in Hz.
fs (float, optional) – Sampling frequency in Samples/s.
wavelength (float, optional) – Wavelength in meters. Default is 1550e-9.
N (int, optional) – Number of samples.
plt_style (str, optional) – Matplotlib plot style. Default is “fast”.
verbose (int | None, optional) – Verbosity level for logging.
**kargs (dict) – Additional custom parameters.
- Returns:
The instance itself.
- Return type:
gv
Notes
In the absence of parameters, default values are used. Missing parameters are calculated from the provided ones, prioritizing the default value of gv.R when more than one of sps, fs, and R is not provided.
- class opticomlib.typing.binary_sequence(data: str | Iterable)[source]
Binary Sequence
This class provides methods and attributes to work with binary sequences. The binary sequence can be provided as a string, list, tuple, or numpy array.
Attributes
The binary sequence data, a 1D numpy array of boolean values.
The execution time of the last operation performed on the binary sequence.
Number of ones in the binary sequence.
Number of zeros in the binary sequence.
Number of slots of the binary sequence.
Object type.
Memory size of object in bytes.
Methods
prbs(order[, len, seed, return_seed])Pseudorandom binary sequence generator (PRBS) (static method).
print([msg])Print object parameters.
to_numpy([dtype])Return a NumPy representation of the binary sequence.
flip()Invert the binary sequence.
hamming_distance(other)Calculate the Hamming distance to another binary sequence of the same length.
dac(h)Apply upsampling and FIR filtering to the binary sequence for digital-to-analog conversion.
plot(**kwargs)Plot the binary sequence using matplotlib.
Implemented Operators Operator
Description
~~aNOT operation, bit by bit.&a & bAND operation, bit by bit|a | bOR operation, bit by bit^a ^ bXOR operation, bit by bit+a + bconcatenatea ∪ b;b + aconcatenateb ∪ a.*a * n(n > 1 integer) repeatsan times;a * bequivalent to&operator.==a == bcompares elements, returning abinary_sequencemask of matches.!=a != bcompares elements, returning abinary_sequencemask of differences.[:]a[i]returns the integer value at indexi;a[i:j]returns a slicedbinary_sequence.<,<=,>,>=-,/,//,<<,>>,Not implemented
- data
The binary sequence data, a 1D numpy array of boolean values.
- execution_time
The execution time of the last operation performed on the binary sequence.
- __array__(dtype=None)[source]
Return the array representation of the binary sequence.
This method provides the basic array conversion for NumPy compatibility. It returns the data. This is the fundamental protocol that allows the object to be converted to a NumPy array when needed, enabling direct use in NumPy functions that expect array-like objects.
Unlike
__array_ufunc__and__array_function__, this method is called for basic array conversion and does not handle specific NumPy operations - it simply provides the underlying data as an array.- Parameters:
dtype (np.dtype, optional) – Desired data type of the array.
- Returns:
The array representation of the binary data.
- Return type:
np.ndarray
- __getattr__(name)[source]
Delegate attribute access to the underlying NumPy array for array-like methods.
This method allows instances of
binary_sequenceto access NumPy array methods (like max, min, sum, etc.) directly as if they were arrays. If the requested attribute is a method or property of np.ndarray, it will be called on the array representation of this object.- Parameters:
name (str) – The name of the attribute being accessed.
- Returns:
The result of calling the attribute on the array representation.
- Return type:
result
- Raises:
AttributeError – If the attribute is not found in np.ndarray.
- __array_ufunc__(ufunc, method, *inputs, **kwargs)[source]
Handle NumPy universal functions (ufuncs) by converting the object to an array.
This method is specifically designed for NumPy’s universal functions, which are element-wise operations like np.add, np.sin, np.multiply, etc. When a ufunc is called on an instance of this class, this method intercepts the call, converts any instances of this class in the inputs to arrays using
__array__(), and then applies the ufunc to the converted arrays.Unlike
__array__, which provides basic array conversion, this method handles the execution of specific ufunc operations. Unlike__array_function__, which handles higher-level array functions, this focuses on element-wise operations.- Parameters:
ufunc (numpy.ufunc) – The NumPy universal function being called.
method (str) – The method of the ufunc (e.g., ‘__call__’, ‘reduce’).
*inputs (tuple) – The input arguments to the ufunc.
**kwargs (dict) – Keyword arguments passed to the ufunc.
- Returns:
The result of applying the ufunc to the converted inputs, wrapped in the appropriate class if the result is an array with compatible shape.
- Return type:
result
- __array_function__(func, types, args, kwargs)[source]
Handle NumPy array functions by converting the object to an array.
This method is called for NumPy array functions that are not universal functions (ufuncs). It handles higher-level array operations like np.sum, np.mean, np.concatenate, np.fft.fft, and other array manipulation functions. When such a function is called on an instance of this class, this method converts any instances in the arguments to arrays and then calls the function with the converted arguments.
Key differences from other protocols:
__array__: Provides basic array conversion without handling specific operations.__array_ufunc__: Handles element-wise universal functions (ufuncs) like np.add, np.sin, etc.__array_function__: Handles higher-level array functions and transformations like np.abs, etc.
This enables seamless integration with NumPy’s array function ecosystem, allowing instances to be used directly in functions like np.sum(x), np.mean(x), np.concatenate([x, y]), etc., without manual conversion.
- Parameters:
func (callable) – The NumPy array function being called (e.g., np.sum, np.mean).
types (tuple) – The types of all arguments passed to the function.
args (tuple) – The positional arguments passed to the function.
kwargs (dict) – The keyword arguments passed to the function.
- Returns:
The result of applying the NumPy array function to the converted arguments, wrapped in the appropriate class if the result is an array with compatible shape.
- Return type:
result
- __getitem__(slice: int | slice)[source]
Get a slice of the binary sequence (
self[slice]).- Parameters:
slice (
intorslice) – The slice to get.- Returns:
The value of the slot if slice is an integer, or a new binary sequence object with the result of the slice.
- Return type:
intorbinary_sequence
- property ones
Number of ones in the binary sequence.
- property zeros
Number of zeros in the binary sequence.
- property size
Number of slots of the binary sequence.
- property type
Object type.
- property sizeof
Memory size of object in bytes.
- static prbs(order: int, len: int = None, seed: int = None, return_seed: bool = False)[source]
Pseudorandom binary sequence generator (PRBS) (static method).
- Parameters:
order (
int, {7, 9, 11, 15, 20, 23, 31}) – degree of the generating pseudorandom polynomiallen (
int, optional) – lenght of output binary sequenceseed (
int, optional) – seed of the generator (initial state of the LFSR). It must be provided if you want to continue the sequence. Default is 2**order-1.return_seed (
bool, optional) – If True, the last state of LFSR is returned. Default is False.
- Returns:
out (
binary_sequence) – generated pseudorandom binary sequence if return_seed is Falseout, last_seed (
tupleof (binary_sequence, : obj:int)) – generated pseudorandom binary sequence and last state of LFSR if return_seed
- print(msg: str = None)[source]
Print object parameters.
- Parameters:
msg (str, opcional) – top message to show
- Returns:
The same object.
- Return type:
- to_numpy(dtype: dtype | None = None) ndarray[source]
Return a NumPy representation of the binary sequence. This method is similar to
__array__, the diference is that some libraries, as matplotlib, used to call this method to get the numpy array.
- flip()[source]
Invert the binary sequence. Equivalent to the
~operator.- Returns:
A new binary sequence object with the result of the inversion.
- Return type:
- hamming_distance(other)[source]
Calculate the Hamming distance to another binary sequence of the same length.
- Parameters:
other (
strorbinary_sequenceorArray_Like) – The binary sequence to compare.- Returns:
The Hamming distance between the two binary sequences.
- Return type:
int
- dac(h: ndarray)[source]
Apply upsampling and FIR filtering to the binary sequence for digital-to-analog conversion.
This method upsamples the binary sequence by the global samples per slot (gv.sps) and applies the provided FIR filter to produce an electrical signal.
- Parameters:
h (
np.ndarray) – The FIR filter impulse response to use for shaping the signal.- Returns:
The resulting electrical signal after upsampling, filtering, and downsampling.
- Return type:
- class opticomlib.typing.electrical_signal(signal: str | Iterable, noise: str | Iterable = NULL, dtype: dtype = None)[source]
Electrical Signal
This class provides methods and attributes to work with electrical signals. It has overloaded operators necessary to properly interpret the
+,-,*,/,**, and comparison operations as any numpy array.Attributes
The signal values, a 1D array-like values.
The noise values, a 1D array-like values.
The execution time of the last operation performed.
Number of samples of the electrical signal.
Real part of the electrical signal (signal + noise).
Imaginary part of the electrical signal (signal + noise).
Object type.
Sampling frequency of the electrical signal.
Samples per slot of the electrical signal.
Time step of the electrical signal.
Time array for the electrical signal.
Memory size of object in bytes.
Methods
__init__(signal[, noise, dtype])Initialize the electrical signal object.
__call__(domain[, shift])Return a new object with Fast Fourier Transform (FFT) of signal and noise of input object.
print([msg])Print object parameters.
to_numpy([dtype, copy])Return a NumPy representation of the electrical signal (signal + noise).
conj()Return the complex conjugate of the electrical signal.
sum([axis])Return the sum of the elements over a given axis.
w([shift])Return angular frequency (rad/s) for spectrum representation.
f([shift])Return frequency (Hz) for spectrum representation.
abs([of])Get absolute value of
signal,noiseorsignal+noise.power([unit, of])Get power of the electrical signal.
normalize([by])Return the power-normalized signal
phase()Get phase of the electrical signal:
unwrap(angle(signal+noise)).filter(h)Apply FIR filter of impulse response h to the electrical signal:
np.convolve(signal + noise, h, mode='same').plot([fmt, n, xlabel, ylabel, grid, hold, show])Plot signal in time domain.
psd([fmt, mode, n, xlabel, ylabel, yscale, ...])Plot Power Spectral Density (PSD) of the electrical/optical signal.
plot_eye([n_traces, cmap, N_grid_bins, ...])Plots a colored eye diagram, internally calculating color density.
grid(**kwargs)Add grid to the plot.
legend(*args, **kwargs)Add a legend to the plot.
show()Show plots.
Implemented Operators Operator
Description
+a + badds signals and noises element-wise;sig = (a.signal + b.signal), noi = (a.noise + b.noise)-a - bsubtracts signals and noises element-wise;sig = (a.signal - b.signal), noi = (a.noise - b.noise)*a * bmultiplies twoelectrical_signal;sig = (a.signal*b.signal)noi = (a.signal*b.noise + a.noise*b.signal + a.noise*b.noise)/a / ndivides signal and noise by a scalar;sig = (a.signal/n), noi = (a.signal/n)//a // nfloor divides signal and noise by a scalar;sig = (a.signal//n), noi = (a.signal//n)**a ** nraiseselectrical_signalto a power;- n=1 --> sig = (a.signal), noi = (a.noise);- n=2 --> sig = (a.signal**2), noi = (2*a.signal*a.noise + a.noise**2)- n=other --> sig = (a.signal + a.noise)**n, noi=NULL>a > bcompares signals element-wise, returnsbinary_sequencemask.<a < bcompares signals element-wise, returnsbinary_sequencemask.==a == bcompares signals element-wise, returnsnp.ndarraymask.[:]a[i]returns the value at indexi;a[i:j]returns a slicedelectrical_signal.-(unary)-anegates signal and noise.- __init__(signal: str | Iterable, noise: str | Iterable = NULL, dtype: dtype = None) None[source]
Initialize the electrical signal object.
- Parameters:
signal (
stror 1D array_like or scalar) – The signal values.noise (
stror 1D array_like or scalar, optional) – The noise values. Defaults toNULL.dtype (
np.dtype, optional) – The desired data type for the signal and noise arrays. If not provided, the data type will be inferred from the input data. Defaults toNone.
Notes
The signal and noise can be provided as a string, in which case it will be converted to a
numpy.arrayusing thestr2array()function. For example:>>> electrical_signal('1 2 3,4,5') # separate values by space or comma indistinctly electrical_signal(signal=[1 2 3 4 5], noise=NULL) >>> electrical_signal('1+2j, 3+4j, 5+6j') # complex values electrical_signal(signal=[1.+2.j 3.+4.j 5.+6.j], noise=NULL)
- signal
The signal values, a 1D array-like values.
- noise
The noise values, a 1D array-like values.
- execution_time
The execution time of the last operation performed.
- __call__(domain: Literal['t', 'w', 'f'], shift: bool = False)[source]
Return a new object with Fast Fourier Transform (FFT) of signal and noise of input object.
- Parameters:
domain ({'t', 'w', 'f'}) – Domain to transform. ‘t’ for time domain (ifft is applied), ‘w’ and ‘f’ for frequency domain (fft is applied).
shift (
bool, optional) – If True, apply thenp.fft.fftshift()ornp.fft.ifftshiftfunctions as appropriate.
- Returns:
new_obj – A new electrical signal object with the result of the transformation.
- Return type:
- Raises:
TypeError – If
domainis not one of the following values (‘t’, ‘w’, ‘f’).
- property size: ndarray
Number of samples of the electrical signal.
- property real: ndarray
Real part of the electrical signal (signal + noise).
- property imag: ndarray
Imaginary part of the electrical signal (signal + noise).
- property type
Object type.
- property sizeof
Memory size of object in bytes.
- property fs
Sampling frequency of the electrical signal.
- property sps
Samples per slot of the electrical signal.
- property dt
Time step of the electrical signal.
- property t
Time array for the electrical signal.
- print(msg: str = None)[source]
Print object parameters.
- Parameters:
msg (
str, opcional) – top message to show- Returns:
self – The same object.
- Return type:
- to_numpy(dtype: dtype | None = None, copy: bool = False) ndarray[source]
Return a NumPy representation of the electrical signal (signal + noise).
- conj()[source]
Return the complex conjugate of the electrical signal.
- Returns:
The complex conjugate of the electrical signal.
- Return type:
- sum(axis: int = None)[source]
Return the sum of the elements over a given axis.
- Parameters:
axis (
int, optional) – Axis along which the sum is computed. By default, the sum is computed over the entire array.- Returns:
New object with signal and noise summed over the specified axis.
- Return type:
- w(shift: bool = False)[source]
Return angular frequency (rad/s) for spectrum representation.
- Parameters:
shift (
bool, optional) – If True, apply fftshift().- Returns:
The angular frequency array for signals simulation.
- Return type:
np.ndarray
- f(shift: bool = False)[source]
Return frequency (Hz) for spectrum representation.
- Parameters:
shift (
bool, optional) – If True, apply fftshift().- Returns:
The frequency array for signals simulation.
- Return type:
np.ndarray
- abs(of: Literal['signal', 'noise', 'all'] = 'all')[source]
Get absolute value of
signal,noiseorsignal+noise.- Parameters:
of (
str, optional) – Defines from which attribute to obtain the absolute value. If ‘all’, absolute value ofsignal+noiseis determined.- Returns:
out – The absolute value of the object.
- Return type:
np.ndarray, (1D or 2D, float)
- power(unit: Literal['W', 'dBm'] = 'W', of: Literal['signal', 'noise', 'all'] = 'all')[source]
Get power of the electrical signal.
- Parameters:
unit (
str, optional) – Defines the unit of power. ‘W’ for Watts, ‘dBm’ for decibels-milliwatts.of (
str, optional) – Defines from which attribute to obtain the power. If ‘all’, power ofsignal+noiseis determined.
- Returns:
The power of the electrical signal.
- Return type:
float
- normalize(by: Literal['power', 'amplitude'] = 'power')[source]
Return the power-normalized signal
- Parameters:
by (
str, optional) – Defines the normalization method.'power'for power normalization,'amplitude'for amplitude normalization.- Returns:
The normalized electrical signal.
- Return type:
- phase()[source]
Get phase of the electrical signal:
unwrap(angle(signal+noise)).- Returns:
the unwrapped phase of the electrical signal.
- Return type:
np.ndarray
- filter(h: ndarray)[source]
Apply FIR filter of impulse response h to the electrical signal:
np.convolve(signal + noise, h, mode='same').- Parameters:
h (
np.ndarray) – The FIR filter impulse response.- Returns:
An electrical signal object with the result of the filtering.
- Return type:
- plot(fmt: str | list = '-', n: int = None, xlabel: str = None, ylabel: str = None, grid: bool = False, hold: bool = True, show: bool = False, **kwargs: dict)[source]
Plot signal in time domain.
For electrical_signal: plots the real part of the signal. For optical_signal: plots the intensity/power.
- Parameters:
fmt (
strorlist, optional) – Format style of line. Example'b-.', Defaults to'-'.n (
int, optional) – Number of samples to plot. Defaults to the length of the signal.xlabel (
str, optional) – X-axis label. Defaults to'Time [ns]'.ylabel (
str, optional) – Y-axis label. Defaults to'Amplitude [V]'grid (
bool, optional) – If show grid. Defaults toFalse.hold (
bool, optional) – If hold the current plot. Defaults toTrue.**kwargs (
dict) – Additional keyword arguments compatible withmatplotlib.pyplot.plot().
- Returns:
The same object.
- Return type:
- psd(fmt: str | list = '-', mode: Literal['x', 'y', 'both'] = 'x', n: int = None, xlabel: str = None, ylabel: str = None, yscale: Literal['linear', 'dbm'] = 'dbm', grid: bool = False, hold: bool = True, show: bool = False, **kwargs: dict)[source]
Plot Power Spectral Density (PSD) of the electrical/optical signal.
- Parameters:
fmt (
strorlist) – Format style of line. Example'b-.'. Defaults to'-'.mode (
str, optional) –Polarization mode to show (for optical signals). Defaults to
'x'.'x'plot polarization x.'y'plot polarization y.'both'plot both polarizations x and y in the same figure.
n (
int, optional) – Number of samples to plot. Defaults to the length of the signal.xlabel (
str, optional) – X-axis label. Defaults to'Frequency [GHz]'.ylabel (
str, optional) – Y-axis label. Defaults to'Power [dBm]'ifyscale='dbm'or'Power [mW]'ifyscale='linear'.yscale (
str, {‘linear’, ‘dbm’}, optional) – Kind of Y-axis plot. Defaults to'dbm'.grid (
bool, optional) – If show grid. Defaults toTrue.hold (
bool, optional) – If hold the current plot. Defaults toTrue.**kwargs (
dict) – Additional matplotlib arguments.
- Returns:
obj – The same object.
- Return type:
electrical_signal
- plot_eye(n_traces=None, cmap='viridis', N_grid_bins=350, grid_sigma=3, ax=None, **plot_kw)[source]
Plots a colored eye diagram, internally calculating color density.
- Parameters:
n_traces (
int, optional) – Maximum number of traces to plot. IfNone, all available traces will be plotted. Defaults toNone.cmap (
str, optional) – Name of the matplotlib colormap. Defaults to'viridis'.N_grid_bins (
int, optional) – Number of bins for the density histogram. Defaults to350.grid_sigma (
float, optional) – Sigma for the Gaussian filter applied to the density. Defaults to3.ax (
matplotlib.axes.Axes, optional) – Axes object to plot on. IfNone, creates new figure and axes. Defaults toNone.**plot_kw (
dict, optional) –Additional plotting parameters:
Figure parameters (used only if ax is ``None``):
figsize :
tuple, default(10, 6)dpi :
int, default100
Line collection parameters:
linewidth :
float, default0.75alpha :
float, default0.25capstyle :
str, default'round'joinstyle :
str, default'round'
Axes formatting parameters:
xlabel :
str, default"Time (2-symbol segment)"ylabel :
str, default"Amplitude"title :
str, default"Eye Diagram ({num_traces} traces)"grid : bool, default
Truegrid_alpha :
float, default0.3xlim :
tuple, optional (xmin, xmax)ylim :
tuple, optional (ymin, ymax)tight_layout :
bool, defaultTrue
Display parameters:
show :
bool, defaultTrue(whether to callplt.show())
- Returns:
The same object with the plotted eye diagram.
- Return type:
- grid(**kwargs)[source]
Add grid to the plot.
- Parameters:
**kwargs (
dict) – Arbitrary keyword arguments to pass to the function.- Returns:
self – The same object.
- Return type:
- legend(*args, **kwargs)[source]
Add a legend to the plot.
- Parameters:
*args (
iterable) – Variable length argument list to pass to the function.**kwargs (
dict) – Arbitrary keyword arguments to pass to the function.
- Returns:
self – The same object.
- Return type:
- class opticomlib.typing.optical_signal(signal: str | Iterable, noise: str | Iterable = NULL, n_pol: Literal[1, 2] = None, dtype: dtype = None)[source]
Optical Signal
Bases:
electrical_signalThis class provides methods and attributes to work with optical signals. Attributes and some methods are inherited from the
electrical_signalclass.Attributes
signalThe signal values, a 1D array-like values.
noiseThe noise values, a 1D array-like values.
execution_timeThe execution time of the last operation performed.
Methods
__init__(signal[, noise, n_pol, dtype])Initialize the optical signal object.
plot([fmt, mode, n, xlabel, ylabel, grid, ...])Plot signal in time domain.
- __init__(signal: str | Iterable, noise: str | Iterable = NULL, n_pol: Literal[1, 2] = None, dtype: dtype = None)[source]
Initialize the optical signal object.
- Parameters:
signal (
stror array_like (1D, 2D) or scalar) – The signal values.noise (
stror array_like (1D, 2D) or scalar, optional) – The noise values, default isNULL.n_pol (
int, optional) – Number of polarizations. Defaults to1.
- property size: ndarray
Number of samples of one polarization of the optical signal.
- plot(fmt: str | list = '-', mode: Literal['field', 'power'] = 'power', n: int = None, xlabel: str = None, ylabel: str = None, grid: bool = False, hold: bool = True, show: bool = False, **kwargs: dict)[source]
Plot signal in time domain.
For optical_signal: plots the intensity/power or field.
- Parameters:
fmt (
strorlist, optional) – Format style of line. Example'b-.', Defaults to'-'.mode (
str, optional) –Plot mode.
'field','power'(default).'field'plot real and imaginary parts of the field one-polarization.'power'plot power/intensity (one or two polarizations).
n (
int, optional) – Number of samples to plot. Defaults to the length of the signal.xlabel (
str, optional) – X-axis label. Defaults to'Time [ns]'.ylabel (
str, optional) – Y-axis label. Defaults to'Power [mW]'for power,'Field [W**0.5]'for field.grid (
bool, optional) – If show grid. Defaults toFalse.hold (
bool, optional) – If hold the current plot. Defaults toTrue.**kwargs (
dict) – Additional keyword arguments compatible withmatplotlib.pyplot.plot().
- Returns:
self – The same object.
- Return type:
- class opticomlib.typing.eye(**kwargs: dict)[source]
Eye Diagram Parameters.
This object contains the parameters of an eye diagram and methods to plot it.
Methods
__init__(**kwargs)Initialize the eye diagram object.
__str__([title])Return a formatted string with the eye diagram data.
print([msg])Print object parameters.
plot([show_options, hlines, vlines, style, ...])Plot eye diagram.
show()Show plot
- t
The time values resampled. Shape (Nx1).
- Type:
np.ndarray
- y
The signal values resampled. Shape (Nx1).
- Type:
np.ndarray
- dt
Time between samples.
- Type:
float
- sps
Samples per slot.
- Type:
int
- t_left
Cross time of left edge.
- Type:
float
- t_right
Cross time of right edge.
- Type:
float
- t_opt
Optimal time decision.
- Type:
float
- t_dist
Time between slots.
- Type:
float
- t_span0
t_opt - t_dist*5%.
- Type:
float
- t_span1
t_opt + t_dist*5%.
- Type:
float
- y_top
Samples of signal above threshold and within t_span0 and t_apan1.
- Type:
np.ndarray
- y_bot
Samples of signal below threshold and within t_span0 and t_apan1.
- Type:
np.ndarray
- mu0
Mean of y_bot.
- Type:
float
- mu1
Mean of y_top.
- Type:
float
- s0
Standard deviation of y_bot.
- Type:
float
- s1
Standard deviation of y_top.
- Type:
float
- er
Extinction ratio.
- Type:
float
- eye_h
Eye height.
- Type:
float
- __init__(**kwargs: dict)[source]
Initialize the eye diagram object.
- Parameters:
**kwargs (
dict, optional) – Dictionary with the eye diagram parameters.
- print(msg: str = None)[source]
Print object parameters.
- Parameters:
msg (
str, optional) – Top message to show.- Returns:
self – Same object
- Return type:
- plot(show_options: ~opticomlib.typing.EyeShowOptions = <opticomlib.typing.EyeShowOptions object>, hlines: list = [], vlines: list = [], style: ~typing.Literal['dark', 'light'] = 'dark', cmap: ~typing.Literal['viridis', 'plasma', 'inferno', 'cividis', 'magma', 'winter'] = 'winter', smooth: bool = True, title: str = '', savefig: str = None, ax=None)[source]
Plot eye diagram.
- Parameters:
show_options (
typing.EyeShowOptions, optional) – Options to show in the plot. Default show all.hlines (
list, optional) – A list of time values in which hlines will be set.vlines (
list, optional) – A list of voltage values in which vlines will be set.style (
str, optional) – Plot style. ‘dark’ or ‘light’.cmap (
str, optional) – Colormap to plot.title (
str, optional) – Title of plot.savefig (
str, optional) – Name of the file to save the plot. If None, the plot is not saved. Input just the name of the file without extension (extension is .png by default).
- Returns:
self – Same object
- Return type: