pyphysim.util package

Submodules

pyphysim.util.conversion module

Module containing function related to several conversions, such as linear to dB, binary to gray code, as well as the inverse of them.

pyphysim.util.conversion.EbN0_dB_to_SNR_dB(EbN0: NumberOrArray, bits_per_symb: int) → NumberOrArray[source]

Convert an Eb/N0 value (in dB) to the equivalent SNR value (also in dB).

Parameters
  • EbN0 – Eb/N0 value (in dB)

  • bits_per_symb – Number of bits in a symbol.

Returns

SNR value (in dB)

Return type

SNR

pyphysim.util.conversion.SNR_dB_to_EbN0_dB(SNR: NumberOrArray, bits_per_symb: int) → NumberOrArray[source]

Convert an SNR value (in dB) to the equivalent Eb/N0 value (also in dB).

Parameters
  • SNR – SNR value (in dB).

  • bits_per_symb – Number of bits in a symbol.

Returns

Eb/N0 value (in dB)

Return type

EbN0

pyphysim.util.conversion.binary2gray(num: IntOrIntArray) → IntOrIntArray[source]

Convert a number (in decimal format) to the corresponding Gray code (still in decimal format).

Parameters

num (int | np.ndarray) – The number in decimal encoding

Returns

num_gray – Corresponding gray code (in decimal format) of num.

Return type

int | np.ndarray

Examples

>>> binary2gray(np.arange(0, 8))
array([0, 1, 3, 2, 6, 7, 5, 4])
pyphysim.util.conversion.dB2Linear(valueIndB: NumberOrArray) → NumberOrArray[source]

Convert input from dB to linear scale.

Parameters

valueIndB (int | float | np.ndarray) – Value in dB

Returns

valueInLinear – Value in Linear scale.

Return type

int | float | np.ndarray

Examples

>>> dB2Linear(30)
1000.0
pyphysim.util.conversion.dBm2Linear(valueIndBm: NumberOrArray) → NumberOrArray[source]

Convert input from dBm to linear scale.

Parameters

valueIndBm (int | float | np.ndarray) – Value in dBm.

Returns

valueInLinear – Value in linear scale.

Return type

float | np.ndarray

Examples

>>> dBm2Linear(60)
1000.0
pyphysim.util.conversion.gray2binary(num: IntOrIntArray) → IntOrIntArray[source]

Convert a number in Gray code (in decimal format) to its original value (in decimal format).

Parameters

num (int | np.ndarray) – The number in gray coding

Returns

num_orig – The original number (in decimal format) whose Gray code correspondent is num.

Return type

int | np.ndarray

Examples

>>> gray2binary(binary2gray(np.arange(0,10)))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
pyphysim.util.conversion.linear2dB(valueInLinear: NumberOrArray) → NumberOrArray[source]

Convert input from linear to dB scale.

Parameters

valueInLinear (int | float | np.ndarray) – Value in Linear scale.

Returns

valueIndB – Value in dB scale.

Return type

int | float | np.ndarray

Examples

>>> linear2dB(1000)
30.0
pyphysim.util.conversion.linear2dBm(valueInLinear: NumberOrArray) → NumberOrArray[source]

Convert input from linear to dBm scale.

Parameters

valueInLinear (float | np.ndarray) – Value in Linear scale

Returns

valueIndBm – Value in dBm.

Return type

float | np.ndarray

Examples

>>> linear2dBm(1000)
60.0
pyphysim.util.conversion.single_matrix_to_matrix_of_matrices(single_matrix: numpy.ndarray, nrows: Optional[numpy.ndarray] = None, ncols: Optional[numpy.ndarray] = None)numpy.ndarray[source]

Converts a single numpy array to a numpy array of numpy arrays.

For instance, a 6x6 numpy array may be converted to a 3x3 numpy array of 2x2 arrays.

Parameters
  • single_matrix (np.ndarray) – The single numpy array. This should be a 1D numpy array or a 2D numpy array.

  • nrows (np.ndarray, optional) – The number of rows of each submatrix (if single_matrix is 2D), or the number of elements in each subarray (if single_matrix is 1D).

  • ncols (np.ndarray, optional) – The number of rows of each submatrix. If single_matrix is a 1D array then ncols should be None (default)

Returns

The converted array (1D or 2D) of arrays (1D or 2D) as a 1D or 2D numpy array of arrays.

Return type

np.ndarray

Notes

The parameters ncols and nrows cannot both be equal to None.

