tensorcircuit.cons¶

Constants and setups

exception tensorcircuit.cons.NodesReturn(value_to_return: Any)[source]¶

Bases: Exception

Intentionally stop execution to return a value.

__init__(value_to_return: Any)[source]¶
add_note()¶

Exception.add_note(note) – add a note to the exception

args¶
with_traceback()¶

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class tensorcircuit.cons.OMEOptimizer(optimizer: Any | None = None)[source]¶

Bases: object

Adapt an omeco optimizer for tc.set_contractor("custom", ...).

omeco stays an optional dependency and is imported lazily only when this adapter is actually used.

Example:

>>> import omeco
>>> opt = omeco.TreeSA(ntrials=4, niters=8, betas=[0.1, 1.0, 10.0])
>>> tc.set_contractor("custom", optimizer=opt, preprocessing=True)
__init__(optimizer: Any | None = None)[source]¶
tensorcircuit.cons.contraction_info_decorator(algorithm: Callable[[...], Any]) Callable[[...], Any][source]¶

Decorator to add contraction information logging to an optimizer.

This decorator wraps an optimization algorithm and prints detailed information about the contraction cost (FLOPs, size, write) and path finding time.

Parameters:

algorithm (Callable[..., Any]) – The optimization algorithm to decorate.

Returns:

The decorated optimization algorithm.

Return type:

Callable[…, Any]

tensorcircuit.cons.contractor(nodes: ~typing.List[~typing.Any], *, optimizer: ~typing.Any = <function greedy>, memory_limit: int | None = None, output_edge_order: ~typing.List[~typing.Any] | None = None, ignore_edge_order: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: ~typing.Any) Any¶
tensorcircuit.cons.custom(nodes: List[Any], optimizer: Any, memory_limit: int | None = None, output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: Any) Any[source]¶
tensorcircuit.cons.custom_stateful(nodes: List[Any], optimizer: Any, memory_limit: int | None = None, opt_conf: Dict[str, Any] | None = None, output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False, use_primitives: bool | None = None, **kws: Any) Any[source]¶
tensorcircuit.cons.d2s(n: int, dl: List[Any]) List[Any][source]¶
tensorcircuit.cons.experimental_contractor(nodes: List[Any], output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False, local_steps: int = 2) Any[source]¶
tensorcircuit.cons.function_nodes_capture(func: Callable[[Any], Any]) Callable[[Any], Any][source]¶
tensorcircuit.cons.get_contractor(method: str | None = None, optimizer: Any | None = None, memory_limit: int | None = None, opt_conf: Dict[str, Any] | None = None, *, set_global: bool = False, contraction_info: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: Any) Callable[[...], Any]¶

To set runtime contractor of the tensornetwork for a better contraction path. For more information on the usage of contractor, please refer to independent tutorial.

Parameters:
  • method (Optional[str], optional) – “auto”, “greedy”, “branch”, “plain”, “tng”, “custom”, “custom_stateful”. defaults to None (“auto”)

  • optimizer (Optional[Any], optional) – Valid for “custom” or “custom_stateful” as method, defaults to None

  • memory_limit (Optional[int], optional) – It is not very useful, as memory_limit leads to branch contraction instead of greedy which is rather slow, defaults to None

Raises:
  • Exception – Tensornetwork version is too low to support some of the contractors.

  • ValueError – Unknown method options.

Returns:

The new tensornetwork with its contractor set.

Return type:

tn.Node

tensorcircuit.cons.get_dtype(dtype: str | None = None, *, set_global: bool = False) Tuple[str, str]¶

Set the global runtime numerical dtype of tensors.

Parameters:

dtype (Optional[str], optional) – “complex64”/”float32” or “complex128”/”float64”, defaults to None, which is equivalent to “complex64”.

Returns:

complex dtype str and the corresponding real dtype str

Return type:

Tuple[str, str]

tensorcircuit.cons.get_symbol(i: int) str[source]¶

Get the symbol corresponding to int i - runs through the usual 52 letters before resorting to unicode characters, starting at chr(192) and skipping surrogates. From cotengra codebase

