inquanto.computables

inquanto.computables.atomic

Submodule for quantum computable expressions that interact directly with InQuanto Protocols.

class ExpectationValue(state, kernel)

Bases: ComputableNode[float]

Represents the expectation value of a Hermitian operator kernel with a state.

\(\langle \Psi | H | \Psi\rangle\)

Parameters:
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the state \(|\Psi \rangle\).

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: QubitOperator
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ExpectationValueBraDerivativeImag(state, kernel, symbols)

Bases: IExpectationValueDerivative

Represents the imaginary part of the bra derivatives of an expectation value of a Hermitian operator.

\(\Im \langle\partial_{\theta} \Psi(\theta) | H | \Psi(\theta)\rangle\)

Parameters:
  • state (GeneralAnsatz) – Ansatz state \(|\Psi(\theta)\rangle\).

  • kernel (QubitOperator) – Qubit operator kernel \(H\).

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the ansatz state.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: QubitOperator
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
symbols: Set[Symbol]
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ExpectationValueBraDerivativeReal(state, kernel, symbols)

Bases: IExpectationValueDerivative

Represents the real part of the bra derivatives of an expectation value of a Hermitian operator.

\(\Re \langle \partial_{\theta} \Psi(\theta) | H | \Psi(\theta)\rangle\)

Parameters:
  • state (GeneralAnsatz) – Ansatz state \(|\Psi(\theta)\rangle\).

  • kernel (QubitOperator) – Qubit operator kernel \(H\).

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the ansatz state.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: QubitOperator
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
symbols: Set[Symbol]
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ExpectationValueDerivative(state, kernel, symbols)

Bases: IExpectationValueDerivative

Represents the derivatives of the expectation value of a Hermitian operator.

\(\partial_{\theta} \langle \Psi(\theta) | H | \Psi(\theta) \rangle\)

Parameters:
  • state (GeneralAnsatz) – Ansatz state \(|\Psi(\theta)\rangle\).

  • kernel (QubitOperator) – Qubit operator kernel \(H\).

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the ansatz state.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: QubitOperator
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
symbols: Set[Symbol]
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ExpectationValueKetDerivativeImag(state, kernel, symbols)

Bases: IExpectationValueDerivative

Represents the imaginary part of the ket derivatives of an expectation value of a Hermitian operator.

\(\Im \langle\Psi(\theta) | H | \partial_{\theta} \Psi(\theta)\rangle\)

Parameters:
  • state (GeneralAnsatz) – Ansatz state \(|\Psi(\theta)\rangle\).

  • kernel (QubitOperator) – Qubit operator kernel \(H\).

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the ansatz state.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: QubitOperator
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
symbols: Set[Symbol]
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ExpectationValueKetDerivativeReal(state, kernel, symbols)

Bases: IExpectationValueDerivative

Represents the real part of the ket derivatives of an expectation value of a Hermitian operator.

\(\Re \langle\Psi(\theta) | H | \partial_{\theta} \Psi(\theta)\rangle\)

Parameters:
  • state (GeneralAnsatz) – Ansatz state \(|\Psi(\theta)\rangle\).

  • kernel (QubitOperator) – Qubit operator kernel \(H\).

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the ansatz state.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: QubitOperator
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
symbols: Set[Symbol]
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ExpectationValueNonHermitian(state, kernel)

Bases: ComputableNode[complex]

Represents the expectation value of a non-Hermitian operator kernel with a state.

\(\langle \Psi | H | \Psi\rangle\)

Parameters:
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the state \(|\Psi \rangle\).

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: QubitOperator
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class MetricTensorImag(state, symbols)

Bases: IMetricTensor

Represents the imaginary part of the metric tensor.

Calculates: \(\Im \langle\partial_{\theta_i} \Psi(\theta) | \partial_{\theta_j}\Psi(\theta)\rangle\) for all \(i, j\).

Parameters:
  • state (GeneralAnsatz) – Ansatz state \(|\Psi(\theta)\rangle\).

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the state.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
symbols: Set[Symbol]
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class MetricTensorReal(state, symbols)

Bases: IMetricTensor

Represents the real part of the metric tensor.

Calculates: \(\Re \langle\partial_{\theta_i} \Psi(\theta) | \partial_{\theta_j}\Psi(\theta)\rangle\) for all \(i, j\).

Parameters:
  • state (GeneralAnsatz) – Ansatz state \(|\Psi(\theta)\rangle\).

  • symbols (Set[Symbol]) – Symbols with respect to which the derivatives are computed.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in the state.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