Examples

>>> # Case where we have a single array
>>> single_array = np.array([2, 2, 4, 5, 6, 8, 8, 8, 8])
>>> sizes = np.array([2, 3, 4])
>>> m_of_ms = single_matrix_to_matrix_of_matrices(single_array, sizes)
>>> print(m_of_ms.size)
3
>>> print(m_of_ms[0])
[2 2]
>>> print(m_of_ms[1])
[4 5 6]
>>> print(m_of_ms[2])
[8 8 8 8]
>>>
>>> # Case where we have a matrix to break in packs of rows
>>> single_matrix = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
>>> rows = np.array([1, 2])
>>> multi_M =single_matrix_to_matrix_of_matrices(single_matrix, rows)
>>> print(multi_M[0])
[[1 1 1]]
>>> print(multi_M[1])
[[2 2 2]
 [3 3 3]]
>>> # Case where we have a matrix to break in packs of columns
>>> rows = None
>>> cols = np.array([1, 2])
>>> multi_M=single_matrix_to_matrix_of_matrices(single_matrix,                                                     rows, cols)
>>> print(multi_M[0])
[[1]
 [2]
 [3]]
>>> print(multi_M[1])
[[1 1]
 [2 2]
 [3 3]]
>>> # Case where we break into multiple matrices
>>> rows = np.array([2, 1])
>>> cols = np.array([1, 2])
>>> multi_M=single_matrix_to_matrix_of_matrices(single_matrix,                                                     rows, cols)
>>> print(multi_M[0, 0])
[[1]
 [2]]
>>> print(multi_M[0, 1])
[[1 1]
 [2 2]]

pyphysim.util.misc module

Module containing useful general functions that don’t belong to another module.

pyphysim.util.misc.calc_autocorr(x: numpy.ndarray)numpy.ndarray[source]

Calculates the (normalized) auto-correlation of an array x starting from lag 0.

Parameters

x (np.ndarray) – A 1D numpy array.

Returns

result – The normalized auto-correlation of x.

Return type

np.ndarray

Examples

>>> x = np.array([4, 2, 1, 3, 7, 3, 8])
>>> calc_autocorr(x)
array([ 1.   , -0.025,  0.15 , -0.175, -0.25 , -0.2  ,  0.   ])
pyphysim.util.misc.calc_confidence_interval(mean: float, std: float, n: int, P: float = 95.0) → Tuple[float, float][source]

Calculate the confidence interval that contains the true mean (of a normal random variable) with a certain probability P, given the measured mean, standard deviation std for number of samples n.

Only a few values are allowed for the probability P, which are: 50%, 60%, 70%, 80%, 90%, 95%, 98%, 99%, 99.5%, 99.8% and 99.9%.

Parameters
  • mean (float) – The measured mean value.

  • std (float) – The measured standard deviation.

  • n (int) – The number of samples used to measure the mean and standard deviation.

  • P (float) – The desired confidence (probability in %) that true value is inside the calculated interval.

Returns

A list with two float elements, the interval minimum and maximum values.

Return type

float, float

Notes

This function assumes that the estimated random variable is a normal variable.

pyphysim.util.misc.calc_decorrelation_matrix(cov_matrix: numpy.ndarray)numpy.ndarray[source]

Calculates the decorrelation matrix that can be applied to a data vector whose covariance matrix is cov_matrix so that the new vector covariance matrix is a diagonal matrix.

Parameters

cov_matrix (np.ndarray) – The covariance matrix of the original data that will be decorrelated. This must be a symmetric and positive semi-definite matrix

Returns

The decorrelation matrix \(\mtW_D\). If the original data is a vector \(\vtX\) it can be decorrelated with \(\mtW_D^T \vtX\).

Return type

np.ndarray

pyphysim.util.misc.calc_shannon_sum_capacity(sinrs: Union[numpy.ndarray, float])float[source]

Calculate the sum of the Shannon capacity of the values in sinrs

Parameters

sinrs (float | np.ndarray) – SINR values (in linear scale).

Returns

sum_capacity – Sum capacity.

Return type

float

Examples

>>> calc_shannon_sum_capacity(11.4)
3.6322682154995127
>>> calc_shannon_sum_capacity(20.3)
4.412781525338476
>>> sinrs_linear = np.array([11.4, 20.3])
>>> print(calc_shannon_sum_capacity(sinrs_linear))
8.045049740837989
pyphysim.util.misc.calc_unorm_autocorr(x: numpy.ndarray)numpy.ndarray[source]

