Utils
This module contains useful methods and general settings.
Holds a map from aliases to objects. |
|
A common base class for types that act as wrappers for C# objects. |
|
An abstract base class for all serializable classes. |
|
Returns the smallest positive integer \(d\) such that \(x=d^n\) for some positive integer \(n\). |
|
Finds all free parameters inside the text description of a function using exception handling. |
|
Returns the default subsystem dimension or the provided one if it is valid. |
|
Returns the template for the figures generated by plotly. |
|
Returns the default NumPy generator for producing random values. |
|
Returns the integer solution to |
|
Returns the integer logarithm of |
|
Load objects from a json file. |
|
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. |
|
Creates a Python function from a string containing numbers, variables, and standard math functions. |
|
Parses a nested list of strings containing numbers and standard math functions. |
|
Returns a prime less than |
|
Resets all settings to their original values. |
|
Returns a sanitized string with redundant quotes removed and raises an error if a protected Python keyword is encountered. |
|
Save an object to a json file, preserving Python references. |
|
Returns the default subsystem dimension or the provided one if it is valid. |
|
Sets the template for the figures generated by plotly. |
|
Sets the NumPy generator for producing random values. |
|
Returns a string representation of a list truncated to a specified number of elements. |
|
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 notNone
and is or contains any objects that are not instances of typet
.
Cs Wrapper
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()
andprime_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 than1
.
- keysight.qcs.utils.int_base(x: int, n: int) int | None
Returns the integer solution to
base ** n == x
orNone
if no exact solution exists to numerical precision. See alsoprime_base()
,auto_base()
, andint_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 givenbase
orNone
if no exact solution exists to numerical precision. See alsoint_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 orNone
if no such prime exists. See alsoint_base()
andauto_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 than1
.
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: Union[None, Iterable[Figure]] = None, subplot_titles: tuple = ()) 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)
, wheretr
is a plotly trace that will be added to the figure, androw
andcol
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 isNone
.subplot_titles – The titles of the individual subplots.
- Returns:
A plotly figure.
- Raises:
ValueError – If
n_plots
is0
.
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: pathlib.Path | str | keysight.qcs.utils.serialization.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: Optional[Union[str, Path]] = 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 asave_path
attribute.- Raises:
ValueError – If
filename
isNone
and the object to be saved does not have asave_path
andname
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: collections.abc.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.