state: GeneralAnsatz
symbols: Set[Symbol]
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class Overlap(bra_state, ket_state, kernel=<factory>)

Bases: IOverlap

Represents the overlap of two states with a Hermitian kernel operator.

\(\langle\Phi | H | \Psi\rangle\)

Parameters:
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

bra_state: GeneralAnsatz
children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in both bra and ket states.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: Union[QubitOperator, QubitOperatorString]
ket_state: GeneralAnsatz
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class OverlapImag(bra_state, ket_state, kernel=<factory>)

Bases: IOverlap

Represents the imaginary part of the overlap of two states with a Hermitian kernel operator.

\(\Im \langle\Phi | H | \Psi\rangle\)

Parameters:
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

bra_state: GeneralAnsatz
children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in both bra and ket states.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: Union[QubitOperator, QubitOperatorString]
ket_state: GeneralAnsatz
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class OverlapReal(bra_state, ket_state, kernel=<factory>)

Bases: IOverlap

Represents the real part of the overlap of two states with a Hermitian kernel operator.

\(\Re \langle\Phi | H | \Psi\rangle\)

Parameters:
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

bra_state: GeneralAnsatz
children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in both bra and ket states.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: Union[QubitOperator, QubitOperatorString]
ket_state: GeneralAnsatz
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class OverlapSquared(bra_state, ket_state, kernel=<factory>)

Bases: IOverlap

Represents the overlap squared of two states with a kernel operator.

\(| \langle \Phi | P | \Psi \rangle |^2\)

Note

The kernel operator must be a single Pauli string.

Parameters:
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

bra_state: GeneralAnsatz
children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluate this object using the provided evaluator function.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – A callable evaluator that is called on the instance.

Returns:

Union[TypeVar(EvaluatableType, bound= Evaluatable), TypeVar(EvaluatedType)] – The computed result.

free_symbols()

Returns free symbols in both bra and ket states.

Return type:

Set[Symbol]

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

kernel: Union[QubitOperator, QubitOperatorString]
ket_state: GeneralAnsatz
label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

inquanto.computables.primitive

Primitive objects for constructing quantum computable expressions.

class ComputableFunction(func, *args)

Bases: ComputableNode[EvaluatedType]

Class representing a function applied to computable nodes in the expression tree.

Parameters:
  • func (Callable[..., TypeVar(EvaluatedType)]) – Callable expression to be evaluated.

  • args (Any) – Computable nodes passed to callable func.

Example

>>> from inquanto.computables.primitive import ComputableInt
>>> add = ComputableFunction(lambda x, y: x + y, ComputableInt(3), ComputableInt(4))
>>> result = add.evaluate()
>>> result
7
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

args: Tuple[Any, ...]
children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Recursively evaluates the expression tree and returns the computed result.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Union[Evaluatable, Any]]], default: None) – Evaluator function passed to the evaluate() methods of the child computable nodes recursively.

Returns:

Union[ComputableFunction, TypeVar(EvaluatedType)] – The computed result of the expression tree.

free_symbols()

Returns the union of free symbols from all children.

Returns:

Set[Symbol] – A set containing the free symbols from all children.

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

func: Callable[..., TypeVar(EvaluatedType)]
is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ComputableInt(value)

Bases: ComputableNode[int]

Computable wrapper class for an int, mainly for demonstration purposes.

Parameters:

value (int) – Integer value.

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluates its value.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Any]], default: None)

Return type:

int

free_symbols()

Returns the union of free symbols from all children.

Returns:

Set[Symbol] – A set containing the free symbols from all children.

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

label: str = None
print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

value: int
walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ComputableList(iterable=(), /)

Bases: list, ComputableNode[List]

Class representing a list of items of any types in the computable expression tree.

Parameters:

iterable – An iterable which produces elements to initialize the list.

Example

>>> from inquanto.computables.primitive import ComputableInt
>>> k_list = ComputableList([ComputableInt(1), ComputableInt(2), 3, "foo"])
>>> k_list
[ComputableInt(value=1), ComputableInt(value=2), 3, 'foo']
>>> len(k_list)
4
>>> k_list.evaluate()
[1, 2, 3, 'foo']
add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

append(object, /)

Append object to the end of the list.

children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

clear()

Remove all items from list.

copy()

Return a shallow copy of the list.

count(value, /)

Return number of occurrences of value.

default_evaluate(parameters, protocol=None)

Evaluate the final results immediately for return.