Calculates the unormalized auto-correlation of an array x starting from lag 0.

Parameters

x (np.ndarray) – A 1D numpy array.

Returns

result – The unormalized auto-correlation of x.

Return type

np.ndarray

Examples

>>> x = np.array([4, 2, 1, 3, 7, 3, 8])
>>> calc_unorm_autocorr(x)
array([152,  79,  82,  53,  42,  28,  32])
pyphysim.util.misc.calc_whitening_matrix(cov_matrix: numpy.ndarray)numpy.ndarray[source]

Calculates the whitening matrix that can be applied to a data vector whose covariance matrix is cov_matrix so that the new vector covariance matrix is an identity matrix

Parameters

cov_matrix (np.ndarray) – The covariance matrix of the original data that will be decorrelated. This must be a symmetric and positive semi-definite matrix

Returns

whitening_matrix – The whitening matrix \(\mtW_W\). If the original data is a vector \($\vtX$\) it can be whitened with \(\mtW_W^H \vtX\).

Return type

np.ndarray

Notes

The returned whitening_matrix matrix will make the covariance of the filtered data an identity matrix. If you only need the the covariance matrix of the filtered data to be a diagonal matrix (not necessarily an identity matrix) what you want to calculate is the “decorrelation matrix”. See the calc_decorrelation_matrix() function for that.

pyphysim.util.misc.count_bit_errors(first: IntOrIntArray, second: IntOrIntArray, axis: Optional[Any] = None) → IntOrIntArray[source]

Compare first and second and count the number of equivalent bit errors.

The two arguments are assumed to have the index of transmitted and decoded symbols. The count_bit_errors function will compare each element in first with the corresponding element in second, determine how many bits changed and then return the total number of changes bits. For instance, if we compare the numbers 3 and 0, we see that 2 bits have changed, since 3 corresponds to ‘11’, while 0 corresponds to ‘00’.

Parameters
  • first (int | np.ndarray) – The decoded symbols.

  • second (int | np.ndarray) – The transmitted symbols.

  • axis (int, optional) – Since first and second can be numpy arrays, when axis is not provided (that is, it is None) then the total number of bit errors of all the elements of the ‘difference array’ is returned. If axis is provided, then an array of bit errors is returned where the number of bit errors summed along the provided axis is returned.

Returns

bit_errors – The total number of bit errors.

Return type

int | np.ndarray

Examples

>>> first = np.array([[2, 3, 3, 0], [1, 3, 1, 2]])
>>> second = np.array([[0, 3, 2, 0], [2, 0, 1, 2]])
>>> # The number of changed bits in each element is equal to
>>> # array([1, 0, 1, 0, 2, 2, 0])
>>> count_bit_errors(first, second)
6
>>> count_bit_errors(first, second, 0)
array([3, 2, 1, 0])
>>> count_bit_errors(first, second, 1)
array([2, 4])
pyphysim.util.misc.equal_dicts(a: Dict[Any, Any], b: Dict[Any, Any], ignore_keys: List[Any])bool[source]

Test if two dictionaries are equal ignoring certain keys.

Parameters
  • a (dict) – The first dictionary

  • b (dict) – The second dictionary

  • ignore_keys (list) – A list or tuple with the keys to be ignored.

pyphysim.util.misc.get_mixed_range_representation(array: numpy.ndarray, filename_mode: bool = False)str[source]

Get the “range representation” of a numpy array. This is similar to get_range_representation, but it no pure range representation is possible it will try to represent as least part of the array as range representations.

Suppose you have the array n = [1, 2, 3, 5, 10, 15, 20, 25, 30, 35, 40, 100]

Except for the 3 initial and the final elements, this array is an arithmetic progression with step equal to 5. Lets keep the 3 initial and the final values and represent the other values as a range representation.

Parameters
  • array (np.ndarray) – The array to be represented as a range expression.

  • filename_mode (bool, optional) – If True, the returned representation will be more suitable to be used as part of a file-name. That is instead of “5:5:40” the string “5_(5)_40” would be returned.

Returns

expr – A string expression representing array.

Return type

str

pyphysim.util.misc.get_principal_component_matrix(A: numpy.ndarray, num_components: int)numpy.ndarray[source]

Returns a matrix without the “principal components” of A.

This function returns a new matrix formed by the most significative components of A.

Parameters
  • A (np.ndarray) – The original matrix, which is a 2D numpy matrix.

  • num_components (int) – Number of components to be kept.

