pygsti.io

pyGSTi Input/Output Python Package

Submodules

Package Contents

Classes

_NicelySerializable

The base class for all "nicely serializable" objects in pyGSTi.

_VerbosityPrinter

Class responsible for logging things to stdout or a file.

_Circuit

A quantum circuit.

_CircuitParser

Parser for text-format operation sequences

_DataSet

An association between Circuits and outcome counts, serving as the input data for many QCVV protocols.

_MultiDataSet

A collection of DataSets that hold data for the same circuits.

StdInputParser

Encapsulates a text parser for reading GST input files.

Functions

_deprecated_fn(replacement=None)

Decorator for deprecating a function.

load_dataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, ignore_zero_count_lines=True, with_times='auto', circuit_parse_cache=None, verbosity=1)

Deprecated!

read_dataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, ignore_zero_count_lines=True, with_times='auto', circuit_parse_cache=None, verbosity=1)

Load a DataSet from a file.

load_multidataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, verbosity=1)

Deprecated!

read_multidataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, verbosity=1)

Load a MultiDataSet from a file.

load_time_dependent_dataset(filename, cache=False, record_zero_counts=True)

Deprecated!

read_time_dependent_dataset(filename, cache=False, record_zero_counts=True)

Load time-dependent (time-stamped) data as a DataSet.

load_model(filename)

Load a Model from a file, formatted using the standard text-format for models.

load_circuit_dict(filename)

Load a circuit dictionary from a file, formatted using the standard text-format.

load_circuit_list(filename, read_raw_strings=False, line_labels='auto', num_lines=None)

Deprecated!

read_circuit_list(filename, read_raw_strings=False, line_labels='auto', num_lines=None)

Load a circuit list from a file, formatted using the standard text-format.

read_circuit_strings(filename)

TODO: docstring - load various Circuit-containing standard objects from a file where

load_protocol_from_dir(dirname, quick_load=False, comm=None)

Deprecated!

read_protocol_from_dir(dirname, quick_load=False, comm=None)

Load a Protocol from a directory on disk.

load_edesign_from_dir(dirname, quick_load=False, comm=None)

Deprecated!

read_edesign_from_dir(dirname, quick_load=False, comm=None)

Load a ExperimentDesign from a directory on disk.

create_edesign_from_dir(dirname)

load_data_from_dir(dirname, quick_load=False, comm=None)

Deprecated!

read_data_from_dir(dirname, quick_load=False, comm=None)

Load a ProtocolData from a directory on disk.

load_results_from_dir(dirname, name=None, preloaded_data=None, quick_load=False, comm=None)

Deprecated!

read_results_from_dir(dirname, name=None, preloaded_data=None, quick_load=False, comm=None)

Load a ProtocolResults or ProtocolsResultsDir from a directory on disk.

_full_class_name(x)

Returns the <module>.<classname> for x.

_class_for_name(module_and_class_name)

Return the class object given an name.

_get_auxfile_ext(typ)

load_meta_based_dir(root_dir, auxfile_types_member='auxfile_types', ignore_meta=('type', ), separate_auxfiletypes=False, quick_load=False)

Load the contents of a root_dir into a dict.

_load_auxfile_member(root_dir, filenm, typ, metadata, quick_load)

write_meta_based_dir(root_dir, valuedict, auxfile_types=None, init_meta=None)

Write a dictionary of quantities to a directory.

_write_auxfile_member(root_dir, filenm, typ, val)

_cls_from_meta_json(dirname)

Get the object-type corresponding to the 'type' field in dirname/meta.json.

_obj_to_meta_json(obj, dirname)

Create a meta.json file within dirname that contains (only) the type of obj in its 'type' field.

write_obj_to_meta_based_dir(obj, dirname, auxfile_types_member, omit_attributes=())

Write the contents of obj to dirname using a 'meta.json' file and an auxfile-types dictionary.

_read_json_or_pkl_files_to_dict(dirname)

Load any .json or .pkl files in dirname into a dict.

write_dict_to_json_or_pkl_files(d, dirname)

Write each element of d into a separate file in dirname.

_check_jsonable(x)

Checks that x can be properly converted to JSON, detecting

_create_display_progress_fn(show_progress)

Create and return a progress-displaying function.

_eval_element(el, b_complex)

_eval_row_list(rows, b_complex)

parse_model(filename)

Parse a model file into a Model object.

_deprecated_fn(replacement=None)

Decorator for deprecating a function.

write_empty_dataset(filename, circuits, header_string='## Columns = 1 frequency, count total', num_zero_cols=None, append_weights_column=False)

Write an empty dataset file to be used as a template.

_outcome_to_str(x)

write_dataset(filename, dataset, circuits=None, outcome_label_order=None, fixed_column_mode='auto', with_times='auto')

Write a text-formatted dataset file.

write_multidataset(filename, multidataset, circuits=None, outcome_label_order=None)

Write a text-formatted multi-dataset file.

write_circuit_list(filename, circuits, header=None)

Write a text-formatted circuit list file.

write_model(model, filename, title=None)

Write a text-formatted model file.

write_empty_protocol_data(dirname, edesign, sparse='auto', clobber_ok=False)

Write to disk an empty ProtocolData object.

fill_in_empty_dataset_with_fake_data(dataset_filename, model, num_samples, sample_error='multinomial', seed=None, rand_state=None, alias_dict=None, collision_action='aggregate', record_zero_counts=True, comm=None, mem_limit=None, times=None, fixed_column_mode='auto')

Fills in the text-format data set file dataset_fileame with simulated data counts using model.

write_circuit_strings(filename, obj)

TODO: docstring - write various Circuit-containing standard objects with circuits

Attributes

QUICK_LOAD_MAX_SIZE

_global_parse_cache

pygsti.io._deprecated_fn(replacement=None)

Decorator for deprecating a function.

Parameters

replacement (str, optional) – the name of the function that should replace it.

Returns

function

pygsti.io.load_dataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, ignore_zero_count_lines=True, with_times='auto', circuit_parse_cache=None, verbosity=1)

Deprecated!

pygsti.io.read_dataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, ignore_zero_count_lines=True, with_times='auto', circuit_parse_cache=None, verbosity=1)

Load a DataSet from a file.

This function first tries to load file as a saved DataSet object, then as a standard text-formatted DataSet.

Parameters
  • filename (string) – The name of the file

  • cache (bool, optional) – When set to True, a pickle file with the name filename + “.cache” is searched for and loaded instead of filename if it exists and is newer than filename. If no cache file exists or one exists but it is older than filename, a cache file will be written after loading from filename.

  • collision_action ({"aggregate", "keepseparate"}) – Specifies how duplicate circuits should be handled. “aggregate” adds duplicate-circuit counts, whereas “keepseparate” tags duplicate circuits by setting their .occurrence IDs to sequential positive integers.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels. When reading from a cache file (using cache==True) this argument is ignored: the presence of zero- counts is dictated by the value of record_zero_counts when the cache file was created.

  • ignore_zero_count_lines (bool, optional) – Whether circuits for which there are no counts should be ignored (i.e. omitted from the DataSet) or not.

  • with_times (bool or "auto", optional) – Whether to the time-stamped data format should be read in. If “auto”, then the time-stamped format is allowed but not required on a per-circuit basis (so the dataset can contain both formats). Typically you only need to set this to False when reading in a template file.

  • circuit_parse_cache (dict, optional) – A dictionary mapping qubit string representations into created Circuit objects, which can improve performance by reducing or eliminating the need to parse circuit strings.

  • verbosity (int, optional) – If zero, no output is shown. If greater than zero, loading progress is shown.

Returns

DataSet

pygsti.io.load_multidataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, verbosity=1)

Deprecated!

pygsti.io.read_multidataset(filename, cache=False, collision_action='aggregate', record_zero_counts=True, verbosity=1)

Load a MultiDataSet from a file.

This function first tries to load file as a saved MultiDataSet object, then as a standard text-formatted MultiDataSet.

Parameters
  • filename (string) – The name of the file

  • cache (bool, optional) – When set to True, a pickle file with the name filename + “.cache” is searched for and loaded instead of filename if it exists and is newer than filename. If no cache file exists or one exists but it is older than filename, a cache file will be written after loading from filename.

  • collision_action ({"aggregate", "keepseparate"}) – Specifies how duplicate circuits should be handled. “aggregate” adds duplicate-circuit counts, whereas “keepseparate” tags duplicate circuits by setting their .occurrence IDs to sequential positive integers.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned MultiDataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels. When reading from a cache file (using cache==True) this argument is ignored: the presence of zero-counts is dictated by the value of record_zero_counts when the cache file was created.

  • verbosity (int, optional) – If zero, no output is shown. If greater than zero, loading progress is shown.

Returns

MultiDataSet

pygsti.io.load_time_dependent_dataset(filename, cache=False, record_zero_counts=True)

Deprecated!

pygsti.io.read_time_dependent_dataset(filename, cache=False, record_zero_counts=True)

Load time-dependent (time-stamped) data as a DataSet.

Parameters
  • filename (string) – The name of the file

  • cache (bool, optional) – Reserved to perform caching similar to read_dataset. Currently this argument doesn’t do anything.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

Returns

DataSet

pygsti.io.load_model(filename)

Load a Model from a file, formatted using the standard text-format for models.

Parameters

filename (string) – The name of the file

Returns

Model

pygsti.io.load_circuit_dict(filename)

Load a circuit dictionary from a file, formatted using the standard text-format.

Parameters

filename (string) – The name of the file.

Returns

Dictionary with keys = circuit labels and values = Circuit objects.

pygsti.io.load_circuit_list(filename, read_raw_strings=False, line_labels='auto', num_lines=None)

Deprecated!

pygsti.io.read_circuit_list(filename, read_raw_strings=False, line_labels='auto', num_lines=None)

Load a circuit list from a file, formatted using the standard text-format.

Parameters
  • filename (string) – The name of the file

  • read_raw_strings (boolean) – If True, circuits are not converted to Circuit objects.

  • line_labels (iterable, optional) – The (string valued) line labels used to initialize Circuit objects when line label information is absent from the one-line text representation contained in filename. If ‘auto’, then line labels are taken to be the list of all state-space labels present in the circuit’s layers. If there are no such labels then the special value ‘*’ is used as a single line label.

  • num_lines (int, optional) – Specify this instead of line_labels to set the latter to the integers between 0 and num_lines-1.

Returns

list of Circuit objects

pygsti.io.read_circuit_strings(filename)

TODO: docstring - load various Circuit-containing standard objects from a file where they have been replaced by their string representations

pygsti.io.load_protocol_from_dir(dirname, quick_load=False, comm=None)

Deprecated!

pygsti.io.read_protocol_from_dir(dirname, quick_load=False, comm=None)

Load a Protocol from a directory on disk.

Parameters
  • dirname (string) – Directory name.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load. This can be useful when this information isn’t needed and loading takes a long time.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to synchronize file access.

Returns

Protocol

pygsti.io.load_edesign_from_dir(dirname, quick_load=False, comm=None)

Deprecated!

pygsti.io.read_edesign_from_dir(dirname, quick_load=False, comm=None)

Load a ExperimentDesign from a directory on disk.

Parameters
  • dirname (string) – Directory name.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load. This can be useful when this information isn’t needed and loading takes a long time.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to synchronize file access.

Returns

ExperimentDesign

pygsti.io.create_edesign_from_dir(dirname)
pygsti.io.load_data_from_dir(dirname, quick_load=False, comm=None)

Deprecated!

pygsti.io.read_data_from_dir(dirname, quick_load=False, comm=None)

Load a ProtocolData from a directory on disk.

Parameters
  • dirname (string) – Directory name.

  • quick_load (bool, optional) – Setting this to True skips the loading of components that may take a long time to load. This can be useful when this information isn’t needed and loading takes a long time.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to synchronize file access.

Returns

ProtocolData

pygsti.io.load_results_from_dir(dirname, name=None, preloaded_data=None, quick_load=False, comm=None)

Deprecated!

pygsti.io.read_results_from_dir(dirname, name=None, preloaded_data=None, quick_load=False, comm=None)

Load a ProtocolResults or ProtocolsResultsDir from a directory on disk.

Which object type is loaded depends on whether name is given: if it is, then a ProtocolResults object is loaded. If not, a ProtocolsResultsDir results.

Parameters
  • dirname (string) – Directory name. This should be a “base” directory, containing subdirectories like “edesign”, “data”, and “results”

  • name (string or None) – The ‘name’ of a particular ProtocolResults object, which is a sub-directory beneath dirname/results/. If None, then all the results (all names) at the given base-directory are loaded and returned as a ProtocolResultsDir object.

  • preloaded_data (ProtocolData, optional) – The data object belonging to the to-be-loaded results, in cases when this has been loaded already (only use this if you know what you’re doing).

  • quick_load (bool, optional) – Setting this to True skips the loading of data and experiment-design components that may take a long time to load. This can be useful all the information of interest lies only within the results objects.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator used to synchronize file access.

Returns

ProtocolResults or ProtocolResultsDir

class pygsti.io._NicelySerializable

Bases: object

The base class for all “nicely serializable” objects in pyGSTi.

A “nicely serializable” object can be converted to and created from a native Python object (like a string or dict) that contains only other native Python objects. In addition, there are constraints on the makeup of these objects so that they can be easily serialized to standard text-based formats, e.g. JSON. For example, dictionary keys must be strings, and the list vs. tuple distinction cannot be assumed to be preserved during serialization.

classmethod read(cls, path, format=None)

Read an object of this type, or a subclass of this type, from a file.

Parameters
  • path (str or Path or file-like) – The filename to open or an already open input stream.

  • format ({'json', None}) – The format of the file. If None this is determined automatically by the filename extension of a given path.

Returns

NicelySerializable

classmethod load(cls, f, format='json')

Load an object of this type, or a subclass of this type, from an input stream.

Parameters
  • f (file-like) – An open input stream to read from.

  • format ({'json'}) – The format of the input stream data.

Returns

NicelySerializable

classmethod loads(cls, s, format='json')

Load an object of this type, or a subclass of this type, from a string.

Parameters
  • s (str) – The serialized object.

  • format ({'json'}) – The format of the string data.

Returns

NicelySerializable

classmethod from_nice_serialization(cls, state)

Create and initialize an object from a “nice” serialization.

A “nice” serialization here means one created by a prior call to to_nice_serialization using this class or a subclass of it. Nice serializations adhere to additional rules (e.g. that dictionary keys must be strings) that make them amenable to common file formats (e.g. JSON).

The state argument is typically a dictionary containing ‘module’ and ‘state’ keys specifying the type of object that should be created. This type must be this class or a subclass of it.