If a protocol is not given it will attempt to use statevector backends from pytket-extensions. First, it will try the AerStateBackend from pytket-qiskit, and then the QulacsBackend from pytket-qulacs.

Parameters:
  • parameters (SymbolDict) – SymbolDict or dict to map symbols to values.

  • protocol (Optional[Any], default: None) – Optional protocol is assumed to be capable of measuring and evaluating the internal quantities to calculate the final value.

Returns:

Union[Evaluatable, Any] – Final value of the evaluatable object.

evaluate(evaluator=None)

Evaluates each item in the list and returns the computed results as a list.

If an item is a computable, its evaluate() method is called. Otherwise, the item itself is returned.

Parameters:

evaluator (Optional[Callable[[Evaluatable], Any]], default: None) – Callable passed to each item’s evaluate() method.

Returns:

Union[ComputableList, List] – The computed results of the items.

extend(iterable, /)

Extend list by appending elements from the iterable.

free_symbols()

Returns the union of free symbols from all children.

Returns:

Set[Symbol] – A set containing the free symbols from all children.

free_symbols_ordered()

Returns the free symbols in increasing lexicographic order as SymbolSet.

Returns:

SymbolSet – Ordered free symbols in object.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

insert(index, object, /)

Insert object before index.

is_leaf()

Check if the current computable node is a leaf (i.e., it has no children).

Returns:

boolTrue if the computable node is a leaf, False otherwise.

label: str = None
pop(index=-1, /)

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

print_tree()

Prints the nodes of the computable expression tree, with an indentation level proportional to their depth.

Return type:

None

remove(value, /)

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse()

Reverse IN PLACE.

sort(*, key=None, reverse=False)

Sort the list in ascending order and return None.

The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).

If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.

The reverse flag can be set to sort in descending order.

walk(depth=0)

Generator method to traverse the computable expression tree in a depth-first manner.

Parameters:

depth (int, default: 0) – The initial depth of the tree. Default is 0.

Yields:

A tuple containing the current computable node and its depth in the tree.

Return type:

Iterator[Tuple[ComputableNode, int]]

class ComputableNDArray(array_like: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], *args: Any, **kwargs: Any)

Bases: ndarray, ComputableNode[ndarray[Any, dtype[_ScalarType_co]]]

Class representing a multi-dimensional array of items in a computable expression tree.

This class dresses numpy ndarrays with Computable methods. It can contain computable items as objects, allowing computations to be deferred. It provides an interface to seamlessly integrate within a computational framework that uses Computable-based structures.

The array can be of any dimension, and its constructor signature is the same as a numpy array with the dtype set to object if a computable element is used. Supports all mathematical operations.

Parameters:
  • array_like – Initial data for the array. It can be a list, an already instantiated numpy array, or a list of Computable objects.

  • *args – Arguments passed to the numpy array constructor.

  • **kwargs – Key word arguments passed to the numpy array constructor, for example dtype=object

Example

>>> from inquanto.computables.primitive import ComputableInt
>>> qc_array = ComputableNDArray([ComputableInt(1), ComputableInt(2), ComputableInt(3), ComputableInt(4)], dtype=object)
>>> qc_array.evaluate()
array([1, 2, 3, 4], dtype=object)
>>> another_array = ComputableNDArray([ComputableInt(0), 1, ComputableInt(1), ComputableInt(0)])
>>> result = (qc_array + another_array)
>>> result.evaluate()
array([1, 3, 4, 4], dtype=object)

Note

The behavior of mathematical operations and functions on this class is determined by the behavior of the underlying numpy arrays. Computable items like ComputableInt will be evaluated when the evaluate() method is called.

T

View of the transposed array.