tensorcircuit.cons.get_tn_info(nodes: ~typing.List[~tensornetwork.network_components.Node], *, algorithm: ~typing.Any = <function _identity>) Tuple[List[Tuple[int, int]], List[Node]]¶

import cotengra as ctg import opt_einsum as oem

sys.setrecursionlimit(10000) # for successfullt ctg parallel

opt = ctg.ReusableHyperOptimizer(

methods=[“greedy”, “kahypar”], parallel=True, minimize=”write”, max_time=30, max_repeats=4096, progbar=True,

) tc.set_contractor(“custom”, optimizer=opt, preprocessing=True) tc.set_contractor(“custom_stateful”, optimizer=oem.RandomGreedy, max_time=60, max_repeats=128, minimize=”size”) tc.set_contractor(“plain-experimental”, local_steps=3)

# hyper efficient contractor: though long computation time required, suitable for extra large circuit simulation opt = ctg.ReusableHyperOptimizer(

minimize=’combo’, max_repeats=1024, max_time=’equil:128’, optlib=’nevergrad’, progbar=True,

)

def opt_reconf(inputs, output, size, **kws):

tree = opt.search(inputs, output, size) tree_r = tree.subtree_reconfigure_forest(progbar=True, num_trees=10,

num_restarts=20, subtree_weight_what=(“size”, ))

return tree_r.get_path()

tc.set_contractor(“custom”, optimizer=opt_reconf)

tensorcircuit.cons.nodes_to_adj(ns: List[Any]) Any[source]¶
tensorcircuit.cons.plain_contractor(nodes: List[Any], output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False) Any[source]¶

The naive state-vector simulator contraction path.

Parameters:
  • nodes (List[Any]) – The list of tn.Node.

  • output_edge_order (Optional[List[Any]], optional) – The list of dangling node edges, defaults to be None.

Returns:

The tn.Node after contraction

Return type:

tn.Node

tensorcircuit.cons.runtime_backend(backend: str | None = None) Iterator[Any][source]¶

Context manager to set with-level runtime backend

Parameters:

backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”, defaults to None

Yield:

the backend object

Return type:

Iterator[Any]

tensorcircuit.cons.runtime_contractor(*confargs: Any, **confkws: Any) Iterator[Any][source]¶

Context manager to change with-levek contractor

Yield:

_description_

Return type:

Iterator[Any]

tensorcircuit.cons.runtime_dtype(dtype: str | None = None) Iterator[Tuple[str, str]][source]¶

Context manager to set with-level runtime dtype

Parameters:

dtype (Optional[str], optional) – “complex64” or “complex128”, defaults to None (“complex64”)

Yield:

complex dtype str and real dtype str

Return type:

Iterator[Tuple[str, str]]

tensorcircuit.cons.runtime_nodes_capture(key: str = 'nodes') Iterator[Any][source]¶
tensorcircuit.cons.set_backend(backend: str | None = None, set_global: bool = True) Any¶

To set the runtime backend of tensorcircuit.

Note: tc.set_backend and tc.cons.set_tensornetwork_backend are the same.

Example:

>>> tc.set_backend("numpy")
numpy_backend
>>> tc.gates.num_to_tensor(0.1)
array(0.1+0.j, dtype=complex64)
>>>
>>> tc.set_backend("tensorflow")
tensorflow_backend
>>> tc.gates.num_to_tensor(0.1)
<tf.Tensor: shape=(), dtype=complex64, numpy=(0.1+0j)>
>>>
>>> tc.set_backend("pytorch")
pytorch_backend
>>> tc.gates.num_to_tensor(0.1)
tensor(0.1000+0.j)
>>>
>>> tc.set_backend("jax")
jax_backend
>>> tc.gates.num_to_tensor(0.1)
DeviceArray(0.1+0.j, dtype=complex64)
Parameters:
  • backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”. defaults to None, which gives the same behavior as tensornetwork.backend_contextmanager.get_default_backend().

  • set_global (bool) – Whether the object should be set as global.

Returns:

The tc.backend object that with all registered universal functions.

Return type:

backend object