Returns

out – The new matrix with the dead dimensions removed.

Return type

np.ndarray

Notes

You might want to normalize the returned matrix out after calling get_principal_component_matrix to have the same norm as the original matrix A.

pyphysim.util.misc.get_range_representation(array: numpy.ndarray, filename_mode: bool = False) → Optional[str][source]

Get the “range representation” of a numpy array consisting of a arithmetic progression. If no valid range representation exists, return None.

Suppose you have the array n = [5, 10, 15, 20, 25, 30, 35, 40] This array is an arithmetic progression with step equal to 5 and can be represented as “5:5:40”, which is exactly what get_range_representation will return for such array.

Parameters
  • array (np.ndarray) – The array to be represented as a range expression.

  • filename_mode (bool, optional) – If True, the returned representation will be more suitable to be used as part of a file-name. That is instead of “5:5:40” the string “5_(5)_40” would be returned.

Returns

expr – A string expression representing array.

Return type

str

pyphysim.util.misc.gmd(U: numpy.ndarray, S: numpy.ndarray, V_H: numpy.ndarray, tol: float = 0.0) → Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray][source]

Perform the Geometric Mean Decomposition of a matrix A, whose SVD is given by [U, S, V_H] = np.linalg.svd(A).

The Geometric Mean Decomposition (GMD) is described in paper “Joint Transceiver Design for MIMO Communications Using Geometric Mean Decomposition.”

Parameters
  • U (np.ndarray) – First matrix obtained from the SVD decomposition of the original matrix you want to decompose.

  • S (np.ndarray) – Second matrix obtained from the SVD decomposition of the original matrix you want to decompose.

  • V_H (np.ndarray) – Third matrix obtained from the SVD decomposition of the original matrix you want to decompose.

  • tol (float) – The tolerance.

Returns

The three matrices Q, R and P such that A = QRP^H, R is an upper triangular matrix and Q and P are unitary matrices.

Return type

(np.ndarray,np.ndarray,np.ndarray)

pyphysim.util.misc.int2bits(n: int)int[source]

Calculates the number of bits needed to represent an integer n.

Parameters

n (int) – The integer number.

Returns

num_bits – The number of bits required to represent the number n.

Return type

int

Examples

>>> list(map(int2bits, range(0,19)))
[1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5]
pyphysim.util.misc.least_right_singular_vectors(A: numpy.ndarray, n: int) → Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray][source]

Return the three matrices. The first one is formed by the n least significative right singular vectors of A, the second one is formed by the remaining right singular vectors of A and the third one has the singular values of the singular vectors of the second matrix (the most significative ones).

Parameters
  • A (np.ndarray) – A 2D numpy array.

  • n (int) – An integer between 0 and the number of columns of A.

Returns

The tree matrices V0, V1 and S.

The matrix V0 has the right singular vectors corresponding to the n least significant singular values.

The matrix V1 has the remaining right singular vectors.

The matrix S has the singular values corresponding to the remaining singular vectors V1.

Return type

np.ndarray, np.ndarray, np.ndarray

Notes

Because of the sort operation, if you call least_right_singular_vectors(A, ncols_of_A) you will get all the right singular vectors of A with the column order reversed.

Examples

>>> A = np.array([1,2,3,6,5,4,2,2,1])
>>> A.shape = (3,3)
>>> (min_Vs, remaining_Vs, S) = least_right_singular_vectors(A,1)
>>> min_Vs
array([[-0.4474985 ],
       [ 0.81116484],
       [-0.3765059 ]])
>>> remaining_Vs
array([[-0.62341491, -0.64116998],
       [ 0.01889071, -0.5845124 ],
       [ 0.78166296, -0.49723869]])
>>> S
array([1.88354706, 9.81370681])
pyphysim.util.misc.leig(A: numpy.ndarray, n: int) → Tuple[numpy.ndarray, numpy.ndarray][source]

Returns a matrix whose columns are the n least significant eigenvectors of A (eigenvectors corresponding to the n dominant eigenvalues).

Parameters
  • A (np.ndarray) – A symmetric matrix (bi-dimensional numpy array)

  • n (int) – Number of desired least significant eigenvectors.

Returns

A list with two elements where the first element is a 2D numpy array with the desired eigenvectors, while the second element is a 1D numpy array with the corresponding eigenvalues.

Return type

np.ndarray,np.ndarray

Notes