Same as self.transpose().

Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.T
array([[1, 3],
       [2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.T
array([1, 2, 3, 4])

See also

transpose

add_label(label, label_children=False)

Assign a label to the current computable.

Overwrites any existing label. Access a computable node’s label with label.

Parameters:
  • label (str) – Label string to be assigned to node. Overwrites any existing label.

  • label_children (bool, default: False) – If True, all child nodes of this computable are labeled with label. If False, children remain unlabeled.

Returns:

ComputableNode – Self.

all(axis=None, out=None, keepdims=False, *, where=True)

Returns True if all elements evaluate to True.

Refer to numpy.all for full documentation.

See also

numpy.all

equivalent function

any(axis=None, out=None, keepdims=False, *, where=True)

Returns True if any of the elements of a evaluate to True.

Refer to numpy.any for full documentation.

See also

numpy.any

equivalent function

argmax(axis=None, out=None, *, keepdims=False)

Return indices of the maximum values along the given axis.

Refer to numpy.argmax for full documentation.

See also

numpy.argmax

equivalent function

argmin(axis=None, out=None, *, keepdims=False)

Return indices of the minimum values along the given axis.

Refer to numpy.argmin for detailed documentation.

See also

numpy.argmin

equivalent function

argpartition(kth, axis=-1, kind='introselect', order=None)

Returns the indices that would partition this array.

Refer to numpy.argpartition for full documentation.

Added in version 1.8.0.

See also

numpy.argpartition

equivalent function

argsort(axis=-1, kind=None, order=None)

Returns the indices that would sort this array.

Refer to numpy.argsort for full documentation.

See also

numpy.argsort

equivalent function

astype(dtype, order='K', casting='unsafe', subok=True, copy=True)

Copy of the array, cast to a specified type.

Parameters:
  • dtype (str or dtype) – Typecode or data-type to which the array is cast.

  • order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.

  • casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) –

    Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.

    • ’no’ means the data types should not be cast at all.

    • ’equiv’ means only byte-order changes are allowed.

    • ’safe’ means only casts which can preserve values are allowed.

    • ’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.

    • ’unsafe’ means any data conversions may be done.

  • subok (bool, optional) – If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.

  • copy (bool, optional) – By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.

Returns:

arr_t (ndarray) – Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.

Notes

Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.

Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.

Raises:

ComplexWarning – When casting from complex to float or int. To avoid this, one should use a.real.astype(t).

Examples

>>> x = np.array([1, 2, 2.5])
>>> x
array([1. ,  2. ,  2.5])
>>> x.astype(int)
array([1, 2, 2])
base

Base object if memory is from some other object.

Examples

The base of an array that owns its memory is None:

>>> x = np.array([1,2,3,4])
>>> x.base is None
True

Slicing creates a view, whose memory is shared with x:

>>> y = x[2:]
>>> y.base is x
True
byteswap(inplace=False)

Swap the bytes of the array elements

Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.

Parameters:

inplace (bool, optional) – If True, swap bytes in-place, default is False.

Returns:

out (ndarray) – The byteswapped array. If inplace is True, this is a view to self.

Examples

>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> list(map(hex, A))
['0x1', '0x100', '0x2233']
>>> A.byteswap(inplace=True)
array([  256,     1, 13090], dtype=int16)
>>> list(map(hex, A))
['0x100', '0x1', '0x3322']

Arrays of byte-strings are not swapped

>>> A = np.array([b'ceg', b'fac'])
>>> A.byteswap()
array([b'ceg', b'fac'], dtype='|S3')
A.newbyteorder().byteswap() produces an array with the same values

but different representation in memory

>>> A = np.array([1, 2, 3])
>>> A.view(np.uint8)
array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
       0, 0], dtype=uint8)
>>> A.newbyteorder().byteswap(inplace=True)
array([1, 2, 3])
>>> A.view(np.uint8)
array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
       0, 3], dtype=uint8)
children()

Generator method that yields the child computable nodes of the current computable node.

Yields:

An iterator over the child computable nodes of the current computable node.

Return type:

Iterator[ComputableNode]

choose(choices, out=None, mode='raise')

Use an index array to construct a new array from a set of choices.

Refer to numpy.choose for full documentation.

See also

numpy.choose

equivalent function

clip(min=None, max=None, out=None, **kwargs)

Return an array whose values are limited to [min, max]. One of max or min must be given.

Refer to numpy.clip for full documentation.

See also

numpy.clip

equivalent function

compress(condition, axis=None, out=None)

Return selected slices of this array along given axis.

Refer to numpy.compress for full documentation.

See also

numpy.compress

equivalent function

conj()

Complex-conjugate all elements.

Refer to numpy.conjugate for full documentation.

See also

numpy.conjugate

equivalent function

conjugate()

Return the complex conjugate, element-wise.

Refer to numpy.conjugate for full documentation.

See also

numpy.conjugate

equivalent function

copy(order='C')

Return a copy of the array.

Parameters:

order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and numpy.copy() are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)

See also

numpy.copy

Similar function with different default behavior

numpy.copyto

Notes

This function is the preferred method for creating an array copy. The function numpy.copy() is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.

Examples

>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
       [0, 0, 0]])
>>> y
array([[1, 2, 3],
       [4, 5, 6]])
>>> y.flags['C_CONTIGUOUS']
True
ctypes