tensorcircuit.cons.set_contractor(method: str | None = None, optimizer: Any | None = None, memory_limit: int | None = None, opt_conf: Dict[str, Any] | None = None, set_global: bool = True, contraction_info: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: Any) Callable[[...], Any][source]¶

To set runtime contractor of the tensornetwork for a better contraction path. For more information on the usage of contractor, please refer to independent tutorial.

Parameters:
  • method (Optional[str], optional) – “auto”, “greedy”, “branch”, “plain”, “tng”, “custom”, “custom_stateful”. defaults to None (“auto”)

  • optimizer (Optional[Any], optional) – Valid for “custom” or “custom_stateful” as method, defaults to None

  • memory_limit (Optional[int], optional) – It is not very useful, as memory_limit leads to branch contraction instead of greedy which is rather slow, defaults to None

Raises:
  • Exception – Tensornetwork version is too low to support some of the contractors.

  • ValueError – Unknown method options.

Returns:

The new tensornetwork with its contractor set.

Return type:

tn.Node

tensorcircuit.cons.set_dtype(dtype: str | None = None, set_global: bool = True) Tuple[str, str][source]¶

Set the global runtime numerical dtype of tensors.

Parameters:

dtype (Optional[str], optional) – “complex64”/”float32” or “complex128”/”float64”, defaults to None, which is equivalent to “complex64”.

Returns:

complex dtype str and the corresponding real dtype str

Return type:

Tuple[str, str]

tensorcircuit.cons.set_function_backend(backend: str | None = None) Callable[[...], Any][source]¶

Function decorator to set function-level runtime backend

Parameters:

backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”, defaults to None

Returns:

Decorated function

Return type:

Callable[…, Any]

tensorcircuit.cons.set_function_contractor(*confargs: Any, **confkws: Any) Callable[[...], Any][source]¶

Function decorate to change function-level contractor

Returns:

_description_

Return type:

Callable[…, Any]

tensorcircuit.cons.set_function_dtype(dtype: str | None = None) Callable[[...], Any][source]¶

Function decorator to set function-level numerical dtype

Parameters:

dtype (Optional[str], optional) – “complex64” or “complex128”, defaults to None

Returns:

The decorated function

Return type:

Callable[…, Any]

tensorcircuit.cons.set_tensornetwork_backend(backend: str | None = None, set_global: bool = True) Any[source]¶

To set the runtime backend of tensorcircuit.

Note: tc.set_backend and tc.cons.set_tensornetwork_backend are the same.

Example:

>>> tc.set_backend("numpy")
numpy_backend
>>> tc.gates.num_to_tensor(0.1)
array(0.1+0.j, dtype=complex64)
>>>
>>> tc.set_backend("tensorflow")
tensorflow_backend
>>> tc.gates.num_to_tensor(0.1)
<tf.Tensor: shape=(), dtype=complex64, numpy=(0.1+0j)>
>>>
>>> tc.set_backend("pytorch")
pytorch_backend
>>> tc.gates.num_to_tensor(0.1)
tensor(0.1000+0.j)
>>>
>>> tc.set_backend("jax")
jax_backend
>>> tc.gates.num_to_tensor(0.1)
DeviceArray(0.1+0.j, dtype=complex64)
Parameters:
  • backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”. defaults to None, which gives the same behavior as tensornetwork.backend_contextmanager.get_default_backend().

  • set_global (bool) – Whether the object should be set as global.

Returns:

The tc.backend object that with all registered universal functions.

Return type:

backend object

tensorcircuit.cons.sorted_edges(edges: Iterator[Edge]) List[Edge][source]¶
tensorcircuit.cons.split_rules(max_singular_values: int | None = None, max_truncation_err: float | None = None, relative: bool = False) Any[source]¶

Obtain the direcionary of truncation rules

Parameters:
  • max_singular_values (int, optional) – The maximum number of singular values to keep.

  • max_truncation_err (float, optional) – The maximum allowed truncation error.

  • relative (bool, optional) – Multiply max_truncation_err with the largest singular value.

tensorcircuit.cons.tn_greedy_contractor(nodes: List[Any], output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False, max_branch: int = 1) Any[source]¶