Utils

This module contains useful methods and general settings.

keysight.qcs.utils.AliasMap

Holds a map from aliases to objects.

keysight.qcs.utils.CsWrapper

A common base class for types that act as wrappers for C# objects.

keysight.qcs.utils.Plotter

keysight.qcs.utils.Serializable

An abstract base class for all serializable classes.

keysight.qcs.utils.auto_base

Returns the smallest positive integer \(d\) such that \(x=d^n\) for some positive integer \(n\).

keysight.qcs.utils.find_parameters

Finds all free parameters inside the text description of a function using exception handling.

keysight.qcs.utils.get_dim

Returns the default subsystem dimension or the provided one if it is valid.

keysight.qcs.utils.get_plotly_template

Returns the template for the figures generated by plotly.

keysight.qcs.utils.get_rng

Returns the default NumPy generator for producing random values.

keysight.qcs.utils.int_base

Returns the integer solution to base ** n == x or None if no exact solution exists to numerical precision.

keysight.qcs.utils.int_log

Returns the integer logarithm of x in the given base or None if no exact solution exists to numerical precision.

keysight.qcs.utils.load

Load objects from a json file.

keysight.qcs.utils.mat_to_yaml

Turns a numpy array into a list of lists of formatted strings or floats, the conversions are chosen for the appearance when converted to YAML.

keysight.qcs.utils.parse_func

Creates a Python function from a string containing numbers, variables, and standard math functions.

keysight.qcs.utils.parse_list

Parses a nested list of strings containing numbers and standard math functions.

keysight.qcs.utils.prime_base

Returns a prime less than 20 such that the argument is an integer power of the prime or None if no such prime exists.

keysight.qcs.utils.reset

Resets all settings to their original values.

keysight.qcs.utils.safe_str

Returns a sanitized string with redundant quotes removed and raises an error if a protected Python keyword is encountered.

keysight.qcs.utils.save

Save an object to a json file, preserving Python references.

keysight.qcs.utils.get_dim

Returns the default subsystem dimension or the provided one if it is valid.

keysight.qcs.utils.set_plotly_template

Sets the template for the figures generated by plotly.

keysight.qcs.utils.set_rng

Sets the NumPy generator for producing random values.

keysight.qcs.utils.str_list

Returns a string representation of a list truncated to a specified number of elements.

keysight.qcs.utils.to_tuple

Converts an input to a tuple of a fixed type.

keysight.qcs.utils.str_list(lst: Sequence[any], trunc=3, add_brackets=True) str

Returns a string representation of a list truncated to a specified number of elements.

Parameters:
  • lst – The list to return the string representation of.

  • trunc – The number of elements to include in the string representation.

  • add_brackets – Whether to surround the string with brackets. Default is true.

keysight.qcs.utils.to_tuple(param: any, t: type) tuple

Converts an input to a tuple of a fixed type.

from keysight.qcs import utils as qcsu

assert qcsu.to_tuple(None, int) == tuple()
assert qcsu.to_tuple(0, int) == (0,)
assert qcsu.to_tuple((0, 1), int) == (0, 1)
Parameters:
  • param – The iterable to be converted.

  • t – The expected type.

Raises:

TypeError – If param is not None and is or contains any objects that are not instances of type t.

Cs Wrapper

class keysight.qcs.utils.CsWrapper

A common base class for types that act as wrappers for C# objects.

reference_equals(other: any) bool

Whether this object points to the same underlying C# object.

Parameters:

other – The object to check.

Discrete Bases

A collection of methods to handle working with discrete bases.

keysight.qcs.utils.auto_base(x: int) int

Returns the smallest positive integer \(d\) such that \(x=d^n\) for some positive integer \(n\). This is always possible due to the trivial choice \(d=x\) and \(n=1\). This function can be used to figure out a suitable subsystem dimension when only the total dimension of a composite system is known. See also int_base() and prime_base().

import keysight.qcs as qcs