A must be a symmetric matrix so that its eigenvalues are real and positive.

Raises

ValueError – If n is greater than the number of columns of A.

Examples

>>> A = np.random.randn(3,3) + 1j*np.random.randn(3,3)
>>> V, D = peig(A, 1)
pyphysim.util.misc.level2bits(n: int)int[source]

Calculates the number of bits needed to represent n different values.

Parameters

n (int) – Number of different levels.

Returns

num_bits – Number of bits required to represent n levels.

Return type

int

Examples

>>> list(map(level2bits,range(1,20)))
[1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5]
pyphysim.util.misc.peig(A: numpy.ndarray, n: int) → Tuple[numpy.ndarray, numpy.ndarray][source]

Returns a matrix whose columns are the n dominant eigenvectors of A (eigenvectors corresponding to the n dominant eigenvalues).

Parameters
  • A (np.ndarray) – A symmetric matrix (bi-dimensional numpy array).

  • n (int) – Number of desired dominant eigenvectors.

Returns

A list with two elements where the first element is a 2D numpy array with the desired eigenvectors, while the second element is a 1D numpy array with the corresponding eigenvalues.

Return type

np.ndarray, np.ndarray

Notes

A must be a symmetric matrix so that its eigenvalues are real and positive.

Raises

ValueError – If n is greater than the number of columns of A.

Examples

>>> A = np.random.randn(3,3) + 1j*np.random.randn(3,3)
>>> V, D = peig(A, 1)
pyphysim.util.misc.pretty_time(time_in_seconds: float)str[source]

Return the time in a more friendly way.

Parameters

time_in_seconds (float) – Time in seconds.

Returns

time_string – Pretty time representation as a string.

Return type

str

Examples

>>> pretty_time(30)
'30.00s'
>>> pretty_time(76)
'1m:16s'
>>> pretty_time(4343)
'1h:12m:23s'
pyphysim.util.misc.qfunc(x: float)float[source]

Calculates the ‘q’ function of x.

Parameters

x (float) – The value to apply the Q function.

Returns

result – Qfunc(x)

Return type

float

Examples

>>> qfunc(0.0)
0.5
>>> round(qfunc(1.0), 9)
0.158655254
>>> round(qfunc(3.0), 9)
0.001349898
pyphysim.util.misc.randn_c(*args: int)numpy.ndarray[source]

Generates a random circularly complex gaussian matrix.

Parameters

*args (any) – Variable number of arguments (int values) specifying the dimensions of the returned array. This is directly passed to the numpy.random.randn function.

Returns

result – A random N-dimensional numpy array (complex dtype) where the N is equal to the number of parameters passed to randn_c.

Return type

np.ndarray

Examples

>>> a = randn_c(4,3)
>>> a.shape
(4, 3)
>>> a.dtype
dtype('complex128')
pyphysim.util.misc.randn_c_RS(RS: numpy.random.mtrand.RandomState, *args: int)numpy.ndarray[source]

Generates a random circularly complex gaussian matrix.

This is essentially the same as the the randn_c function. The only difference is that the randn_c function uses the global RandomState object in numpy, while randn_c_RS use the provided RandomState object. This allow us greater control.

Parameters
  • RS (np.random.RandomState) – The RandomState object used to generate the random values.

  • *args (any) – Variable number of arguments specifying the dimensions of the returned array. This is directly passed to the numpy.random.randn function.

Returns

result – A random N-dimensional numpy array (complex dtype) where the N is equal to the number of parameters passed to randn_c.

Return type

np.ndarray

pyphysim.util.misc.replace_dict_values(name: str, dictionary: Dict[str, str], filename_mode: bool = False)str[source]

Perform the replacements in name with the value of dictionary[name].

See the usage example below:

>>> name = "results_snr_{snr}_param_a_{param_a}"
>>> replacements = {'snr': np.array([0,5,10,15,20]), 'param_a': 'something'}
>>> replace_dict_values(name, replacements)
'results_snr_[0:5:20]_param_a_something'

Note that some small changes are performed in the dictionary prior to the replacement. More specifically, modifications such as changing a numpy array to a more compact representation (when possible). This is done by converting the numpy arrays with the get_mixed_range_representation function.

If the string is going to be used as a filename, pass True to filename_mode as in the example below