Parameters

state (object) – An object, usually a dictionary, representing the object to de-serialize.

Returns

object

to_nice_serialization(self)

Serialize this object in a way that adheres to “niceness” rules of common text file formats.

Returns

object – Usually a dictionary representing the serialized object, but may also be another native Python type, e.g. a string or list.

write(self, path, **format_kwargs)

Writes this object to a file.

Parameters
  • path (str or Path) – The name of the file that is written.

  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

None

dump(self, f, format='json', **format_kwargs)

Serializes and writes this object to a given output stream.

Parameters
  • f (file-like) – A writable output stream.

  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

None

dumps(self, format='json', **format_kwargs)

Serializes this object and returns it as a string.

Parameters
  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

str

_dump_or_dumps(self, f, format='json', **format_kwargs)

Serializes and writes this object to a given output stream.

Parameters
  • f (file-like) – A writable output stream. If None, then object is written as a string and returned.

  • format ({'json', 'repr'}) – The format to write.

  • format_kwargs (dict, optional) – Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

Returns

str or None – If f is None, then the serialized object as a string is returned. Otherwise, None is returned.

_to_nice_serialization(self)
classmethod _from_nice_serialization(cls, state)
classmethod _state_class(cls, state, check_is_subclass=True)

Returns the class specified by the given state dictionary

classmethod _check_compatible_nice_state(cls, state)
classmethod _encodemx(cls, mx)
classmethod _decodemx(cls, mx)
classmethod _encodevalue(cls, val)
classmethod _decodevalue(cls, val)
class pygsti.io._VerbosityPrinter(verbosity=1, filename=None, comm=None, warnings=True, split=False, clear_file=True)

Bases: object

Class responsible for logging things to stdout or a file.

Controls verbosity and can print progress bars. ex:

>>> VerbosityPrinter(1)

would construct a printer that printed out messages of level one or higher to the screen.

>>> VerbosityPrinter(3, 'output.txt')

would construct a printer that sends verbose output to a text file

The static function create_printer() will construct a printer from either an integer or an already existing printer. it is a static method of the VerbosityPrinter class, so it is called like so:

>>> VerbosityPrinter.create_printer(2)

or

>>> VerbostityPrinter.create_printer(VerbosityPrinter(3, 'output.txt'))

printer.log('status') would log ‘status’ if the printers verbosity was one or higher. printer.log('status2', 2) would log ‘status2’ if the printer’s verbosity was two or higher

printer.error('something terrible happened') would ALWAYS log ‘something terrible happened’. printer.warning('something worrisome happened') would log if verbosity was one or higher - the same as a normal status.

Both printer.error and printer.warning will prepend ‘ERROR: ‘ or ‘WARNING: ‘ to the message they are given. Optionally, printer.log() can also prepend ‘Status_n’ to the message, where n is the message level.

Logging of progress bars/iterations:

>>> with printer_instance.progress_logging(verbosity):
>>>     for i, item in enumerate(data):
>>>         printer.show_progress(i, len(data))
>>>         printer.log(...)

will output either a progress bar or iteration statuses depending on the printer’s verbosity

