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()

Global Variables (gv)

binary_sequence(data)

Binary Sequence

electrical_signal(signal[, noise, dtype])

Electrical Signal

optical_signal(signal[, noise, n_pol, dtype])

Optical Signal

eye(**kwargs)

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 via plt_style or adjust the logger through verbose.

Attributes

sps

Number of samples per slot, 16 by default.

R

Slot rate in Hz, 1e9 by default.

fs

Sampling frequency in Samples/s, R*sps=16e9 by default.

wavelength

Optical communication central wavelength in meters, 1550e-9 by default.

f0

Optical communication central frequency in Hz, c/wavelength=193.4e12 by default.

N

Number of slots to simulate (128 by default).

dt

Time step in seconds, 1/fs=62.5e-12 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, None by 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, fs and R) 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, 16 by default.

R

Slot rate in Hz, 1e9 by default.

fs

Sampling frequency in Samples/s, R*sps=16e9 by default.

dt

Time step in seconds, 1/fs=62.5e-12 by default.

wavelength

Optical communication central wavelength in meters, 1550e-9 by default.

f0

Optical communication central frequency in Hz, c/wavelength=193.4e12 by 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, None by default. Can be set to DEBUG or 10, INFO or 20, WARNING or 30.

print()[source]

Prints the global variables in a formatted manner

__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.

default()[source]

Return all parameters to default values.

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

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.

ones

Number of ones in the binary sequence.

zeros

Number of zeros in the binary sequence.

size

Number of slots of the binary sequence.

type

Object type.

sizeof

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

~

~a NOT operation, bit by bit.

&

a & b AND operation, bit by bit

|

a | b OR operation, bit by bit

^

a ^ b XOR operation, bit by bit

+

a + b concatenate a b; b + a concatenate b a.

*

a * n (n > 1 integer) repeats a n times; a * b equivalent to & operator.

==

a == b compares elements, returning a binary_sequence mask of matches.

!=

a != b compares elements, returning a binary_sequence mask of differences.

[:]

a[i] returns the integer value at index i; a[i:j] returns a sliced binary_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_sequence to 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 (int or slice) – 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:

int or binary_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 polynomial

  • len (int, optional) – lenght of output binary sequence

  • seed (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 False

  • out, last_seed (tuple of (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:

binary_sequence

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:

binary_sequence

hamming_distance(other)[source]

Calculate the Hamming distance to another binary sequence of the same length.

Parameters:

other (str or binary_sequence or Array_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:

electrical_signal

plot(**kwargs)[source]

Plot the binary sequence using matplotlib.

Parameters:

**kwargs (dict) – Additional keyword arguments to customize the plot.

Returns:

The axes object of the plot.

Return type:

matplotlib.axes.Axes

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

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.

size

Number of samples of the electrical signal.

real

Real part of the electrical signal (signal + noise).

imag

Imaginary part of the electrical signal (signal + noise).

type

Object type.

fs

Sampling frequency of the electrical signal.

sps

Samples per slot of the electrical signal.

dt

Time step of the electrical signal.

t

Time array for the electrical signal.

sizeof

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, noise or signal+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 + b adds signals and noises element-wise; sig = (a.signal + b.signal), noi = (a.noise + b.noise)

-

a - b subtracts signals and noises element-wise; sig = (a.signal - b.signal), noi = (a.noise - b.noise)

*

a * b multiplies two electrical_signal; sig = (a.signal*b.signal) noi = (a.signal*b.noise + a.noise*b.signal + a.noise*b.noise)

/

a / n divides signal and noise by a scalar; sig = (a.signal/n), noi = (a.signal/n)

//

a // n floor divides signal and noise by a scalar; sig = (a.signal//n), noi = (a.signal//n)

**

a ** n raises electrical_signal to 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 > b compares signals element-wise, returns binary_sequence mask.

<

a < b compares signals element-wise, returns binary_sequence mask.

==

a == b compares signals element-wise, returns np.ndarray mask.

[:]

a[i] returns the value at index i; a[i:j] returns a sliced electrical_signal.

- (unary)

-a negates signal and noise.

__init__(signal: str | Iterable, noise: str | Iterable = NULL, dtype: dtype = None) None[source]

Initialize the electrical signal object.

Parameters:
  • signal (str or 1D array_like or scalar) – The signal values.

  • noise (str or 1D array_like or scalar, optional) – The noise values. Defaults to NULL.

  • 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 to None.

Notes

The signal and noise can be provided as a string, in which case it will be converted to a numpy.array using the str2array() 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 the np.fft.fftshift() or np.fft.ifftshift functions as appropriate.

Returns:

new_obj – A new electrical signal object with the result of the transformation.

Return type:

electrical_signal or optical_signal

Raises:

TypeError – If domain is 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:

electrical_signal

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:

electrical_signal

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:

electrical_signal

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, noise or signal+noise.

Parameters:

of (str, optional) – Defines from which attribute to obtain the absolute value. If ‘all’, absolute value of signal+noise is 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 of signal+noise is 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:

electrical_signal

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:

electrical_signal

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 (str or list, 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 to False.

  • hold (bool, optional) – If hold the current plot. Defaults to True.

  • **kwargs (dict) – Additional keyword arguments compatible with matplotlib.pyplot.plot().

Returns:

The same object.

Return type:

electrical_signal

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 (str or list) – 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]' if yscale='dbm' or 'Power [mW]' if yscale='linear'.

  • yscale (str, {‘linear’, ‘dbm’}, optional) – Kind of Y-axis plot. Defaults to 'dbm'.

  • grid (bool, optional) – If show grid. Defaults to True.

  • hold (bool, optional) – If hold the current plot. Defaults to True.

  • **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. If None, all available traces will be plotted. Defaults to None.

  • cmap (str, optional) – Name of the matplotlib colormap. Defaults to 'viridis'.

  • N_grid_bins (int, optional) – Number of bins for the density histogram. Defaults to 350.

  • grid_sigma (float, optional) – Sigma for the Gaussian filter applied to the density. Defaults to 3.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. If None, creates new figure and axes. Defaults to None.

  • **plot_kw (dict, optional) –

    Additional plotting parameters:

    Figure parameters (used only if ax is ``None``):

    • figsize : tuple, default (10, 6)

    • dpi : int, default 100

    Line collection parameters:

    • linewidth : float, default 0.75

    • alpha : float, default 0.25

    • capstyle : 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 True

    • grid_alpha : float, default 0.3

    • xlim : tuple, optional (xmin, xmax)

    • ylim : tuple, optional (ymin, ymax)

    • tight_layout : bool, default True

    Display parameters:

    • show : bool, default True (whether to call plt.show())

Returns:

The same object with the plotted eye diagram.

Return type:

electrical_signal

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:

electrical_signal

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:

electrical_signal

show()[source]

Show plots.

Returns:

self – The same object.

Return type:

electrical_signal

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_signal

This class provides methods and attributes to work with optical signals. Attributes and some methods are inherited from the electrical_signal class.

Attributes

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.

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 (str or array_like (1D, 2D) or scalar) – The signal values.

  • noise (str or array_like (1D, 2D) or scalar, optional) – The noise values, default is NULL.

  • n_pol (int, optional) – Number of polarizations. Defaults to 1.

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 (str or list, 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 to False.

  • hold (bool, optional) – If hold the current plot. Defaults to True.

  • **kwargs (dict) – Additional keyword arguments compatible with matplotlib.pyplot.plot().

Returns:

self – The same object.

Return type:

optical_signal

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.

__str__(title: str = None)[source]

Return a formatted string with the eye diagram data.

print(msg: str = None)[source]

Print object parameters.

Parameters:

msg (str, optional) – Top message to show.

Returns:

self – Same object

Return type:

eye

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:

eye

show()[source]

Show plot

Returns:

self – The same object.

Return type:

eye