assert qcs.utils.auto_base(512) == 2
assert qcs.utils.auto_base(36) == 6
assert qcs.utils.auto_base(21) == 21
Parameters:

x – A positive integer.

keysight.qcs.utils.get_dim(dim: int | None = None) int

Returns the default subsystem dimension or the provided one if it is valid.

Parameters:

dim – If None, return the default subsystem dimension, or the provided integer if it is valid.

Raises:

ValueError – If dim is not an integer greater than 1.

keysight.qcs.utils.int_base(x: int, n: int) int | None

Returns the integer solution to base ** n == x or None if no exact solution exists to numerical precision. See also prime_base(), auto_base(), and int_log().

import keysight.qcs as qcs

assert qcs.utils.int_base(16, 4) == 2
assert qcs.utils.int_base(9, 2) == 3
assert qcs.utils.int_base(12, 2) is None
Parameters:
  • x – The positive integer to find the base of.

  • n – A positive integer; the power to which the base should be raised to get x.

keysight.qcs.utils.int_log(x: int, base: int) int | None

Returns the integer logarithm of x in the given base or None if no exact solution exists to numerical precision. See also int_base().

import keysight.qcs as qcs

assert qcs.utils.int_log(16, 2) == 4
assert qcs.utils.int_log(16, 4) == 2
assert qcs.utils.int_log(16, 3) is None
Parameters:
  • x – The positive integer to compute the logarithm of.

  • base – The base of the logarithm.

keysight.qcs.utils.prime_base(n: int) int | None

Returns a prime less than 20 such that the argument is an integer power of the prime or None if no such prime exists. See also int_base() and auto_base().

Parameters:

n – The number to check.

keysight.qcs.utils.set_dim(dim: int) None

Sets the default subsystem dimension for several constructors.

Parameters:

dim – The dimension to set the default value to.

Raises:

ValueError – If dim is not an integer greater than 1.

AliasMap

class keysight.qcs.utils.AliasMap(**kwargs: dict[str, any])

Holds a map from aliases to objects.

Parameters:

kwargs – a map from aliases to objects.

property aliases: set[str]

Returns the aliases in this alias map.

add_alias(key: str, val: any) None

Adds an object to this alias map with a given alias.

Parameters:
  • key – The alias.

  • val – The object to add.

Raises:

AttributeError – If key is already an attribute of this alias map.

add_aliases(**kwargs: dict[str, any]) None

Adds objects to this alias map with given aliases.

Parameters:

kwargs – The map from names to objects.

get_from_type(cls: type | tuple[type, ...]) Iterable[any]

Yields every instance of the specified class or classes and subclasses thereof.

Parameters:

cls – The class or classes to get all instances of.

Parsing

A collection of methods to handle parsing.

keysight.qcs.utils.find_parameters(func_str: str) list[str]

Finds all free parameters inside the text description of a function using exception handling.

from keysight.qcs.utils import find_parameters

params = find_parameters("sin(x) + phi / 2 + theta")
assert set(params) == {"x", "phi", "theta"}
Parameters:

func_str – A string describing the function.

Raises:

ValueError – If func_str contains a protected Python keyword.

keysight.qcs.utils.mat_to_yaml(mat: ArrayLike) list[list[str]]

Turns a numpy array into a list of lists of formatted strings or floats, the conversions are chosen for the appearance when converted to YAML.

import numpy as np
from keysight.qcs.utils import mat_to_yaml

output = mat_to_yaml(np.array([[1, 1j]]))
assert output == [["(1+0j)", "1j"]]
Parameters:

mat – A numpy array to convert into a list of lists of formatted strings.

keysight.qcs.utils.parse_func(func_str: str) callable

Creates a Python function from a string containing numbers, variables, and standard math functions.

import numpy as np
from keysight.qcs.utils import parse_func

f = parse_func("5*sin(x) + y")
assert np.isclose(f(x=np.pi, y=1), 1.0)

Note

Parsing functions adds an overhead relative to directly calling numpy functions.