Parameters
  • verbosity (int) – How verbose the printer should be.

  • filename (str, optional) – Where to put output (If none, output goes to screen)

  • comm (mpi4py.MPI.Comm or ResourceAllocation, optional) – Restricts output if the program is running in parallel (By default, if the rank is 0, output is sent to screen, and otherwise sent to commfiles 1, 2, …

  • warnings (bool, optional) – Whether or not to print warnings

  • split (bool, optional) – Whether to split output between stdout and stderr as appropriate, or to combine the streams so everything is sent to stdout.

  • clear_file (bool, optional) – Whether or not filename should be cleared (overwritten) or simply appended to.

_comm_path

relative path where comm files (outputs of non-root ranks) are stored.

Type

str

_comm_file_name

root filename for comm files (outputs of non-root ranks).

Type

str

_comm_file_ext

filename extension for comm files (outputs of non-root ranks).

Type

str

_comm_path =
_comm_file_name =
_comm_file_ext = .txt
_create_file(self, filename)
_get_comm_file(self, comm_id)
clone(self)

Instead of deepcopy, initialize a new printer object and feed it some select deepcopied members

Returns

VerbosityPrinter

static create_printer(verbosity, comm=None)

Function for converting between interfaces

Parameters
  • verbosity (int or VerbosityPrinter object, required:) – object to build a printer from

  • comm (mpi4py.MPI.Comm object, optional) – Comm object to build printers with. !Will override!

Returns

VerbosityPrinter – The printer object, constructed from either an integer or another printer

__add__(self, other)

Increase the verbosity of a VerbosityPrinter

__sub__(self, other)

Decrease the verbosity of a VerbosityPrinter

__getstate__(self)
__setstate__(self, state_dict)
_append_to(self, filename, message)
_put(self, message, flush=True, stderr=False)
_record(self, typ, level, message)
error(self, message)

Log an error to the screen/file

Parameters

message (str) – the error message

Returns

None

warning(self, message)

Log a warning to the screen/file if verbosity > 1

Parameters

message (str) – the warning message

Returns

None

log(self, message, message_level=None, indent_char='  ', show_statustype=False, do_indent=True, indent_offset=0, end='\n', flush=True)

Log a status message to screen/file.

Determines whether the message should be printed based on current verbosity setting, then sends the message to the appropriate output

Parameters
  • message (str) – the message to print (or log)

  • message_level (int, optional) – the minimum verbosity level at which this level is printed.

  • indent_char (str, optional) – what constitutes an “indent” (messages at higher levels are indented more when do_indent=True).

  • show_statustype (bool, optional) – if True, prepend lines with “Status Level X” indicating the message_level.

  • do_indent (bool, optional) – whether messages at higher message levels should be indented. Note that if this is False it may be helpful to set show_statustype=True.

  • indent_offset (int, optional) – an additional number of indentations to add, on top of any due to the message level.

  • end (str, optional) – the character (or string) to end message lines with.

  • flush (bool, optional) – whether stdout should be flushed right after this message is printed (this avoids delays in on-screen output due to buffering).

Returns

None

_progress_bar(self, iteration, total, bar_length, num_decimals, fill_char, empty_char, prefix, suffix, indent)
_verbose_iteration(self, iteration, total, prefix, suffix, verbose_messages, indent, end)
__str__(self)

Return str(self).

verbosity_env(self, level)

Create a temporary environment with a different verbosity level.

This is context manager, controlled using Python’s with statement:

>>> with printer.verbosity_env(2):
        printer.log('Message1') # printed at verbosity level 2
        printer.log('Message2') # printed at verbosity level 2
Parameters

level (int) – the verbosity level of the environment.

progress_logging(self, message_level=1)

Context manager for logging progress bars/iterations.

(The printer will return to its normal, unrestricted state when the progress logging has finished)

Parameters

message_level (int, optional) – progress messages will not be shown until the verbosity level reaches message_level.

show_progress(self, iteration, total, bar_length=50, num_decimals=2, fill_char='#', empty_char='-', prefix='Progress:', suffix='', verbose_messages=[], indent_char='  ', end='\n')

Displays a progress message (to be used within a progress_logging block).

Parameters
  • iteration (int) – the 0-based current iteration – the interation number this message is for.

  • total (int) – the total number of iterations expected.

  • bar_length (int, optional) – the length, in characters, of a text-format progress bar (only used when the verbosity level is exactly equal to the progress_logging message level.

  • num_decimals (int, optional) – number of places after the decimal point that are displayed in progress bar’s percentage complete.

  • fill_char (str, optional) – replaces ‘#’ as the bar-filling character

  • empty_char (str, optional) – replaces ‘-’ as the empty-bar character

  • prefix (str, optional) – message in front of the bar

  • suffix (str, optional) – message after the bar

  • verbose_messages (list, optional) – A list of strings to display after an initial “Iter X of Y” line when the verbosity level is higher than the progress_logging message level and so more verbose messages are shown (and a progress bar is not). The elements of verbose_messages will occur, one per line, after the initial “Iter X of Y” line.

  • indent_char (str, optional) – what constitutes an “indentation”.

  • end (str, optional) – the character (or string) to end message lines with.

Returns

None

_end_progress(self)
start_recording(self)

Begins recording the output (to memory).

Begins recording (in memory) a list of (type, verbosityLevel, message) tuples that is returned by the next call to :method:`stop_recording`.

Returns

None

is_recording(self)

Returns whether this VerbosityPrinter is currently recording.

Returns

bool

stop_recording(self)

Stops recording and returns recorded output.

Stops a “recording” started by :method:`start_recording` and returns the list of (type, verbosityLevel, message) tuples that have been recorded since then.

Returns

list

pygsti.io.QUICK_LOAD_MAX_SIZE
pygsti.io._full_class_name(x)

Returns the <module>.<classname> for x.

Parameters

x (class) – The class whose full name you want.

Returns

str

pygsti.io._class_for_name(module_and_class_name)

Return the class object given an name.

Parameters

module_and_class_name (strictly) – The module and class name, e.g. “mymodule.MyClass”

Returns

class

pygsti.io._get_auxfile_ext(typ)
pygsti.io.load_meta_based_dir(root_dir, auxfile_types_member='auxfile_types', ignore_meta=('type',), separate_auxfiletypes=False, quick_load=False)

Load the contents of a root_dir into a dict.

The de-serialization uses the ‘meta.json’ file within root_dir to describe how the directory was serialized.

Parameters
  • root_dir (str) – The directory name.

  • auxfile_types_member (str, optional) – The key within meta.json that is used to describe how other members have been serialized into files. Unless you know what you’re doing, leave this as the default.

  • ignore_meta (tuple, optional) – Keys within meta.json that should be ignored, i.e. not loaded into elements of the returned dict. By default, “type” is in this category because it describes a class name to be built and is used in a separate first-pass processing to construct a object. Unless you know what you’re doing, leave this as the default.

  • separate_auxfiletypes (bool, optional) – If True, then return the auxfile_types_member element (a dict describing how quantities that aren’t in ‘meta.json’ have been serialized) as a separate return value, instead of placing it within the returned dict.

  • quick_load (bool, optional) – Setting this to True skips the loading of members that may take a long time to load, namely those in separate files whose files are large. When the loading of an attribute is skipped, it is set to None.

Returns

  • loaded_qtys (dict) – A dictionary of the quantities in ‘meta.json’ plus any loaded from the auxiliary files.

  • auxfile_types (dict) – Only returned as a separate value when separate_auxfiletypes=True. A dict describing how members of loaded_qtys that weren’t loaded directly from ‘meta.json’ were serialized.

pygsti.io._load_auxfile_member(root_dir, filenm, typ, metadata, quick_load)
pygsti.io.write_meta_based_dir(root_dir, valuedict, auxfile_types=None, init_meta=None)

Write a dictionary of quantities to a directory.

Write the dictionary by placing everything in a ‘meta.json’ file except for special key/value pairs (“special” usually because they lend themselves to an non-JSON format or they simply cannot be rendered as JSON) which are placed in “auxiliary” files formatted according to auxfile_types (which itself is saved in meta.json).

Parameters
  • root_dir (str) – The directory to write to (will be created if needed).

  • valuedict (dict) – The dictionary of values to serialize to disk.

  • auxfile_types (dict, optional) – A dictionary whose keys are a subset of the keys of valuedict, and whose values are known “aux-file” types. auxfile_types[key] says that valuedict[key] should be serialized into a separate file (whose name is usually key + an appropriate extension) of the given format rather than be included directly in ‘meta.json`. If None, this dictionary is assumed to be valuedict[‘auxfile_types’].

  • init_meta (dict, optional) – A dictionary of “initial” meta-data to be included in the ‘meta.json’ (but that isn’t in valuedict). For example, the class name of an object is often stored as in the “type” field of meta.json when the_model objects .__dict__ is used as valuedict.

Returns

None

pygsti.io._write_auxfile_member(root_dir, filenm, typ, val)
pygsti.io._cls_from_meta_json(dirname)

Get the object-type corresponding to the ‘type’ field in dirname/meta.json.

Parameters

dirname (str) – the directory name.

Returns

class

pygsti.io._obj_to_meta_json(obj, dirname)

Create a meta.json file within dirname that contains (only) the type of obj in its ‘type’ field.

This is used to save an object that contains essentially no other data to a directory, in lieu of :function:`write_obj_to_meta_based_dir`.

Parameters
  • obj (object) – he object whose type you want to save.

  • dirname (str) – the directory name.

Returns

None

pygsti.io.write_obj_to_meta_based_dir(obj, dirname, auxfile_types_member, omit_attributes=())

Write the contents of obj to dirname using a ‘meta.json’ file and an auxfile-types dictionary.

This is similar to :function:`write_meta_based_dir`, except it takes an object (obj) whose .__dict__, minus omitted attributes, is used as the dictionary to write and whose auxfile-types comes from another object attribute..

Parameters
  • obj (object) – the object to serialize

  • dirname (str) – the directory name

  • auxfile_types_member (str) – the name of the attribute within obj that holds the dictionary mapping of attributes to auxiliary-file types. Usually this is “auxfile_types”.

  • omit_attributes (list or tuple) – List of (string-valued) names of attributes to omit when serializing this object. Usually you should just leave this empty.

Returns

None

pygsti.io._read_json_or_pkl_files_to_dict(dirname)

Load any .json or .pkl files in dirname into a dict.

Parameters

dirname (str) – the directory name.

Returns

dict

pygsti.io.write_dict_to_json_or_pkl_files(d, dirname)

Write each element of d into a separate file in dirname.

If the element is json-able, it is JSON-serialized and the “.json” extension is used. If not, pickle is used to serialize the element, and the “.pkl” extension is used. This is the reverse of :function:`_read_json_or_pkl_files_to_dict`.

Parameters
  • d (dict) – the dictionary of elements to serialize.

  • dirname (str) – the directory name.

Returns

None

pygsti.io._check_jsonable(x)

Checks that x can be properly converted to JSON, detecting errors that the json modules doesn’t pick up. E.g. ensures that x doesn’t contain dicts with non-string-valued keys

class pygsti.io._Circuit(layer_labels=(), line_labels='auto', num_lines=None, editable=False, stringrep=None, name='', check=True, expand_subcircuits='default', occurrence=None, compilable_layer_indices=None)

Bases: object

A quantum circuit.

A Circuit represents a quantum circuit, consisting of state preparation, gates, and measurement operations. It is composed of some number of “lines”, typically one per qubit, and stores the operations on these lines as a sequence of Label objects, one per circuit layer, whose .sslbls members indicate which line(s) the label belongs on. When a circuit is created with ‘editable=True’, a rich set of operations may be used to construct the circuit in place, after which done_editing() should be called so that the Circuit can be properly hashed as needed.

Parameters
  • layer_labels (iterable of Labels or str) –

    This argument provides a list of the layer labels specifying the state preparations, gates, and measurements for the circuit. This argument can also be a Circuit or a string, in which case it is parsed as a text-formatted circuit. Internally this will eventually be converted to a list of Label objects, one per layer, but it may be specified using anything that can be readily converted to a Label objects. For example, any of the following are allowed:

    • [‘Gx’,’Gx’] : X gate on each of 2 layers

    • `[Label(‘Gx’),Label(‘Gx’)] : same as above

    • [(‘Gx’,0),(‘Gy’,0)] : X then Y on qubit 0 (2 layers)

    • [[(‘Gx’,0),(‘Gx’,1)],[(‘Gy’,0),(‘Gy’,1)]] : parallel X then Y on qubits 0 & 1

  • line_labels (iterable, optional) – The (string valued) label for each circuit line. If ‘auto’, then line_labels is taken to be the list of all state-space labels present within layer_labels. If there are no such labels (e.g. if layer_labels contains just gate names like (‘Gx’,’Gy’)), then the special value ‘*’ is used as a single line label.

  • num_lines (int, optional) – Specify this instead of line_labels to set the latter to the integers between 0 and num_lines-1.

  • editable (bool, optional) – Whether the created Circuit is created in able to be modified. If True, then you should call done_editing() once the circuit is completely assembled, as this makes the circuit read-only and allows it to be hashed.

  • stringrep (string, optional) – A string representation for the circuit. If None (the default), then this will be generated automatically when needed. One reason you’d want to specify this is if you know of a nice compact string representation that you’d rather use, e.g. “Gx^4” instead of the automatically generated “GxGxGxGx”. If you want to initialize a Circuit entirely from a string representation you can either specify the string in as layer_labels or set layer_labels to None and stringrep to any valid (one-line) circuit string.

  • name (str, optional) – A name for this circuit (useful if/when used as a block within larger circuits).

  • check (bool, optional) – Whether stringrep should be checked against layer_labels to ensure they are consistent, and whether the labels in layer_labels are a subset of line_labels. The only reason you’d want to set this to False is if you’re absolutely sure stringrep and line_labels are consistent and want to save computation time.

  • expand_subcircuits (bool or "default") – If “default”, then the value of Circuit.default_expand_subcircuits is used. If True, then any sub-circuits (e.g. anything exponentiated like “(GxGy)^4”) will be expanded when it is stored within the created Circuit. If False, then such sub-circuits will be left as-is. It’s typically more robust to expand sub-circuits as this facilitates comparison (e.g. so “GxGx” == “Gx^2”), but in cases when you have massive exponents (e.g. “Gx^8192”) it may improve performance to set expand_subcircuits=False.

  • occurrence (hashable, optional) – A value to set as the “occurrence id” for this circuit. This value doesn’t affect the circuit an any way except by affecting it’s hashing and equivalence testing. Circuits with different occurrence ids are not equivalent. Occurrence values effectively allow multiple copies of the same ciruit to be stored in a dictionary or DataSet.

  • compilable_layer_indices (tuple, optional) – The circuit-layer indices that may be internally altered (but retaining the same target operation) and/or combined with the following circuit layer by a hardware compiler.when executing this circuit. Layers that are not “compilable” are effectively followed by a barrier which prevents the hardward compiler from restructuring the circuit across the layer boundary.

default_expand_subcircuits

By default, expand sub-circuit labels.

Type

bool

line_labels

The line labels (often qubit labels) of this circuit.

Type

tuple

layertup

This Circuit’s layers as a standard Python tuple of layer Labels.

Type

tuple

tup

This Circuit as a standard Python tuple of layer Labels and line labels.

Type

tuple

str

The Python string representation of this Circuit.

Type

str

default_expand_subcircuits = True
classmethod cast(cls, obj)

Convert obj into a Circuit.

Parameters

obj (object) – Object to convert

Returns

Circuit

classmethod from_tuple(cls, tup)

Creates a Circuit from a tuple

Parameters

tup (tuple) – The tuple to convert.

Returns

Circuit

classmethod _fastinit(cls, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)
_bare_init(self, labels, line_labels, editable, name='', stringrep=None, occurrence=None, compilable_layer_indices=None)
to_label(self, nreps=1)

Construct and return this entire circuit as a CircuitLabel.

Note: occurrence-id information is not stored in a circuit label, so circuits that differ only in their occurence_id will return circuit labels that are equal.

Parameters

nreps (int, optional) – The number of times this circuit will be repeated (CircuitLabels support exponentiation and you can specify this here).

Returns

CircuitLabel

property line_labels(self)

The line labels (often qubit labels) of this circuit.

property name(self)

The name of this circuit.

Note: the name is not a part of the hashed value. The name is used to name the CircuitLabel returned from :method:`to_label`.

property occurrence(self)

The occurrence id of this circuit.

property layertup(self)

This Circuit’s layers as a standard Python tuple of layer Labels.

Returns

tuple

property tup(self)

This Circuit as a standard Python tuple of layer Labels and line labels.

Returns

tuple

property compilable_layer_indices(self)

Tuple of the layer indices corresponding to “compilable” layers.

property compilable_by_layer(self)

Boolean array indicating whether each layer is “compilable” or not.

property str(self)

The Python string representation of this Circuit.

Returns

str

property layerstr(self)

Just the string representation of the circuit layers (no ‘@<line_labels>’ suffix)

property linesstr(self)

Just the string representation of the circuit’s line labels (the ‘@<line_labels>’ suffix)

_labels_lines_str(self)

Split the string representation up into layer-labels & line-labels parts

__hash__(self)

Return hash(self).

__len__(self)
__iter__(self)
__contains__(self, x)

Note: this is not covered by __iter__ for case of contained CircuitLabels

__radd__(self, x)
__add__(self, x)
repeat(self, ntimes, expand='default')

Repeat this circuit ntimes times.

Parameters
  • ntimes (int) – Number of repetitions.

  • expand (bool or "default", optional) – When False, the returned circuit will contain a CircuitLabel encapsulating the repetitions without explicitly storing them. When True, the returned circuit will be expanded into the ntimes repetitions. “default” means to use the value in the class variable Circuit.default_expand_subcircuits.

__mul__(self, x)
__pow__(self, x)
__eq__(self, x)

Return self==value.

__lt__(self, x)

Return self<value.

__gt__(self, x)

Return self>value.

property num_lines(self)

The number of lines in this circuit.

Returns

int

copy(self, editable='auto')

Returns a copy of the circuit.

Parameters

editable ({True,False,"auto"}) – Whether returned copy is editable. If “auto” is given, then the copy is editable if and only if this Circuit is.

Returns

Circuit

clear(self)

Removes all the gates in a circuit (preserving the number of lines).

Returns

None

_proc_layers_arg(self, layers)

Pre-process the layers argument used by many methods

_proc_lines_arg(self, lines)

Pre-process the lines argument used by many methods

_proc_key_arg(self, key)

Pre-process the key argument used by many methods

_layer_components(self, ilayer)

Get the components of the ilayer-th layer as a list/tuple.

_remove_layer_component(self, ilayer, indx)

Removes the indx-th component from the ilayer-th layer

_append_layer_component(self, ilayer, val)

Add val to the ilayer-th layer

_replace_layer_component(self, ilayer, indx, val)
extract_labels(self, layers=None, lines=None, strict=True)

Get a subregion - a “rectangle” - of this Circuit.

This can be used to select multiple layers and/or lines of this Circuit. The strict argument controls whether gates need to be entirely within the given rectangle or can be intersecting it. If layers is a single integer then a Label is returned (representing a layer or a part of a layer), otherwise a Circuit is returned.

Parameters
  • layers (int, slice, or list/tuple of ints) – Which layers to select (the horizontal dimension of the selection rectangle). Layers are always selected by index, and this argument can be a single (integer) index - in which case a Label is returned - or multiple indices as given by a slice or list - in which case a Circuit is returned. Note that, even though we speak of a “rectangle”, layer indices do not need to be contiguous. The special value None selects all layers.

  • lines (str/int, slice, or list/tuple of strs/ints) – Which lines to select (the vertical dimension of the selection rectangle). Lines are selected by their line-labels (elements of the circuit’s .line_labels property), which can be strings and/or integers. A single or multiple line-labels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to select multiple of them. Note that line-labels do not need to be contiguous. The special value None selects all lines.

  • strict (bool, optional) – When True, only gates lying completely within the selected region are included in the return value. If a gate straddles the region boundary (e.g. if we select just line 1 and the circuit contains “Gcnot:1:2”) then it is silently not-included in the returned label or circuit. If False, then gates which straddle the region boundary are included. Note that this may result in a Label or Circuit containing more line labels than where requested in the call to extract_labels(…)..

Returns

Label or Circuit – The requested portion of this circuit, given as a Label if layers is a single integer and as a Circuit otherwise. Note: if you want a Circuit when only selecting one layer, set layers to a slice or tuple containing just a single index.

set_labels(self, lbls, layers=None, lines=None)

Write lbls to the block defined by the layers and lines arguments.

Note that lbls can be anything interpretable as a Label or list of labels.

Parameters
  • lbls (Label, list/tuple of Labels, or Circuit) – When layers is a single integer, lbls should be a single “layer label” of type Label. Otherwise, lbls should be a list or tuple of Label objects with length equal to the number of layers being set. A Circuit may also be used in this case.

  • layers (int, slice, or list/tuple of ints) – Which layers to set (the horizontal dimension of the destination rectangle). Layers are always selected by index, and this argument can be a single (integer) index or multiple indices as given by a slice or list. Note that these indices do not need to be contiguous. The special value None stands for all layers.

  • lines (str/int, slice, or list/tuple of strs/ints) – Which lines to set (the vertical dimension of the destination rectangle). Lines are selected by their line-labels, which can be strings and/or integers. A single or multiple line-labels can be specified. If the line labels are integers a slice can be used, otherwise a list or tuple of labels is the only way to specify multiple of them. The line-labels do not need to be contiguous. The special value None stands for all lines, and in this case new lines will be created if there are new state-space labels in lbls (when lines is not None an error is raised instead).

Returns

None

insert_idling_layers(self, insert_before, num_to_insert, lines=None)

Inserts into this circuit one or more idling (blank) layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • num_to_insert (int) – The number of new layers to insert.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

Circuit

insert_idling_layers_inplace(self, insert_before, num_to_insert, lines=None)

Inserts into this circuit one or more idling (blank) layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • insert_before (int) – The layer index to insert the new layers before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • num_to_insert (int) – The number of new layers to insert.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

None

_append_idling_layers_inplace(self, num_to_insert, lines=None)

Adds one or more idling (blank) layers to the end of this circuit.

By default, complete layer(s) are appended. The lines argument allows you to add partial layers (on only a subset of the lines).

Parameters
  • num_to_insert (int) – The number of new layers to append.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have new layers (blank circuit space) inserted into them. A single or multiple line-labels can be specified, similarly as in :method:`extract_labels`. The default value None stands for all lines.

Returns

None

insert_labels_into_layers(self, lbls, layer_to_insert_before, lines=None)

Inserts into this circuit the contents of lbls into new full or partial layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.

Returns

Circuit

insert_labels_into_layers_inplace(self, lbls, layer_to_insert_before, lines=None)

Inserts into this circuit the contents of lbls into new full or partial layers.

By default, complete layer(s) are inserted. The lines argument allows you to insert partial layers (on only a subset of the lines).

Parameters
  • lbls (list/tuple of Labels, or Circuit) – The full or partial layer labels to insert. The length of this list, tuple, or circuit determines the number of layers which are inserted.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The special value None inserts at the end.

  • lines (str/int, slice, or list/tuple of strs/ints, optional) – Which lines should have lbls inserted into them. Currently this can only be a larger set than the set of line labels present in lbls (in future versions this may allow filtering of lbls). value None stands for all lines.

Returns

None

insert_idling_lines(self, insert_before, line_labels)

Insert one or more idling (blank) lines into this circuit.

Parameters
  • insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.

  • line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

Circuit

insert_idling_lines_inplace(self, insert_before, line_labels)

Insert one or more idling (blank) lines into this circuit.

Parameters
  • insert_before (str or int) – The line label to insert new lines before. The special value None inserts lines at the bottom of this circuit.

  • line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

None

_append_idling_lines(self, line_labels)

Add one or more idling (blank) lines onto the bottom of this circuit.

Parameters

line_labels (list or tuple) – A list or tuple of the new line labels to insert (can be integers and/or strings).

Returns

None

insert_labels_as_lines_inplace(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')

Inserts into this circuit the contents of lbls into new lines.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.

Returns

None

insert_labels_as_lines(self, lbls, layer_to_insert_before=None, line_to_insert_before=None, line_labels='auto')

Inserts into this circuit the contents of lbls into new lines.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to insert as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_to_insert_before (str or int) – The line label to insert the new lines before. The default value of None inserts lines at the bottom of the circuit.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being inserted. If “auto”, then these are inferred from lbls.

Returns

None

_append_labels_as_lines(self, lbls, layer_to_insert_before=None, line_labels='auto')

Adds the contents of lbls as new lines at the bottom of this circuit.

By default, lbls is inserted at the beginning of the new lines(s). The layer_to_insert_before argument allows you to insert lbls beginning at a layer of your choice.

Parameters
  • lbls (list/tuple of Labels, or Circuit) – A list of layer labels to append as new lines. The state-space (line) labels within lbls must not overlap with that of this circuit or an error is raised. If lbls contains more layers than this circuit currently has, new layers are added automatically.

  • layer_to_insert_before (int) – The layer index to insert lbls before. Can be from 0 (insert at the beginning) to len(self)-1 (insert at end), and negative indexing can be used to insert relative to the last layer. The default value of None inserts at the beginning.

  • line_labels (list, tuple, or "auto") – The labels of the new lines being added. If “auto”, then these are inferred from lbls.

Returns

None

_clear_labels(self, layers, lines, clear_straddlers=False)

remove all labels in a block given by layers and lines Note: layers & lines must be lists/tuples of values; they can’t be slices or single vals

clear_labels(self, layers=None, lines=None, clear_straddlers=False)

Removes all the gates within the given circuit region. Does not reduce the number of layers or lines.

Parameters
  • layers (int, slice, or list/tuple of ints) – Defines the horizontal dimension of the region to clear. See :method:`extract_labels` for details.

  • lines (str/int, slice, or list/tuple of strs/ints) – Defines the vertical dimension of the region to clear. See :method:`extract_labels` for details.

  • clear_straddlers (bool, optional) – Whether or not gates which straddle cleared and non-cleared lines should be cleared. If False and straddling gates exist, an error will be raised.

Returns

None

delete_layers(self, layers=None)

Deletes one or more layers from the circuit.

Parameters

layers (int, slice, or list/tuple of ints) – The layer index or indices to delete. See :method:`extract_labels` for details.

Returns

None

delete_lines(self, lines, delete_straddlers=False)

Deletes one or more lines from the circuit.

Parameters
  • lines (str/int, slice, or list/tuple of strs/ints) – The line label(s) to delete. See :method:`extract_labels` for details.

  • delete_straddlers (bool, optional) – Whether or not gates which straddle deleted and non-deleted lines should be removed. If False and straddling gates exist, an error will be raised.

Returns

None

__getitem__(self, key)
__setitem__(self, key, val)
__delitem__(self, key)
to_pythonstr(self, op_labels)

Convert this circuit to an “encoded” python string.

In the returned string each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This can be useful for processing operation sequences using python’s string tools (regex in particular).

Parameters

op_labels (tuple) – An iterable containing at least all the layer-Labels that appear in this Circuit, and which will be mapped to alphabet characters, beginning with ‘A’.

Returns

string – The converted operation sequence.

Examples

(‘Gx’,’Gx’,’Gy’,’Gx’) => “AABA”

classmethod from_pythonstr(cls, python_string, op_labels)

Decode an “encoded string” into a Circuit.

Create a Circuit from a python string where each operation label is represented as a single character, starting with ‘A’ and continuing down the alphabet. This performs the inverse of :method:`to_pythonstr`.

Parameters
  • python_string (string) – string whose individual characters correspond to the operation labels of a operation sequence.

  • op_labels (tuple) – tuple containing all the operation labels that will be mapped from alphabet characters, beginning with ‘A’.

Returns

Circuit

Examples

“AABA” => (‘Gx’,’Gx’,’Gy’,’Gx’)

serialize(self)

Serialize the parallel gate operations of this Circuit.

Construct a new Circuit whereby all layers containing multiple gates are converted to separate single-gate layers, effectively putting each elementary gate operation into its own layer. Ordering is dictated by the ordering of the compound layer labels.

Returns

Circuit

parallelize(self, can_break_labels=True, adjacent_only=False)

Compress a circuit’s gates by performing them in parallel.

Construct a circuit with the same underlying labels as this one, but with as many gates performed in parallel as possible (with some restrictions - see the Parameters section below). Generally, gates are moved as far left (toward the start) of the circuit as possible.

Parameters
  • can_break_labels (bool, optional) – Whether compound (parallel-gate) labels in this Circuit can be separated during the parallelization process. For example, if can_break_labels=True then “Gx:0[Gy:0Gy:1]” => “[Gx:0Gy:1]Gy:0” whereas if can_break_labels=False the result would remain “Gx:0[Gy:0Gy:1]” because [Gy:0Gy:1] cannot be separated.

  • adjacent_only (bool, optional) – It True, then operation labels are only allowed to move into an adjacent label, that is, they cannot move “through” other operation labels. For example, if adjacent_only=True then “Gx:0Gy:0Gy:1” => “Gx:0[Gy:0Gy:1]” whereas if adjacent_only=False the result would be “[Gx:0Gy:1]Gy:0. Setting this to True is sometimes useful if you want to parallelize a serial string in such a way that subsequently calling .serialize() will give you back the original string.

Returns

Circuit

expand_subcircuits_inplace(self)

Expands all CircuitLabel labels within this circuit.

This operation is done in place and so can only be performed on an editable Circuit.

Returns

None

expand_subcircuits(self)

Returns a new circuit with CircuitLabel labels expanded.

Returns

Circuit

factorize_repetitions_inplace(self)

Attempt to replace repeated sub-circuits with CircuitLabel objects.

More or less the reverse of :method:`expand_subcircuits`, this method attempts to collapse repetitions of the same labels into single CircuitLabel labels within this circuit.

This operation is done in place and so can only be performed on an editable Circuit.

Returns

None

insert_layer(self, circuit_layer, j)

Inserts a single layer into a circuit.

The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.

Parameters
  • circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.

  • j (int) – The layer index (depth) at which to insert the circuit_layer.

Returns

Circuit

insert_layer_inplace(self, circuit_layer, j)

Inserts a single layer into a circuit.

The input layer does not need to contain a gate that acts on every qubit, but it should not contain more than one gate on a qubit.

Parameters
  • circuit_layer (Label) – The layer to insert. A (possibly compound) Label object or something that can be converted into one, e.g. ((‘Gx’,0),(‘Gcnot’,1,2)) or just ‘Gx’.

  • j (int) – The layer index (depth) at which to insert the circuit_layer.

Returns

None

insert_circuit(self, circuit, j)

Inserts a circuit into this circuit.

The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all non-idling qubits must be a subset of the labels of this circuit.

Parameters
  • circuit (Circuit) – The circuit to be inserted.

  • j (int) – The layer index (depth) at which to insert the circuit.

Returns

Circuit

insert_circuit_inplace(self, circuit, j)

Inserts a circuit into this circuit.

The circuit to insert can be over more qubits than this circuit, as long as all qubits that are not part of this circuit are idling. In this case, the idling qubits are all discarded. The circuit to insert can also be on less qubits than this circuit: all other qubits are set to idling. So, the labels of the circuit to insert for all non-idling qubits must be a subset of the labels of this circuit.

Parameters
  • circuit (Circuit) – The circuit to be inserted.

  • j (int) – The layer index (depth) at which to insert the circuit.

Returns

None

append_circuit(self, circuit)

Append a circuit to the end of this circuit.

This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be appended.

Returns

Circuit

append_circuit_inplace(self, circuit)

Append a circuit to the end of this circuit.

This circuit must satisfy the requirements of :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be appended.

Returns

None

prefix_circuit(self, circuit)

Prefix a circuit to the beginning of this circuit.

This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be prefixed.

Returns

Circuit

prefix_circuit_inplace(self, circuit)

Prefix a circuit to the beginning of this circuit.

This circuit must satisfy the requirements of the :method:`insert_circuit()`. See that method for more details.

Parameters

circuit (A Circuit object) – The circuit to be prefixed.

Returns

None

tensor_circuit_inplace(self, circuit, line_order=None)

The tensor product of this circuit and circuit.

That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.

Parameters
  • circuit (A Circuit object) – The circuit to be tensored.

  • line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.

Returns

None

tensor_circuit(self, circuit, line_order=None)

The tensor product of this circuit and circuit.

That is, it adds circuit to this circuit as new lines. The line labels of circuit must be disjoint from the line labels of this circuit, as otherwise applying the circuits in parallel does not make sense.

Parameters
  • circuit (A Circuit object) – The circuit to be tensored.

  • line_order (List, optional) – A list of all the line labels specifying the order of the circuit in the updated circuit. If None, the lines of circuit are added below the lines of this circuit. Note that, for many purposes, the ordering of lines of the circuit is irrelevant.

Returns

Circuit

replace_layer_with_circuit_inplace(self, circuit, j)

Replaces the j-th layer of this circuit with circuit.

Parameters
  • circuit (Circuit) – The circuit to insert

  • j (int) – The layer index to replace.

Returns

None

replace_layer_with_circuit(self, circuit, j)

Replaces the j-th layer of this circuit with circuit.

Parameters
  • circuit (Circuit) – The circuit to insert

  • j (int) – The layer index to replace.

Returns

Circuit

replace_gatename_inplace(self, old_gatename, new_gatename)

Changes the name of a gate throughout this Circuit.

Note that the name is only a part of the label identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.

Parameters
  • old_gatename (str) – The gate name to replace.

  • new_gatename (str) – The name to replace old_gatename with.

Returns

None

replace_gatename(self, old_gatename, new_gatename)

Returns a copy of this Circuit except that old_gatename is changed to new_gatename.

Note that the “name” is only a part of the “label” identifying each gate, and doesn’t include the lines (qubits) a gate acts upon. For example, the “Gx:0” and “Gx:1” labels both have the same name but act on different qubits.

Parameters
  • old_gatename (str) – The gate name to replace.

  • new_gatename (str) – The name to replace old_gatename with.

Returns

Circuit

replace_gatename_with_idle_inplace(self, gatename)

Treats a given gatename as an idle gate throughout this Circuit.

This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.

Parameters

gatename (str) – The gate name to replace.

Returns

None

replace_gatename_with_idle(self, gatename)

Returns a copy of this Circuit with a given gatename treated as an idle gate.

This effectively removes this gate name from the circuit, and replaces a layer containing only this gate name with an idle layer.

Parameters

gatename (str) – The gate name to replace.

Returns

Circuit

replace_layer(self, old_layer, new_layer)

Returns a copy of this Circuit except that old_layer is changed to new_layer.

Parameters
  • old_layer (str or Label) – The layer to find.

  • new_layer (str or Label) – The layer to replace found layers with.

Returns

Circuit

replace_layers_with_aliases(self, alias_dict)

Performs a find and replace using layer aliases.

Returns a copy of this Circuit except that it’s layers that match keys of alias_dict are replaced with the corresponding values.

Parameters

alias_dict (dict) – A dictionary whose keys are layer Labels (or equivalent tuples or strings), and whose values are Circuits.

Returns

Circuit

change_gate_library(self, compilation, allowed_filter=None, allow_unchanged_gates=False, depth_compression=True, one_q_gate_relations=None)

Re-express a circuit over a different model.

Parameters
  • compilation (dict or CompilationLibrary.) –

    If a dictionary, the keys are some or all of the gates that appear in the circuit, and the values are replacement circuits that are normally compilations for each of these gates (if they are not, the action of the circuit will be changed). The circuits need not be on all of the qubits, and need only satisfy the requirements of the insert_circuit method. There must be a key for every gate except the self.identity gate, unless allow_unchanged_gates is False. In that case, gate that aren’t a key in this dictionary are left unchanged.

    If a CompilationLibrary, this will be queried via the retrieve_compilation_of() method to find compilations for all of the gates in the circuit. So this CompilationLibrary must contain or be able to auto-generate compilations for the requested gates, except when allow_unchanged_gates is True. In that case, gates that a compilation is not returned for are left unchanged.

  • allowed_filter (dict or set, optional) – Specifies which gates are allowed to be used when generating compilations from compilation. Can only be not None if compilation is a CompilationLibrary. If a dict, keys must be gate names (like “Gcnot”) and values QubitGraph objects indicating where that gate (if it’s present in the library) may be used. If a set, then it specifies a set of qubits and any gate in the current library that is confined within that set is allowed. If None, then all gates within the library are allowed.

  • allow_unchanged_gates (bool, optional) – Whether to allow some gates to remain unchanged, and therefore to be absent from compilation. When True such gates are left alone; when False an error is raised if any such gates are encountered.

  • depth_compression (bool, optional) – Whether to perform depth compression after changing the gate library. If one_q_gate_relations is None this will only remove idle layers and compress the circuit by moving everything as far forward as is possible without knowledge of the action of any gates other than self.identity. See the depth_compression method for more details. Under most circumstances this should be true; if it is False changing gate library will often result in a massive increase in circuit depth.

  • one_q_gate_relations (dict, optional) – Gate relations for the one-qubit gates in the new gate library, that are used in the depth compression, to cancel / combine gates. E.g., one key-value pair might be (‘Gh’,’Gh’) : ‘I’, to signify that two Hadamards c ompose to the idle gate ‘Gi’. See the depth_compression() method for more details.

Returns

None

map_names_inplace(self, mapper)

The names of all of the simple labels are updated in-place according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing gate name values and whose values are the new names (strings) or a function which takes a single (existing name) argument and returns a new name.

Returns

None

map_state_space_labels_inplace(self, mapper)

The labels of all of the lines (wires/qubits) are updated according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing line-label) argument and returns a new line-label.

Returns

None

map_state_space_labels(self, mapper)

Creates a new Circuit whose line labels are updated according to the mapping function mapper.

Parameters

mapper (dict or function) – A dictionary whose keys are the existing self.line_labels values and whose value are the new labels, or a function which takes a single (existing line-label) argument and returns a new line-label.

Returns

Circuit

reorder_lines_inplace(self, order)

Reorders the lines (wires/qubits) of the circuit.

Note that the ordering of the lines is unimportant for most purposes.

Parameters

order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.

Returns

None

reorder_lines(self, order)

Reorders the lines (wires/qubits) of the circuit.

Note that the ordering of the lines is unimportant for most purposes.

Parameters

order (list) – A list containing all of the circuit line labels (self.line_labels) in the order that the should be converted to.

Returns

Circuit

_is_line_idling(self, line_label, idle_layer_labels=None)

Whether the line in question is idling in every circuit layer.

Parameters
  • line_label (str or int) – The label of the line (i.e., “wire” or qubit).

  • idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

bool – True if the line is idling. False otherwise.

idling_lines(self, idle_layer_labels=None)

Returns the line labels corresponding to idling lines.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

tuple

delete_idling_lines_inplace(self, idle_layer_labels=None)

Removes from this circuit all lines that are idling at every layer.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

None

delete_idling_lines(self, idle_layer_labels=None)

Removes from this circuit all lines that are idling at every layer.

Parameters

idle_layer_labels (iterable, optional) – A list or tuple of layer-labels that should be treated as idle operations, so their presence will not disqualify a line from being “idle”. E.g. [“Gi”] will cause “Gi” layers to be considered idle layers.

Returns

Circuit

replace_with_idling_line_inplace(self, line_label, clear_straddlers=True)

Converts the specified line to an idling line, by removing all its gates.

If there are any multi-qubit gates acting on this line, this function will raise an error when clear_straddlers=False.

Parameters
  • line_label (str or int) – The label of the line to convert to an idling line.

  • clear_straddlers (bool, optional) – Whether or not gates which straddle the line_label should also be cleared. If False and straddling gates exist, an error will be raised.

Returns

None

reverse_inplace(self)

Reverses the order of the circuit.

Returns

None

_combine_one_q_gates_inplace(self, one_q_gate_relations)

Compresses sequences of 1-qubit gates in the circuit, using the provided gate relations.

One of the steps of the depth_compression() method, and in most cases that method will be more useful.

Parameters

one_q_gate_relations (dict) –

Keys that are pairs of strings, corresponding to 1-qubit gate names, with values that are a single string, also corresponding to a 1-qubit gate name. Whenever a 1-qubit gate with name name1 is followed in the circuit by a 1-qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 -> name3 and name2 -> self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1-qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1-qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) -> name12, (name12,name3) -> name123 etc then the entire sequence of 1-qubit gates will be compressed into a single possibly non-idle 1-qubit gate followed by idle gates in place of the previous 1-qubit gates. Note that None can be used as name3 to signify that the result is the identity (no gate labels).

If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and auto-generated) one_q_gate_relations.