>>> replace_dict_values(name, replacements, True)
'results_snr_[0_(5)_20]_param_a_something'
Parameters
  • name (str) – The name fo be formatted.

  • dictionary (dict) – The dictionary with the values to be replaced in name.

  • filename_mode (bool, optional) – Extra parameter passed to the get_mixed_range_representation function. If True, the returned representation will be more suitable to be used as part of a file-name. That is instead of “5:5:40” the string “5_(5)_40” would be used.

Returns

new_name – The value of name after the replacements in dictionary.

Return type

str

Examples

>>> name = "something {value1} - {value2} something else {value3}"
>>> dictionary = {'value1':'bla bla',                       'value2':np.array([5, 10, 15, 20, 25, 30]),                       'value3': 76}
>>> replace_dict_values(name, dictionary, True)
'something bla bla - [5_(5)_30] something else 76'
pyphysim.util.misc.update_inv_sum_diag(invA: numpy.ndarray, diagonal: numpy.ndarray)numpy.ndarray[source]

Calculates the inverse of a matrix \((A + D)\), where \(D\) is a diagonal matrix, given the inverse of :math`A` and the diagonal of \(D\).

This calculation is performed using the Sherman-Morrison formula, given my

\[(A+uv^T)^{-1} = A^{-1} - {A^{-1}uv^T A^{-1} \over 1 + v^T A^{-1}u},\]

where \(u\) and \(v\) are vectors.

Parameters
  • invA (np.ndarray) – A 2D numpy array.

  • diagonal (np.ndarray) – A 1D numpy array with the elements in the diagonal of \(D\).

Returns

new_inv – The inverse of \(A+D\).

Return type

np.ndarray

pyphysim.util.misc.xor(a: int, b: int)int[source]

Calculates the xor operation between a and b.

In python this is performed with a^b. However, sage changed the “^” operator. This xor function was created so that it can be used in either sage or in regular python.

Parameters
  • a (int) – First number.

  • b (int) – Second number.

Returns

The result of the xor operation between a and b.

Return type

int

Examples

>>> xor(3,7)
4
>>> xor(15,6)
9

pyphysim.util.serialize module

Module containing function related to serialization.

class pyphysim.util.serialize.JsonSerializable[source]

Bases: object

Base class for classes you want to be JSON serializable (convert to/from JSON).

You can call the methods to_json and from_json methods (the later is a staticmethod).

Note that a subclass must implement the _to_dict and _from_dict methods.

static _from_dict(d: Dict[str, Any]) → Any[source]

Convert from a dictionary to an object.

Parameters

d (dict) – The dictionary representing the object.

Returns

The converted object.

Return type

Result

_to_dict() → Dict[str, Any][source]

Convert the object to a dictionary representation.

Returns

The dictionary representation of the object.

Return type

dict

classmethod from_dict(d: Dict[str, Any]) → Any[source]

Convert from a dictionary to an object.

Parameters

d (dict) – The dictionary representing the Result.

Returns

The converted object.

Return type

Result

classmethod from_json(data: Any) → Any[source]

Convert a JSON representation of the object to an actual object.

Parameters

data (str) – The JSON representation of the object.

Returns

The actual object

Return type

any

to_dict() → Dict[str, Any][source]

Convert the object to a dictionary representation.

Returns

The dictionary representation of the object.

Return type

dict

to_json() → Any[source]

Convert the object to JSON.

Returns

JSON representation of the object.

Return type

str

class pyphysim.util.serialize.NumpyOrSetEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

JSON encoder for numpy arrays.

Pass this class to json.dumps when converting a dictionary to json so that any field which with a numpy array as value will be properly converted.

This encoder will also handle numpy scalars and the native python set types.

When you need to convert the json representation back, use the json_numpy_or_set_obj_hook function.

default(obj: Union[numpy.ndarray, numpy.int32, numpy.int64, numpy.float32, numpy.float64, numpy.float128, set]) → Any[source]

If input object is an ndarray it will be converted into a dict holding data, dtype, _is_numpy_array and shape.

Parameters

obj (Serializable) –

Returns

Return type

Serialized Data

pyphysim.util.serialize.json_numpy_or_set_obj_hook(dct: Dict[str, Any]) → Union[numpy.ndarray, numpy.int32, numpy.int64, numpy.float32, numpy.float64, numpy.float128, set][source]

Decodes a previously encoded numpy array.

Parameters

dct (dict) – The JSON encoded numpy array.

Returns

The decoded numpy array or None if the encoded json data was not an encoded numpy array.

Return type

np.ndarray | set | dict, optional

Module contents

Package with several utility modules and classes.

This includes the SimulationRunner class.