Parameters:

func_str – A string describing the function to be created.

Raises:

ValueError – If func_str contains a protected Python keyword.

keysight.qcs.utils.parse_list(list_str: str) array

Parses a nested list of strings containing numbers and standard math functions.

from keysight.qcs.utils import parse_list

assert parse_list(["1/sqrt(2)"]) == [1 / np.sqrt(2)]
Parameters:

list_str – A string describing the matrix to be created.

Raises:

ValueError – If list_str contains a protected Python keyword.

keysight.qcs.utils.safe_str(func_str: str) str

Returns a sanitized string with redundant quotes removed and raises an error if a protected Python keyword is encountered.

from keysight.qcs.utils import safe_str

assert safe_str("'5 * 2 + sin(7)'") == "5 * 2 + sin(7)"
Parameters:

func_str – A string potentially containing redundant quotes or Python protected keywords.

Raises:

ValueError – If func_str contains a protected Python keyword.

Plotter

class keysight.qcs.utils.Plotter
static subplot(n_plots: int, n_columns: int = 1, traces: None | Iterable[go.Figure] = None, subplot_titles: tuple = ()) go.Figure

Returns a plotly figure containing at least n_plots subplots. The traces are created using given estimates. If traces are given, those traces are added.

Parameters:
  • n_plots – How many subfigures there will nominally be.

  • n_columns – The number of columns in the subplot.

  • traces – An iterable containing tuples of the form (tr, row, col), where tr is a plotly trace that will be added to the figure, and row and col are the row and column indices of the subplot to which this trace will be added. Traces can be repeated in this iterable to allow for repeated subfigures. Default is None.

  • subplot_titles – The titles of the individual subplots.

Returns:

A plotly figure.

Raises:

ValueError – If n_plots is 0.

Serialization

class keysight.qcs.utils.Serializable

An abstract base class for all serializable classes.

The following numeric types are supported.

utils.SUPPORTED_DTYPES = (<class 'complex'>, <class 'float'>)

Numeric types are cast to a built in numeric type specified by DTYPE_COERCIONS.

utils.DTYPE_COERCIONS = {<class 'complex'>: <class 'complex'>, <class 'float'>: <class 'float'>, <class 'int'>: <class 'float'>, dtype('complex64'): <class 'complex'>, dtype('complex128'): <class 'complex'>, dtype('float16'): <class 'float'>, dtype('float32'): <class 'float'>, dtype('float64'): <class 'float'>, dtype('int8'): <class 'float'>, dtype('int16'): <class 'float'>, dtype('int32'): <class 'float'>, dtype('int64'): <class 'float'>}

To load or save, use:

keysight.qcs.utils.load(filename: Path | str | Serializable) any

Load objects from a json file.

If the object is already loaded, it will simply be returned.

Parameters:

filename – The name of the json file to load from.

keysight.qcs.utils.save(obj: any, filename: Path | str | None = None) None

Save an object to a json file, preserving Python references.

Parameters:
  • obj – The object to save.

  • filename – The name of the file to save to. Can be set to None for objects with a save_path attribute.

Raises:

ValueError – If filename is None and the object to be saved does not have a save_path and name attribute.

Settings

A collection of methods to get and set settings. These settings are not persistent between Python sessions.

keysight.qcs.utils.reset()

Resets all settings to their original values.

keysight.qcs.utils.set_rng(rng_or_seed: Generator | int)

Sets the NumPy generator for producing random values.

Parameters:

rng_or_seed – A numpy.random.Generator() object, or a seed to create one using :py:func`numpy.random.default_rng`.

keysight.qcs.utils.get_rng() Generator

Returns the default NumPy generator for producing random values.

keysight.qcs.utils.set_plotly_template(template: Template)

Sets the template for the figures generated by plotly.

Parameters:

template – A template for the plotly figures.

keysight.qcs.utils.get_plotly_template() Template

Returns the template for the figures generated by plotly.

On this page