Note that this function will not compress sequences of 1-qubit gates that cannot be compressed by independently inspecting sequential non-idle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) -> Gypi, even though the sequence is the identity).

Returns

bool – False if the circuit is unchanged, and True otherwise.

_shift_gates_forward_inplace(self)

Shift all gates forward (left) as far as is possible.

This operation is performed without any knowledge of what any of the gates are. One of the steps of :method:`depth_compression()`.

Returns

bool – False if the circuit is unchanged, and True otherwise.

delete_idle_layers_inplace(self)

Deletes all layers in this circuit that contain no gate operations.

One of the steps of the depth_compression() method.

Returns

bool – False if the circuit is unchanged, and True otherwise.

compress_depth_inplace(self, one_q_gate_relations=None, verbosity=0)

Compresses the depth of this circuit using very simple re-write rules.

  1. If one_q_gate_relations is provided, all sequences of 1-qubit gates in the circuit are compressed as far as is possible using only the pair-wise combination rules provided by this dict (see below).

  2. All gates are shifted forwarded as far as is possible without any knowledge of what any of the gates are.

  3. All idle-only layers are deleted.

Parameters
  • one_q_gate_relations (dict) –

    Keys that are pairs of strings, corresponding to 1-qubit gate names, with values that are a single string, also corresponding to a 1-qubit gate name. Whenever a 1-qubit gate with name name1 is followed in the circuit by a 1-qubit gate with name2 then, if one_q_gate_relations[name1,name2] = name3, name1 -> name3 and name2 -> self.identity, the identity name in the circuit. Moreover, this is still implemented when there are self.identity gates between these 1-qubit gates, and it is implemented iteratively in the sense that if there is a sequence of 1-qubit gates with names name1, name2, name3, … and there are relations for all of (name1,name2) -> name12, (name12,name3) -> name123 etc then the entire sequence of 1-qubit gates will be compressed into a single possibly non-idle 1-qubit gate followed by idle gates in place of the previous 1-qubit gates.

    If a QubitProcessorSpec object has been created for the gates/device in question, the QubitProcessorSpec.oneQgate_relations is the appropriate (and auto-generated) one_q_gate_relations.

    Note that this function will not compress sequences of 1-qubit gates that cannot be compressed by independently inspecting sequential non-idle pairs (as would be the case with, for example, Gxpi Gzpi Gxpi Gzpi, if the relation did not know that (Gxpi,Gzpi) -> Gypi, even though the sequence is the identity).

  • verbosity (int, optional) – If > 0, information about the depth compression is printed to screen.

Returns

None

layer(self, j)

Returns a tuple of the components, i.e. the (non-identity) gates, in the layer at depth j.

These are the .components of the Label returned by indexing this Circuit (using square brackets) with j, i.e. this returns this_circuit[j].components.

Parameters

j (int) – The index (depth) of the layer to be returned

Returns

tuple

layer_label(self, j)

Returns the layer, as a Label, at depth j.

This label contains as components all the (non-identity) gates in the layer..

Parameters

j (int) – The index (depth) of the layer to be returned

Returns

Label

layer_with_idles(self, j, idle_gate_name='I')

Returns a tuple of the components of the layer at depth j, with idle_gate_name at empty circuit locations.

This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.

Parameters
  • j (int) – The index (depth) of the layer to be returned

  • idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a Label.

Returns

tuple

layer_label_with_idles(self, j, idle_gate_name='I')

Returns the layer, as a Label, at depth j, with idle_gate_name at empty circuit locations.

This effectively places an explicit idle_gate_name gates wherever there is an implied identity operation in the circuit.

Parameters
  • j (int) – The index (depth) of the layer to be returned

  • idle_gate_name (str, optional) – The idle gate name to use. Note that state space (qubit) labels will be added to this name to form a Label.

Returns

Label

property num_layers(self)

The number of circuit layers.

In simple circuits, this is the same as the depth (given by :method:`depth`). For circuits containing sub-circuit blocks, this gives the number of top-level layers in this circuit.

Returns

int

property depth(self)

The circuit depth.

This is the number of layers in simple circuits. For circuits containing sub-circuit blocks, this includes the full depth of these blocks. If you just want the number of top-level layers, use :method:`num_layers`.

Returns

int

property width(self)

The circuit width.

This is the number of qubits on which the circuit acts. This includes qubits that only idle, but are included as part of the circuit according to self.line_labels.

Returns

int

property size(self)

Returns the circuit size.

This is the sum of the sizes of all the gates in the circuit. A gate that acts on n-qubits has a size of n, with the exception of the idle which has a size of 0. Hence, the circuit is given by: size = depth * num_lines - num_1Q_idles.

Returns

int

property duration(self)
two_q_gate_count(self)

The number of two-qubit gates in the circuit.

(Note that this cannot distinguish between “true” 2-qubit gates and gate that have been defined to act on two qubits but that represent some tensor-product gate.)

Returns

int

num_nq_gates(self, nq)

The number of nq-qubit gates in the circuit.

(Note that this cannot distinguish between “true” nq-qubit gates and gate that have been defined to act on nq qubits but that represent some tensor-product gate.)

Parameters

nq (int) – The qubit-count of the gates to count. For example, if nq == 3, this function returns the number of 3-qubit gates.

Returns

int

property num_multiq_gates(self)

The number of multi-qubit (2+ qubits) gates in the circuit.

(Note that this cannot distinguish between “true” multi-qubit gates and gate that have been defined to act on more than one qubit but that represent some tensor-product gate.)

Returns

int

_togrid(self, identity_name)

return a list-of-lists rep?

__str__(self)

A text rendering of the circuit.

__repr__(self)

Return repr(self).

format_display_str(self, width=80)

Formats a string for displaying this circuit suject to a maximum width.

Parameters

width (int, optional) – The maximum width in characters. If the circuit is longer than this width it is wrapped using multiple lines (like a musical score).

Returns

str

_print_labelinfo(self)

A useful debug routine for printing the internal label structure of a circuit

abstract _write_q_circuit_tex(self, filename)

Writes a LaTeX file for rendering this circuit nicely.

Creates a file containing LaTex that will display this circuit using the Qcircuit.tex LaTex import (compiling the LaTex requires that you have the Qcircuit.tex file).

Parameters

filename (str) – The file to write the LaTex into. Should end with ‘.tex’

Returns

None

convert_to_cirq(self, qubit_conversion, wait_duration=None, gatename_conversion=None, idle_gate_name='Gi')

Converts this circuit to a Cirq circuit.

Parameters
  • qubit_conversion (dict) – Mapping from qubit labels (e.g. integers) to Cirq qubit objects.

  • wait_duration (cirq.Duration, optional) – If no gatename_conversion dict is given, the idle operation is not converted to a gate. If wait_diration is specified and gatename_conversion is not specified, then the idle operation will be converted to a cirq.WaitGate with the specified duration.

  • gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the Cirq gates that will appear in the Cirq circuit. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard Cirq names will be implemented.

  • idle_gate_name (str, optional) – Name to use for idle gates. Defaults to ‘Gi’

Returns

A Cirq Circuit object.

convert_to_quil(self, num_qubits=None, gatename_conversion=None, qubit_conversion=None, readout_conversion=None, block_between_layers=True, block_idles=True, gate_declarations=None)

Converts this circuit to a quil string.

Parameters
  • num_qubits (int, optional) – The number of qubits for the quil file. If None, then this is assumed to equal the number of line labels in this circuit.

  • gatename_conversion (dict, optional) – A dictionary mapping gate names contained in this circuit to the corresponding gate names used in the rendered quil. If None, a standard set of conversions is used (see :function:`standard_gatenames_quil_conversions`).

  • qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the quil output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).

  • readout_conversion (dict, optional) – If not None, a dictionary converting the qubit labels mapped through qubit_conversion to the bit labels for readot. E.g. Suppose only qubit 2 (on Rigetti hardware) is in use. Then the pyGSTi string will have only one qubit (labeled 0); it will get remapped to 2 via qubit_conversion={0:2}. At the end of the quil circuit, readout should go recorded in bit 0, so readout_conversion = {0:0}. (That is, qubit with pyGSTi label 0 gets read to Rigetti bit 0, even though that qubit has Rigetti label 2.)

  • block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such “pragma” blocks can be important for QCVV testing, as this can help reduce the “behind-the-scenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.

  • block_idles (bool, optional) – In the special case of global idle gates, pragma-block barriers are inserted even when block_between_layers=False. Set block_idles=False to disable this behavior, whcih typically results in global idle gates being removed by the compiler.

  • gate_declarations (dict, optional) – If not None, a dictionary that provides unitary maps for particular gates that are not already in the quil syntax.

Returns

str – A quil string.

convert_to_openqasm(self, num_qubits=None, standard_gates_version='u3', gatename_conversion=None, qubit_conversion=None, block_between_layers=True, block_between_gates=False, gateargs_map=None)

Converts this circuit to an openqasm string.

Parameters
  • num_qubits (int, optional) – The number of qubits for the openqasm file. If None, then this is assumed to equal the number of line labels in this circuit.

  • version (string, optional) – Either ‘u3’ or ‘x-sx-rz’. Specifies the naming convention for the QASM gates. With ‘u3’, all single-qubit gates are specified in terms of the ‘u3’ gate, used by IBM and QisKit until ~2021 (see the qasm_u3 function). With ‘x-sx-rz’, all single-gates are specified in terms of ‘x’ (an x pi rotation), ‘sx’ (an x pi/2 rotation) and ‘rz’ (a parameterized rotation around z by an angle theta).

  • gatename_conversion (dict, optional) – If not None, a dictionary that converts the gatenames in the circuit to the gatenames that will appear in the openqasm output. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gp’, ‘Gcnot’, ‘Gcphase’, etc) this dictionary need not be specified, and an automatic conversion to the standard openqasm names will be implemented.

  • qubit_conversion (dict, optional) – If not None, a dictionary converting the qubit labels in the circuit to the desired qubit labels in the openqasm output. Can be left as None if the qubit labels are either (1) integers, or (2) of the form ‘Qi’ for integer i. In this case they are converted to integers (i.e., for (1) the mapping is trivial, for (2) the mapping strips the ‘Q’).

  • block_between_layers (bool, optional) – When True, add in a barrier after every circuit layer. Including such barriers can be important for QCVV testing, as this can help reduce the “behind-the-scenes” compilation (beyond necessary conversion to native instructions) experience by the circuit.

  • gateargs_map (dict, optional) – If not None, a dict that maps strings (representing pyGSTi standard gate names) to functions that map the parameters of a pyGSTi gate to a string to be combined with the QASM name to specify the specific gate, in QASM. If only standard pyGSTi names are used (e.g., ‘Gh’, ‘Gzr’, ‘Gczr, etc) or none of the gates are parameterized, this dictionary need not be specified, and an automatic conversion to the standard openqasm format will be implemented.

Returns

str – An openqasm string.

simulate(self, model, return_all_outcomes=False)

Compute the outcome probabilities of this Circuit using model as a model for the gates.

The order of the outcome strings (e.g., ‘0100’) is w.r.t. to the ordering of the qubits in the circuit. That is, the ith element of the outcome string corresponds to the qubit with label self.line_labels[i].

Parameters
  • model (Model) – A description of the gate and SPAM operations corresponding to the labels stored in this Circuit. If this model is over more qubits than the circuit, the output will be the probabilities for the qubits in the circuit marginalized, if possible over the other qubits. But, the simulation is over the full set of qubits in the model, and so the time taken for the simulation scales with the number of qubits in the model. For models where “spectator” qubits do not affect the qubits in this circuit (such as with perfect gates), more efficient simulations will be obtained by first creating a model only over the qubits in this circuit.

  • return_all_outcomes (bool, optional) – Whether to include outcomes in the returned dictionary that have zero probability. When False, the threshold for discarding an outcome as z ero probability is 10^-12.

Returns

probs (dictionary) – A dictionary with keys equal to all (return_all_outcomes is True) or possibly only some (return_all_outcomes is False) of the possible outcomes, and values that are float probabilities.

done_editing(self)

Make this circuit read-only, so that it can be hashed (e.g. used as a dictionary key).

This is done automatically when attempting to hash a Circuit for the first time, so there’s calling this function can usually be skipped (but it’s good for code clarity).

Returns

None

expand_instruments_and_separate_povm(self, model, observed_outcomes=None)

Creates a dictionary of SeparatePOVMCircuit objects from expanding the instruments of this circuit.

Each key of the returned dictionary replaces the instruments in this circuit with a selection of their members. (The size of the resulting dictionary is the product of the sizes of each instrument appearing in this circuit when observed_outcomes is None). Keys are stored as SeparatePOVMCircuit objects so it’s easy to keep track of which POVM outcomes (effects) correspond to observed data. This function is, for the most part, used internally to process a circuit before computing its outcome probabilities.

Parameters

model (Model) –

The model used to provide necessary details regarding the expansion, including:

  • default SPAM layers

  • definitions of instrument-containing layers

  • expansions of individual instruments and POVMs

Returns

OrderedDict – A dict whose keys are SeparatePOVMCircuit objects and whose values are tuples of the outcome labels corresponding to this circuit, one per POVM effect held in the key.

class pygsti.io._CircuitParser(lexer_object=None, lookup={})

Bases: object

Parser for text-format operation sequences

tokens
mode = simple
_parse(self, code, create_subcircuits=True, integerize_sslbls=True)

Parse a circuit string

This method will dispatch to the optimized Cython implementation, if available. Otherwise, the slower native python implementation will be used.

property lookup(self)

The lookup dictionary for expanding references

p_strref(self, p)

strref : STRINGIND REFLBL

static p_slcref_slice(p)

slcref : strref OPENBR INTEGER COLON INTEGER CLOSEBR

static p_slcref(p)

slcref : strref

static p_subcircuit_singlelayer(p)

subcircuit : OPENBR layer CLOSEBR

static p_subcircuit_string(p)

subcircuit : LPAREN layer RPAREN

static p_layerable(p)

layerable : GATE | INSTRMT

static p_layerable_subcircuit(p)

layerable : subcircuit

static p_layerable_subcircuit_expop(p)

layerable : subcircuit EXPOP INTEGER

static p_layer_layerable(p)

layer : layerable

static p_layer_str(p)

layer : layer layerable

static p_layer(p)

layer : layer MULTOP layerable

static p_expable_paren(p)

expable : LPAREN string RPAREN

static p_expable_layer(p)

expable : OPENBR layer CLOSEBR

static p_expable_empty_layer(p)

expable : OPENBR CLOSEBR

static p_expable_single(p)

expable : GATE | INSTRMT | NOP

static p_expable(p)

expable : slcref

static p_expdstr_expop(p)

expdstr : expable EXPOP INTEGER

static p_expdstr(p)

expdstr : expable

static p_string_expdstr(p)

string : expdstr

static p_string_str(p)

string : string expdstr

static p_string(p)

string : string MULTOP expdstr

static p_pstring(p)

pstring : string

static p_pstring_prep(p)

pstring : PREP string

static p_ppstring(p)

ppstring : pstring

static p_ppstring_povm(p)

ppstring : pstring POVM

static p_error(p)
ply_parse(self, code, create_subcircuits=True)

Perform lexing and parsing of code.

Parameters

code (str) – A circuit encoded as a single-line string

Returns

  • layer_labels (tuple) – A tuple of the layer-labels of the circuit

  • line_labels (tuple) – A tuple of the line labels of the circuit.

class pygsti.io._DataSet(oli_data=None, time_data=None, rep_data=None, circuits=None, circuit_indices=None, outcome_labels=None, outcome_label_indices=None, static=False, file_to_load_from=None, collision_action='aggregate', comment=None, aux_info=None)

Bases: object

An association between Circuits and outcome counts, serving as the input data for many QCVV protocols.

The DataSet class associates circuits with counts or time series of counts for each outcome label, and can be thought of as a table with gate strings labeling the rows and outcome labels and/or time labeling the columns. It is designed to behave similarly to a dictionary of dictionaries, so that counts are accessed by:

count = dataset[circuit][outcomeLabel]

in the time-independent case, and in the time-dependent case, for integer time index i >= 0,

outcomeLabel = dataset[circuit][i].outcome count = dataset[circuit][i].count time = dataset[circuit][i].time

Parameters
  • oli_data (list or numpy.ndarray) – When static == True, a 1D numpy array containing outcome label indices (integers), concatenated for all sequences. Otherwise, a list of 1D numpy arrays, one array per gate sequence. In either case, this quantity is indexed by the values of circuit_indices or the index of circuits.

  • time_data (list or numpy.ndarray) – Same format at oli_data except stores floating-point timestamp values.

  • rep_data (list or numpy.ndarray) – Same format at oli_data except stores integer repetition counts for each “data bin” (i.e. (outcome,time) pair). If all repetitions equal 1 (“single-shot” timestampted data), then rep_data can be None (no repetitions).

  • circuits (list of (tuples or Circuits)) – Each element is a tuple of operation labels or a Circuit object. Indices for these strings are assumed to ascend from 0. These indices must correspond to the time series of spam-label indices (above). Only specify this argument OR circuit_indices, not both.

  • circuit_indices (ordered dictionary) – An OrderedDict with keys equal to circuits (tuples of operation labels) and values equal to integer indices associating a row/element of counts with the circuit. Only specify this argument OR circuits, not both.

  • outcome_labels (list of strings or int) – Specifies the set of spam labels for the DataSet. Indices for the spam labels are assumed to ascend from 0, starting with the first element of this list. These indices will associate each elememtn of timeseries with a spam label. Only specify this argument OR outcome_label_indices, not both. If an int, specifies that the outcome labels should be those for a standard set of this many qubits.

  • outcome_label_indices (ordered dictionary) – An OrderedDict with keys equal to spam labels (strings) and value equal to integer indices associating a spam label with given index. Only specify this argument OR outcome_labels, not both.

  • static (bool) –

    When True, create a read-only, i.e. “static” DataSet which cannot be modified. In

    this case you must specify the timeseries data, circuits, and spam labels.

    When False, create a DataSet that can have time series data added to it. In this case,

    you only need to specify the spam labels.

  • file_to_load_from (string or file object) – Specify this argument and no others to create a static DataSet by loading from a file (just like using the load(…) function).

  • collision_action ({"aggregate","overwrite","keepseparate"}) – Specifies how duplicate circuits should be handled. “aggregate” adds duplicate-circuit counts to the same circuit’s data at the next integer timestamp. “overwrite” only keeps the latest given data for a circuit. “keepseparate” tags duplicate-circuits by setting the .occurrence ID of added circuits that are already contained in this data set to the next available positive integer.

  • comment (string, optional) – A user-specified comment string that gets carried around with the data. A common use for this field is to attach to the data details regarding its collection.

  • aux_info (dict, optional) – A user-specified dictionary of per-circuit auxiliary information. Keys should be the circuits in this DataSet and value should be Python dictionaries.

__iter__(self)
__len__(self)
__contains__(self, circuit)

Test whether data set contains a given circuit.

Parameters

circuit (tuple or Circuit) – A tuple of operation labels or a Circuit instance which specifies the the circuit to check for.

Returns

bool – whether circuit was found.

__hash__(self)

Return hash(self).

__getitem__(self, circuit)
__setitem__(self, circuit, outcome_dict_or_series)
__delitem__(self, circuit)
_get_row(self, circuit)

Get a row of data from this DataSet.

Parameters

circuit (Circuit or tuple) – The gate sequence to extract data for.

Returns

_DataSetRow

_set_row(self, circuit, outcome_dict_or_series)

Set the counts for a row of this DataSet.

Parameters
  • circuit (Circuit or tuple) – The gate sequence to extract data for.

  • outcome_dict_or_series (dict or tuple) – The outcome count data, either a dictionary of outcome counts (with keys as outcome labels) or a tuple of lists. In the latter case this can be a 2-tuple: (outcome-label-list, timestamp-list) or a 3-tuple: (outcome-label-list, timestamp-list, repetition-count-list).

Returns

None

keys(self)

Returns the circuits used as keys of this DataSet.

Returns

list – A list of Circuit objects which index the data counts within this data set.

items(self)

Iterator over (circuit, timeSeries) pairs.

Here circuit is a tuple of operation labels and timeSeries is a _DataSetRow instance, which behaves similarly to a list of spam labels whose index corresponds to the time step.

Returns

_DataSetKVIterator

values(self)

Iterator over _DataSetRow instances corresponding to the time series data for each circuit.

Returns

_DataSetValueIterator

property outcome_labels(self)

Get a list of all the outcome labels contained in this DataSet.

Returns

list of strings or tuples – A list where each element is an outcome label (which can be a string or a tuple of strings).

property timestamps(self)

Get a list of all the (unique) timestamps contained in this DataSet.

Returns

list of floats – A list where each element is a timestamp.

gate_labels(self, prefix='G')

Get a list of all the distinct operation labels used in the circuits of this dataset.

Parameters

prefix (str) – Filter the circuit labels so that only elements beginning with this prefix are returned. None performs no filtering.

Returns

list of strings – A list where each element is a operation label.

degrees_of_freedom(self, circuits=None, method='present_outcomes-1', aggregate_times=True)

Returns the number of independent degrees of freedom in the data for the circuits in circuits.

Parameters
  • circuits (list of Circuits) – The list of circuits to count degrees of freedom for. If None then all of the DataSet’s strings are used.

  • method ({'all_outcomes-1', 'present_outcomes-1', 'tuned'}) – How the degrees of freedom should be computed. ‘all_outcomes-1’ takes the number of circuits and multiplies this by the total number of outcomes (the length of what is returned by outcome_labels()) minus one. ‘present_outcomes-1’ counts on a per-circuit basis the number of present (usually = non-zero) outcomes recorded minus one. ‘tuned’ should be the most accurate, as it accounts for low-N “Poisson bump” behavior, but it is not the default because it is still under development. For timestamped data, see aggreate_times below.

  • aggregate_times (bool, optional) – Whether counts that occur at different times should be tallied separately. If True, then even when counts occur at different times degrees of freedom are tallied on a per-circuit basis. If False, then counts occuring at distinct times are treated as independent of those an any other time, and are tallied separately. So, for example, if aggregate_times is False and a data row has 0- and 1-counts of 45 & 55 at time=0 and 42 and 58 at time=1 this row would contribute 2 degrees of freedom, not 1. It can sometimes be useful to set this to False when the DataSet holds coarse-grained data, but usually you want this to be left as True (especially for time-series data).

Returns

int

_collisionaction_update_circuit(self, circuit)
_add_explicit_repetition_counts(self)

Build internal repetition counts if they don’t exist already.

This method is usually unnecessary, as repetition counts are almost always build as soon as they are needed.

Returns

None

add_count_dict(self, circuit, count_dict, record_zero_counts=True, aux=None, update_ol=True)

Add a single circuit’s counts to this DataSet

Parameters
  • circuit (tuple or Circuit) – A tuple of operation labels specifying the circuit or a Circuit object

  • count_dict (dict) – A dictionary with keys = outcome labels and values = counts

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in this DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • aux (dict, optional) – A dictionary of auxiliary meta information to be included with this set of data counts (associated with circuit).

  • update_ol (bool, optional) – This argument is for internal use only and should be left as True.

Returns

None

add_count_list(self, circuit, outcome_labels, counts, record_zero_counts=True, aux=None, update_ol=True, unsafe=False)

Add a single circuit’s counts to this DataSet

Parameters
  • circuit (tuple or Circuit) – A tuple of operation labels specifying the circuit or a Circuit object

  • outcome_labels (list or tuple) – The outcome labels corresponding to counts.

  • counts (list or tuple) – The counts themselves.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in this DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • aux (dict, optional) – A dictionary of auxiliary meta information to be included with this set of data counts (associated with circuit).

  • update_ol (bool, optional) – This argument is for internal use only and should be left as True.

  • unsafe (bool, optional) – True means that outcome_labels is guaranteed to hold tuple-type outcome labels and never plain strings. Only set this to True if you know what you’re doing.

Returns

None

add_count_arrays(self, circuit, outcome_index_array, count_array, record_zero_counts=True, aux=None)

Add the outcomes for a single circuit, formatted as raw data arrays.

Parameters
  • circuit (Circuit) – The circuit to add data for.

  • outcome_index_array (numpy.ndarray) – An array of outcome indices, which must be values of self.olIndex (which maps outcome labels to indices).

  • count_array (numpy.ndarray) – An array of integer (or sometimes floating point) counts, one corresponding to each outcome index (element of outcome_index_array).

  • record_zero_counts (bool, optional) – Whether zero counts (zeros in count_array should be stored explicitly or not stored and inferred. Setting to False reduces the space taken by data sets containing lots of zero counts, but makes some objective function evaluations less precise.

  • aux (dict or None, optional) – If not None a dictionary of user-defined auxiliary information that should be associated with this circuit.

Returns

None

add_cirq_trial_result(self, circuit, trial_result, key)

Add a single circuit’s counts — stored in a Cirq TrialResult — to this DataSet

Parameters
  • circuit (tuple or Circuit) – A tuple of operation labels specifying the circuit or a Circuit object. Note that this must be a PyGSTi circuit — not a Cirq circuit.

  • trial_result (cirq.TrialResult) – The TrialResult to add

  • key (str) – The string key of the measurement. Set by cirq.measure.

Returns

None

add_raw_series_data(self, circuit, outcome_label_list, time_stamp_list, rep_count_list=None, overwrite_existing=True, record_zero_counts=True, aux=None, update_ol=True, unsafe=False)

Add a single circuit’s counts to this DataSet

Parameters
  • circuit (tuple or Circuit) – A tuple of operation labels specifying the circuit or a Circuit object

  • outcome_label_list (list) – A list of outcome labels (strings or tuples). An element’s index links it to a particular time step (i.e. the i-th element of the list specifies the outcome of the i-th measurement in the series).

  • time_stamp_list (list) – A list of floating point timestamps, each associated with the single corresponding outcome in outcome_label_list. Must be the same length as outcome_label_list.

  • rep_count_list (list, optional) – A list of integer counts specifying how many outcomes of type given by outcome_label_list occurred at the time given by time_stamp_list. If None, then all counts are assumed to be 1. When not None, must be the same length as outcome_label_list.

  • overwrite_existing (bool, optional) – Whether to overwrite the data for circuit (if it exists). If False, then the given lists are appended (added) to existing data.

  • record_zero_counts (bool, optional) – Whether zero-counts (elements of rep_count_list that are zero) are actually recorded (stored) in this DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • aux (dict, optional) – A dictionary of auxiliary meta information to be included with this set of data counts (associated with circuit).

  • update_ol (bool, optional) – This argument is for internal use only and should be left as True.

  • unsafe (bool, optional) – When True, don’t bother checking that outcome_label_list contains tuple-type outcome labels and automatically upgrading strings to 1-tuples. Only set this to True if you know what you’re doing and need the marginally faster performance.

Returns

None

_add_raw_arrays(self, circuit, oli_array, time_array, rep_array, overwrite_existing, record_zero_counts, aux)
update_ol(self)

Updates the internal outcome-label list in this dataset.

Call this after calling add_count_dict(…) or add_raw_series_data(…) with update_olIndex=False.

Returns

None

add_series_data(self, circuit, count_dict_list, time_stamp_list, overwrite_existing=True, record_zero_counts=True, aux=None)

Add a single circuit’s counts to this DataSet

Parameters
  • circuit (tuple or Circuit) – A tuple of operation labels specifying the circuit or a Circuit object

  • count_dict_list (list) – A list of dictionaries holding the outcome-label:count pairs for each time step (times given by time_stamp_list.

  • time_stamp_list (list) – A list of floating point timestamps, each associated with an entire dictionary of outcomes specified by count_dict_list.

  • overwrite_existing (bool, optional) – If True, overwrite any existing data for the circuit. If False, add the count data with the next non-negative integer timestamp.

  • record_zero_counts (bool, optional) – Whether zero-counts (elements of the dictionaries in count_dict_list that are zero) are actually recorded (stored) in this DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • aux (dict, optional) – A dictionary of auxiliary meta information to be included with this set of data counts (associated with circuit).

Returns

None

aggregate_outcomes(self, label_merge_dict, record_zero_counts=True)

Creates a DataSet which merges certain outcomes in this DataSet.

Used, for example, to aggregate a 2-qubit 4-outcome DataSet into a 1-qubit 2-outcome DataSet.

Parameters
  • label_merge_dict (dictionary) – The dictionary whose keys define the new DataSet outcomes, and whose items are lists of input DataSet outcomes that are to be summed together. For example, if a two-qubit DataSet has outcome labels “00”, “01”, “10”, and “11”, and we want to ‘’aggregate out’’ the second qubit, we could use label_merge_dict = {‘0’:[‘00’,’01’],’1’:[‘10’,’11’]}. When doing this, however, it may be better to use :function:`filter_qubits` which also updates the circuits.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned (merged) DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

Returns

merged_dataset (DataSet object) – The DataSet with outcomes merged according to the rules given in label_merge_dict.

aggregate_std_nqubit_outcomes(self, qubit_indices_to_keep, record_zero_counts=True)

Creates a DataSet which merges certain outcomes in this DataSet.

Used, for example, to aggregate a 2-qubit 4-outcome DataSet into a 1-qubit 2-outcome DataSet. This assumes that outcome labels are in the standard format whereby each qubit corresponds to a single ‘0’ or ‘1’ character.

Parameters
  • qubit_indices_to_keep (list) – A list of integers specifying which qubits should be kept, that is, not aggregated.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned (merged) DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

Returns

merged_dataset (DataSet object) – The DataSet with outcomes merged.

add_auxiliary_info(self, circuit, aux)

Add auxiliary meta information to circuit.

Parameters
  • circuit (tuple or Circuit) – A tuple of operation labels specifying the circuit or a Circuit object

  • aux (dict, optional) – A dictionary of auxiliary meta information to be included with this set of data counts (associated with circuit).

Returns

None

add_counts_from_dataset(self, other_data_set)

Append another DataSet’s data to this DataSet

Parameters

other_data_set (DataSet) – The dataset to take counts from.

Returns

None

add_series_from_dataset(self, other_data_set)

Append another DataSet’s series data to this DataSet

Parameters

other_data_set (DataSet) – The dataset to take time series data from.

Returns

None

property meantimestep(self)

The mean time-step, averaged over the time-step for each circuit and over circuits.

Returns

float

property has_constant_totalcounts_pertime(self)

True if the data for every circuit has the same number of total counts at every data collection time.

This will return True if there is a different number of total counts per circuit (i.e., after aggregating over time), as long as every circuit has the same total counts per time step (this will happen when the number of time-steps varies between circuit).

Returns

bool

property totalcounts_pertime(self)

Total counts per time, if this is constant over times and circuits.

When that doesn’t hold, an error is raised.

Returns

float or int

property has_constant_totalcounts(self)

True if the data for every circuit has the same number of total counts.

Returns

bool

property has_trivial_timedependence(self)

True if all the data in this DataSet occurs at time 0.

Returns

bool

__str__(self)

Return str(self).

to_str(self, mode='auto')

Render this DataSet as a string.

Parameters

mode ({"auto","time-dependent","time-independent"}) – Whether to display the data as time-series of outcome counts (“time-dependent”) or to report per-outcome counts aggregated over time (“time-independent”). If “auto” is specified, then the time-independent mode is used only if all time stamps in the DataSet are equal to zero (trivial time dependence).

Returns

str

truncate(self, list_of_circuits_to_keep, missing_action='raise')

Create a truncated dataset comprised of a subset of the circuits in this dataset.

Parameters
  • list_of_circuits_to_keep (list of (tuples or Circuits)) – A list of the circuits for the new returned dataset. If a circuit is given in this list that isn’t in the original data set, missing_action determines the behavior.

  • missing_action ({"raise","warn","ignore"}) – What to do when a string in list_of_circuits_to_keep is not in the data set (raise a KeyError, issue a warning, or do nothing).

Returns

DataSet – The truncated data set.

time_slice(self, start_time, end_time, aggregate_to_time=None)

Creates a DataSet by aggregating the counts within the [start_time,`end_time`) interval.

Parameters
  • start_time (float) – The starting time.

  • end_time (float) – The ending time.

  • aggregate_to_time (float, optional) – If not None, a single timestamp to give all the data in the specified range, resulting in time-independent DataSet. If None, then the original timestamps are preserved.

Returns

DataSet

split_by_time(self, aggregate_to_time=None)

Creates a dictionary of DataSets, each of which is a equal-time slice of this DataSet.

The keys of the returned dictionary are the distinct timestamps in this dataset.

Parameters

aggregate_to_time (float, optional) – If not None, a single timestamp to give all the data in each returned data set, resulting in time-independent `DataSet`s. If None, then the original timestamps are preserved.

Returns

OrderedDict – A dictionary of DataSet objects whose keys are the timestamp values of the original (this) data set in sorted order.

drop_zero_counts(self)

Creates a copy of this data set that doesn’t include any zero counts.

Returns

DataSet

process_times(self, process_times_array_fn)

Manipulate this DataSet’s timestamps according to processor_fn.

For example, using, the folloing process_times_array_fn would change the timestamps for each circuit to sequential integers.

``` def process_times_array_fn(times):

return list(range(len(times)))

```

Parameters

process_times_array_fn (function) – A function which takes a single array-of-timestamps argument and returns another similarly-sized array. This function is called, once per circuit, with the circuit’s array of timestamps.

Returns

DataSet – A new data set with altered timestamps.

process_circuits(self, processor_fn, aggregate=False)

Create a new data set by manipulating this DataSet’s circuits (keys) according to processor_fn.

The new DataSet’s circuits result from by running each of this DataSet’s circuits through processor_fn. This can be useful when “tracing out” qubits in a dataset containing multi-qubit data.

Parameters
  • processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit. This function may also return None, in which case the data for that string is deleted.

  • aggregate (bool, optional) – When True, aggregate the data for ciruits that processor_fn assigns to the same “new” circuit. When False, use the data from the last original circuit that maps to a given “new” circuit.

Returns

DataSet

process_circuits_inplace(self, processor_fn, aggregate=False)

Manipulate this DataSet’s circuits (keys) in-place according to processor_fn.

All of this DataSet’s circuits are updated by running each one through processor_fn. This can be useful when “tracing out” qubits in a dataset containing multi-qubit data.

Parameters
  • processor_fn (function) – A function which takes a single Circuit argument and returns another (or the same) Circuit. This function may also return None, in which case the data for that string is deleted.

  • aggregate (bool, optional) – When True, aggregate the data for ciruits that processor_fn assigns to the same “new” circuit. When False, use the data from the last original circuit that maps to a given “new” circuit.

Returns

None

remove(self, circuits, missing_action='raise')

Remove (delete) the data for circuits from this DataSet.

Parameters
  • circuits (iterable) – An iterable over Circuit-like objects specifying the keys (circuits) to remove.

  • missing_action ({"raise","warn","ignore"}) – What to do when a string in circuits is not in this data set (raise a KeyError, issue a warning, or do nothing).

Returns

None

_remove(self, gstr_indices)

Removes the data in indices given by gstr_indices

copy(self)

Make a copy of this DataSet.

Returns

DataSet

copy_nonstatic(self)

Make a non-static copy of this DataSet.

Returns

DataSet

done_adding_data(self)

Promotes a non-static DataSet to a static (read-only) DataSet.

This method should be called after all data has been added.

Returns

None

__getstate__(self)
__setstate__(self, state_dict)
save(self, file_or_filename)
write_binary(self, file_or_filename)

Write this data set to a binary-format file.

Parameters

file_or_filename (string or file object) – If a string, interpreted as a filename. If this filename ends in “.gz”, the file will be gzip compressed.

Returns

None

load(self, file_or_filename)
read_binary(self, file_or_filename)

Read a DataSet from a binary file, clearing any data is contained previously.

The file should have been created with :method:`DataSet.write_binary`

Parameters

file_or_filename (str or buffer) – The file or filename to load from.

Returns

None

rename_outcome_labels(self, old_to_new_dict)

Replaces existing output labels with new ones as per old_to_new_dict.

Parameters

old_to_new_dict (dict) – A mapping from old/existing outcome labels to new ones. Strings in keys or values are automatically converted to 1-tuples. Missing outcome labels are left unaltered.

Returns

None

add_std_nqubit_outcome_labels(self, nqubits)

Adds all the “standard” outcome labels (e.g. ‘0010’) on nqubits qubits.

This is useful to ensure that, even if not all outcomes appear in the data, that all are recognized as being potentially valid outcomes (and so attempts to get counts for these outcomes will be 0 rather than raising an error).

Parameters

nqubits (int) – The number of qubits. For example, if equal to 3 the outcome labels ‘000’, ‘001’, … ‘111’ are added.

Returns

None

add_outcome_labels(self, outcome_labels, update_ol=True)

Adds new valid outcome labels.

Ensures that all the elements of outcome_labels are stored as valid outcomes for circuits in this DataSet, adding new outcomes as necessary.

Parameters
  • outcome_labels (list or generator) – A list or generator of string- or tuple-valued outcome labels.

  • update_ol (bool, optional) – Whether to update internal mappings to reflect the new outcome labels. Leave this as True unless you really know what you’re doing.

Returns

None

auxinfo_dataframe(self, pivot_valuename=None, pivot_value=None, drop_columns=False)

Create a Pandas dataframe with aux-data from this dataset.

Parameters
  • pivot_valuename (str, optional) – If not None, the resulting dataframe is pivoted using pivot_valuename as the column whose values name the pivoted table’s column names. If None and pivot_value is not None,`”ValueName”` is used.

  • pivot_value (str, optional) – If not None, the resulting dataframe is pivoted such that values of the pivot_value column are rearranged into new columns whose names are given by the values of the pivot_valuename column. If None and pivot_valuename is not None,`”Value”` is used.

  • drop_columns (bool or list, optional) – A list of column names to drop (prior to performing any pivot). If True appears in this list or is given directly, then all constant-valued columns are dropped as well. No columns are dropped when drop_columns == False.

Returns

pandas.DataFrame

class pygsti.io._MultiDataSet(oli_dict=None, time_dict=None, rep_dict=None, circuit_indices=None, outcome_labels=None, outcome_label_indices=None, file_to_load_from=None, collision_actions=None, comment=None, comments=None, aux_info=None)

Bases: object

A collection of DataSets that hold data for the same circuits.

The MultiDataSet class allows for the combined access and storage of several static DataSets that contain the same circuits (in the same order) AND the same time-dependence structure (if applicable).

It is designed to behave similarly to a dictionary of DataSets, so that a DataSet is obtained by:

dataset = multiDataset[dataset_name]

where dataset_name may be a string OR a tuple.

Parameters
  • oli_dict (ordered dictionary, optional) – Keys specify dataset names. Values are 1D numpy arrays which specify outcome label indices. Each value is indexed by the values of circuit_indices.

  • time_dict (ordered dictionary, optional) – Same format as oli_dict except stores arrays of floating-point time stamp data.

  • rep_dict (ordered dictionary, optional) – Same format as oli_dict except stores arrays of integer repetition counts (can be None if there are no repetitions)

  • circuit_indices (ordered dictionary, optional) – An OrderedDict with keys equal to circuits (tuples of operation labels) and values equal to integer indices associating a row/element of counts with the circuit.

  • outcome_labels (list of strings) – Specifies the set of spam labels for the DataSet. Indices for the spam labels are assumed to ascend from 0, starting with the first element of this list. These indices will associate each elememtn of timeseries with a spam label. Only specify this argument OR outcome_label_indices, not both.

  • outcome_label_indices (ordered dictionary) – An OrderedDict with keys equal to spam labels (strings) and value equal to integer indices associating a spam label with given index. Only specify this argument OR outcome_labels, not both.

  • file_to_load_from (string or file object, optional) – Specify this argument and no others to create a MultiDataSet by loading from a file (just like using the load(…) function).

  • collision_actions (dictionary, optional) – Specifies how duplicate circuits should be handled for the data sets. Keys must match those of oli_dict and values are “aggregate” or “keepseparate”. See documentation for DataSet. If None, then “aggregate” is used for all sets by default.

  • comment (string, optional) – A user-specified comment string that gets carried around with the data. A common use for this field is to attach to the data details regarding its collection.

  • comments (dict, optional) – A user-specified dictionary of comments, one per dataset. Keys are dataset names (same as oli_dict keys).

  • aux_info (dict, optional) – A user-specified dictionary of per-circuit auxiliary information. Keys should be the circuits in this MultiDataSet and value should be Python dictionaries.

property outcome_labels(self)

Get a list of all the outcome labels contained in this MultiDataSet.

Returns

list of strings or tuples – A list where each element is an outcome label (which can be a string or a tuple of strings).

__iter__(self)
__len__(self)
__getitem__(self, dataset_name)
__setitem__(self, dataset_name, dataset)
__contains__(self, dataset_name)
keys(self)

A list of the keys (dataset names) of this MultiDataSet

Returns

list

items(self)

Iterator over (dataset name, DataSet) pairs.

values(self)

Iterator over DataSets corresponding to each dataset name.

datasets_aggregate(self, *dataset_names)

Generate a new DataSet by combining the outcome counts of multiple member Datasets.

Data with the same time-stamp and outcome are merged into a single “bin” in the returned DataSet.

Parameters

dataset_names (list of strs) – one or more dataset names.

Returns

DataSet – a single DataSet containing the summed counts of each of the data named by the parameters.

add_dataset(self, dataset_name, dataset, update_auxinfo=True)

Add a DataSet to this MultiDataSet.

The dataset must be static and conform with the circuits and time-dependent structure passed upon construction or those inherited from the first dataset added.

Parameters
  • dataset_name (string) – The name to give the added dataset (i.e. the key the new data set will be referenced by).

  • dataset (DataSet) – The data set to add.

  • update_auxinfo (bool, optional) – Whether the auxiliary information (if any exists) in dataset is added to the information already stored in this MultiDataSet.

Returns

None

__str__(self)

Return str(self).

copy(self)

Make a copy of this MultiDataSet

Returns

MultiDataSet

__getstate__(self)
__setstate__(self, state_dict)
save(self, file_or_filename)
write_binary(self, file_or_filename)

Write this MultiDataSet to a binary-format file.

Parameters

file_or_filename (file or string) – Either a filename or a file object. In the former case, if the filename ends in “.gz”, the file will be gzip compressed.

Returns

None

load(self, file_or_filename)
read_binary(self, file_or_filename)

Read a MultiDataSet from a file, clearing any data is contained previously.

The file should have been created with :method:`MultiDataSet.write_binary`

Parameters

file_or_filename (file or string) – Either a filename or a file object. In the former case, if the filename ends in “.gz”, the file will be gzip uncompressed as it is read.

Returns

None

add_auxiliary_info(self, circuit, aux)

Add auxiliary meta information to circuit.

Parameters
  • circuit (tuple or Circuit) – A tuple of operation labels specifying the circuit or a Circuit object

  • aux (dict, optional) – A dictionary of auxiliary meta information to be included with this set of data counts (associated with circuit).

Returns

None

pygsti.io._global_parse_cache
pygsti.io._create_display_progress_fn(show_progress)

Create and return a progress-displaying function.

Only return a function that does somethign if show_progress == True and the current environment is interactive. Otherwise, return a do-nothing function.

Parameters

show_progress (bool) – Whether or not to even try to get a real progress-displaying function.

Returns

function

class pygsti.io.StdInputParser

Bases: object

Encapsulates a text parser for reading GST input files.

_circuit_parser
use_global_parse_cache = True
parse_circuit(self, s, lookup={}, create_subcircuits=True)

Parse a circuit from a string.

Parameters
  • s (string) – The string to parse.

  • lookup (dict, optional) – A dictionary with keys == reflbls and values == tuples of operation labels which can be used for substitutions using the S<reflbl> syntax.

  • create_subcircuits (bool, optional) – Whether to create sub-circuit-labels when parsing string representations or to just expand these into non-subcircuit labels.

Returns

Circuit

parse_circuit_raw(self, s, lookup={}, create_subcircuits=True)

Parse a circuit’s constituent pieces from a string.

This doesn’t actually create a circuit object, which may be desirable in some scenarios.

Parameters
  • s (string) – The string to parse.

  • lookup (dict, optional) – A dictionary with keys == reflbls and values == tuples of operation labels which can be used for substitutions using the S<reflbl> syntax.

  • create_subcircuits (bool, optional) – Whether to create sub-circuit-labels when parsing string representations or to just expand these into non-subcircuit labels.

Returns

  • label_tuple (tuple) – Tuple of operation labels representing the circuit’s layers.

  • line_labels (tuple or None) – A tuple or None giving the parsed line labels (follwing the ‘@’ symbol) of the circuit.

  • occurrence_id (int or None) – The “occurence id” - an integer following a second ‘@’ symbol that identifies a particular copy of this circuit.

  • compilable_indices (tuple or None) – A tuple of layer indices (into label_tuple) marking the layers that can be “compiled”, and are not followed by a barrier so they can be compiled with following layers. This is non-None only when there are explicit markers within the circuit string indicating the presence or absence of barriers.

parse_dataline(self, s, lookup={}, expected_counts=- 1, create_subcircuits=True, line_labels=None)

Parse a data line (dataline in grammar)

Parameters
  • s (string) – The string to parse.

  • lookup (dict, optional) – A dictionary with keys == reflbls and values == tuples of operation labels which can be used for substitutions using the S<reflbl> syntax.

  • expected_counts (int, optional) – The expected number of counts to accompany the circuit on this data line. If < 0, no check is performed; otherwise raises ValueError if the number of counts does not equal expected_counts.

  • create_subcircuits (bool, optional) – Whether to create sub-circuit-labels when parsing string representations or to just expand these into non-subcircuit labels.

Returns

  • circuit (Circuit) – The circuit.

  • counts (list) – List of counts following the circuit.

parse_dictline(self, s)

Parse a circuit dictionary line (dictline in grammar)

Parameters

s (string) – The string to parse.

Returns

  • circuitLabel (string) – The user-defined label to represent this circuit.

  • circuitTuple (tuple) – The circuit as a tuple of operation labels.

  • circuitStr (string) – The circuit as represented as a string in the dictline.

  • circuitLineLabels (tuple) – The line labels of the cirucit.

  • occurrence (object) – Circuit’s occurrence id, or None if there is none.

  • compilable_indices (tuple or None) – A tuple of layer indices (into label_tuple) marking the layers that can be “compiled”, and are not followed by a barrier so they can be compiled with following layers. This is non-None only when there are explicit markers within the circuit string indicating the presence or absence of barriers.

parse_stringfile(self, filename, line_labels='auto', num_lines=None, create_subcircuits=True)

Parse a circuit list file.

Parameters
  • filename (string) – The file to parse.

  • line_labels (iterable, optional) – The (string valued) line labels used to initialize Circuit objects when line label information is absent from the one-line text representation contained in filename. If ‘auto’, then line labels are taken to be the list of all state-space labels present in the circuit’s layers. If there are no such labels then the special value ‘*’ is used as a single line label.

  • num_lines (int, optional) – Specify this instead of line_labels to set the latter to the integers between 0 and num_lines-1.

  • create_subcircuits (bool, optional) – Whether to create sub-circuit-labels when parsing string representations or to just expand these into non-subcircuit labels.

Returns

list of Circuits – The circuits read from the file.

parse_dictfile(self, filename)

Parse a circuit dictionary file.

Parameters

filename (string) – The file to parse.

Returns

dict – Dictionary with keys == circuit labels and values == Circuits.

parse_datafile(self, filename, show_progress=True, collision_action='aggregate', record_zero_counts=True, ignore_zero_count_lines=True, with_times='auto')

Parse a data set file into a DataSet object.

Parameters
  • filename (string) – The file to parse.

  • show_progress (bool, optional) – Whether or not progress should be displayed

  • collision_action ({"aggregate", "keepseparate"}) – Specifies how duplicate circuits should be handled. “aggregate” adds duplicate-circuit counts, whereas “keepseparate” tags duplicate circuits by setting their .occurrence IDs to sequential positive integers.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • ignore_zero_count_lines (bool, optional) – Whether circuits for which there are no counts should be ignored (i.e. omitted from the DataSet) or not.

  • with_times (bool or "auto", optional) – Whether to the time-stamped data format should be read in. If “auto”, then this format is allowed but not required. Typically you only need to set this to False when reading in a template file.

Returns

DataSet – A static DataSet object.

parse_multidatafile(self, filename, show_progress=True, collision_action='aggregate', record_zero_counts=True, ignore_zero_count_lines=True)

Parse a multiple data set file into a MultiDataSet object.

Parameters
  • filename (string) – The file to parse.

  • show_progress (bool, optional) – Whether or not progress should be displayed

  • collision_action ({"aggregate", "keepseparate"}) – Specifies how duplicate circuits should be handled. “aggregate” adds duplicate-circuit counts, whereas “keepseparate” tags duplicate circuits by setting their .occurrence IDs to sequential positive integers.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned MultiDataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • ignore_zero_count_lines (bool, optional) – Whether circuits for which there are no counts should be ignored (i.e. omitted from the MultiDataSet) or not.

Returns

MultiDataSet – A MultiDataSet object.

_extract_labels_from_multi_data_col_labels(self, col_labels)
_fill_multi_data_count_dicts(self, count_dicts, fill_info, col_values)
parse_tddatafile(self, filename, show_progress=True, record_zero_counts=True, create_subcircuits=True)

Parse a timstamped data set file into a DataSet object.

Parameters
  • filename (string) – The file to parse.

  • show_progress (bool, optional) – Whether or not progress should be displayed

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • create_subcircuits (bool, optional) – Whether to create sub-circuit-labels when parsing string representations or to just expand these into non-subcircuit labels.

Returns

DataSet – A static DataSet object.

pygsti.io._eval_element(el, b_complex)
pygsti.io._eval_row_list(rows, b_complex)
pygsti.io.parse_model(filename)

Parse a model file into a Model object.

Parameters

filename (string) – The file to parse.

Returns

Model

pygsti.io._deprecated_fn(replacement=None)

Decorator for deprecating a function.

Parameters

replacement (str, optional) – the name of the function that should replace it.

Returns

function

pygsti.io.write_empty_dataset(filename, circuits, header_string='## Columns = 1 frequency, count total', num_zero_cols=None, append_weights_column=False)

Write an empty dataset file to be used as a template.

Parameters
  • filename (string) – The filename to write.

  • circuits (list of Circuits) – List of circuits to write, each to be followed by num_zero_cols zeros.

  • header_string (string, optional) – Header string for the file; should start with a pound (#) or double-pound (##) so it is treated as a commend or directive, respectively.

  • num_zero_cols (int, optional) – The number of zero columns to place after each circuit. If None, then header_string must begin with “## Columns = ” and number of zero columns will be inferred.

  • append_weights_column (bool, optional) – Add an additional ‘weights’ column.

Returns

None

pygsti.io._outcome_to_str(x)
pygsti.io.write_dataset(filename, dataset, circuits=None, outcome_label_order=None, fixed_column_mode='auto', with_times='auto')

Write a text-formatted dataset file.

Parameters
  • filename (string) – The filename to write.

  • dataset (DataSet) – The data set from which counts are obtained.

  • circuits (list of Circuits, optional) – The list of circuits to include in the written dataset. If None, all circuits are output.

  • outcome_label_order (list, optional) – A list of the outcome labels in dataset which specifies the column order in the output file.

  • fixed_column_mode (bool or 'auto', optional) – When True, a file is written with column headers indicating which outcome each column of counts corresponds to. If a row doesn’t have any counts for an outcome, ‘–’ is used in its place. When False, each row’s counts are written in an expanded form that includes the outcome labels (each “count” has the format <outcomeLabel>:<count>).

  • with_times (bool or "auto", optional) – Whether to include (save) time-stamp information in output. This can only be True when fixed_column_mode=False. “auto” will set this to True if fixed_column_mode=False and dataset has data at non-trivial (non-zero) times.

Returns

None

pygsti.io.write_multidataset(filename, multidataset, circuits=None, outcome_label_order=None)

Write a text-formatted multi-dataset file.

Parameters
  • filename (string) – The filename to write.

  • multidataset (MultiDataSet) – The multi data set from which counts are obtained.

  • circuits (list of Circuits) – The list of circuits to include in the written dataset. If None, all circuits are output.

  • outcome_label_order (list, optional) – A list of the SPAM labels in multidataset which specifies the column order in the output file.

Returns

None

pygsti.io.write_circuit_list(filename, circuits, header=None)

Write a text-formatted circuit list file.

Parameters
  • filename (string) – The filename to write.

  • circuits (list of Circuits) – The list of circuits to include in the written dataset.

  • header (string, optional) – Header line (first line of file). Prepended with a pound sign (#), so no need to include one.

Returns

None

pygsti.io.write_model(model, filename, title=None)

Write a text-formatted model file.

Parameters
  • model (Model) – The model to write to file.

  • filename (string) – The filename to write.

  • title (string, optional) – Header line (first line of file). Prepended with a pound sign (#), so no need to include one.

Returns

None

pygsti.io.write_empty_protocol_data(dirname, edesign, sparse='auto', clobber_ok=False)

Write to disk an empty ProtocolData object.

Write to a directory an experimental design (edesign) and the dataset template files needed to load in a ProtocolData object, e.g. using the :function:`read_data_from_dir` function, after the template files are filled in.

Parameters
  • dirname (str) – The root directory to write into. This directory will have ‘edesign’ and ‘data’ subdirectories created beneath it.

  • edesign (ExperimentDesign) – The experiment design defining the circuits that need to be performed.

  • sparse (bool or "auto", optional) – If True, then the template data set(s) are written in a sparse-data format, i.e. in a format where not all the outcomes need to be given. If False, then a dense data format is used, where counts for all possible bit strings are given. “auto” causes the sparse format to be used when the number of qubits is > 2.

  • clobber_ok (bool, optional) – If True, then a template dataset file will be written even if a file of the same name already exists (this may overwrite existing data with an empty template file, so be careful!).

Returns

None

pygsti.io.fill_in_empty_dataset_with_fake_data(dataset_filename, model, num_samples, sample_error='multinomial', seed=None, rand_state=None, alias_dict=None, collision_action='aggregate', record_zero_counts=True, comm=None, mem_limit=None, times=None, fixed_column_mode='auto')

Fills in the text-format data set file dataset_fileame with simulated data counts using model.

Parameters
  • dataset_filename (str) – the path to the text-formatted data set file.

  • model (Model) – the model to use to simulate the data.

  • num_samples (int or list of ints or None) – The simulated number of samples for each circuit. This only has effect when sample_error == "binomial" or "multinomial". If an integer, all circuits have this number of total samples. If a list, integer elements specify the number of samples for the corresponding circuit. If None, then model_or_dataset must be a DataSet, and total counts are taken from it (on a per-circuit basis).

  • sample_error (string, optional) –

    What type of sample error is included in the counts. Can be:

    • ”none” - no sample error: counts are floating point numbers such that the exact probabilty can be found by the ratio of count / total.

    • ”clip” - no sample error, but clip probabilities to [0,1] so, e.g., counts are always positive.

    • ”round” - same as “clip”, except counts are rounded to the nearest integer.

    • ”binomial” - the number of counts is taken from a binomial distribution. Distribution has parameters p = (clipped) probability of the circuit and n = number of samples. This can only be used when there are exactly two SPAM labels in model_or_dataset.

    • ”multinomial” - counts are taken from a multinomial distribution. Distribution has parameters p_k = (clipped) probability of the gate string using the k-th SPAM label and n = number of samples.

  • seed (int, optional) – If not None, a seed for numpy’s random number generator, which is used to sample from the binomial or multinomial distribution.

  • rand_state (numpy.random.RandomState) – A RandomState object to generate samples from. Can be useful to set instead of seed if you want reproducible distribution samples across multiple random function calls but you don’t want to bother with manually incrementing seeds between those calls.

  • alias_dict (dict, optional) – A dictionary mapping single operation labels into tuples of one or more other operation labels which translate the given circuits before values are computed using model_or_dataset. The resulting Dataset, however, contains the un-translated circuits as keys.

  • collision_action ({"aggregate", "keepseparate"}) – Determines how duplicate circuits are handled by the resulting DataSet. Please see the constructor documentation for DataSet.

  • record_zero_counts (bool, optional) – Whether zero-counts are actually recorded (stored) in the returned DataSet. If False, then zero counts are ignored, except for potentially registering new outcome labels.

  • comm (mpi4py.MPI.Comm, optional) – When not None, an MPI communicator for distributing the computation across multiple processors and ensuring that the same dataset is generated on each processor.

  • mem_limit (int, optional) – A rough memory limit in bytes which is used to determine job allocation when there are multiple processors.

  • times (iterable, optional) – When not None, a list of time-stamps at which data should be sampled. num_samples samples will be simulated at each time value, meaning that each circuit in circuits will be evaluated with the given time value as its start time.

  • fixed_column_mode (bool or 'auto', optional) – How the underlying data set file is written - see :function:`write_dataset`.

Returns

DataSet – The generated data set (also written in place of the template file).

pygsti.io.write_circuit_strings(filename, obj)

TODO: docstring - write various Circuit-containing standard objects with circuits replaced by their string reps