def update(self, teamId, name=None, **request_parameters):

check_type(teamId, basestring, may_be_none=False)<EOL>check_type(name, basestring)<EOL>put_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>name=name,<EOL>)<EOL>json_data = self._session.put(API_ENDPOINT + '<STR_LIT:/>' + teamId,<EOL>json=put_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Update details for a team, by ID.

        Args:
            teamId(basestring): The team ID.
            name(basestring): A user-friendly name for the team.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Team: A Team object with the updated Webex Teams team details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(orgId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + orgId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get the details of an Organization, by ID.

        Args:
            orgId(basestring): The ID of the Organization to be retrieved.

        Returns:
            Organization: An Organization object with the details of the
            requested organization.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def __init__(self, session, object_factory):

check_type(session, RestSession)<EOL>super(GuestIssuerAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Initialize a new GuestIssuerAPI object with the provided RestSession

        Args:
            session(RestSession): The RESTful session object to be used for
            API calls to the Webex Teams service

        Raises:
            TypeError: If the parameter types are incorrect


@generator_container<EOL><INDENT>def list(self, teamId=None, type=None, sortBy=None, max=None,<EOL>**request_parameters):<DEDENT>

check_type(teamId, basestring)<EOL>check_type(type, basestring)<EOL>check_type(sortBy, basestring)<EOL>check_type(max, int)<EOL>params = dict_from_items_with_values(<EOL>request_parameters,<EOL>teamId=teamId,<EOL>type=type,<EOL>sortBy=sortBy,<EOL>max=max,<EOL>)<EOL>items = self._session.get_items(API_ENDPOINT, params=params)<EOL>for item in items:<EOL><INDENT>yield self._object_factory(OBJECT_TYPE, item)<EOL><DEDENT>

List rooms.

        By default, lists rooms to which the authenticated user belongs.

        This method supports Webex Teams's implementation of RFC5988 Web
        Linking to provide pagination support.  It returns a generator
        container that incrementally yields all rooms returned by the
        query.  The generator will automatically request additional 'pages' of
        responses from Webex as needed until all responses have been returned.
        The container makes the generator safe for reuse.  A new API call will
        be made, using the same parameters that were specified when the
        generator was created, every time a new iterator is requested from the
        container.

        Args:
            teamId(basestring): Limit the rooms to those associated with a
                team, by ID.
            type(basestring): 'direct' returns all 1-to-1 rooms. `group`
                returns all group rooms. If not specified or values not
                matched, will return all room types.
            sortBy(basestring): Sort results by room ID (`id`), most recent
                activity (`lastactivity`), or most recently created
                (`created`).
            max(int): Limit the maximum number of items returned from the Webex
                Teams service per request.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            GeneratorContainer: A GeneratorContainer which, when iterated,
            yields the rooms returned by the Webex Teams query.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def update(self, roomId, title=None, **request_parameters):

check_type(roomId, basestring, may_be_none=False)<EOL>check_type(roomId, basestring)<EOL>put_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>title=title,<EOL>)<EOL>json_data = self._session.put(API_ENDPOINT + '<STR_LIT:/>' + roomId,<EOL>json=put_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Update details for a room, by ID.

        Args:
            roomId(basestring): The room ID.
            title(basestring): A user-friendly name for the room.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Room: A Room object with the updated Webex Teams room details.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(eventId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + eventId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get the details for an event, by event ID.

        Args:
            eventId(basestring): The ID of the event to be retrieved.

        Returns:
            Event: A event object with the details of the requested room.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(session, RestSession, may_be_none=False)<EOL>super(EventsAPI, self).__init__()<EOL>self._session = session<EOL>self._object_factory = object_factory<EOL>

Initialize a new EventsAPI object with the provided RestSession.

        Args:
            session(RestSession): The RESTful session object to be used for
                API calls to the Webex Teams service.

        Raises:
            TypeError: If the parameter types are incorrect.


check_type(membershipId, basestring)<EOL>self._session.delete(API_ENDPOINT + '<STR_LIT:/>' + membershipId)<EOL>

Delete a membership, by ID.

        Args:
            membershipId(basestring): The membership ID.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


check_type(membershipId, basestring, may_be_none=False)<EOL>json_data = self._session.get(API_ENDPOINT + '<STR_LIT:/>' + membershipId)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Get details for a membership, by ID.

        Args:
            membershipId(basestring): The membership ID.

        Returns:
            Membership: A Membership object with the details of the requested
            membership.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


def create(self, roomId, personId=None, personEmail=None,<EOL>isModerator=False, **request_parameters):

check_type(roomId, basestring, may_be_none=False)<EOL>check_type(personId, basestring)<EOL>check_type(personEmail, basestring)<EOL>check_type(isModerator, bool)<EOL>post_data = dict_from_items_with_values(<EOL>request_parameters,<EOL>roomId=roomId,<EOL>personId=personId,<EOL>personEmail=personEmail,<EOL>isModerator=isModerator,<EOL>)<EOL>json_data = self._session.post(API_ENDPOINT, json=post_data)<EOL>return self._object_factory(OBJECT_TYPE, json_data)<EOL>

Add someone to a room by Person ID or email address.

        Add someone to a room by Person ID or email address; optionally
        making them a moderator.

        Args:
            roomId(basestring): The room ID.
            personId(basestring): The ID of the person.
            personEmail(basestring): The email address of the person.
            isModerator(bool): Set to True to make the person a room moderator.
            **request_parameters: Additional request parameters (provides
                support for parameters that may be added in the future).

        Returns:
            Membership: A Membership object with the details of the created
            membership.

        Raises:
            TypeError: If the parameter types are incorrect.
            ApiError: If the Webex Teams cloud returns an error.


return self._base_url<EOL>


return self._req_session.headers.copy()<EOL>

The HTTP headers used for requests in this session.


def post(self, url, json=None, data=None, **kwargs):

check_type(url, basestring, may_be_none=False)<EOL>erc = kwargs.pop('<STR_LIT>', EXPECTED_RESPONSE_CODE['<STR_LIT:POST>'])<EOL>response = self.request('<STR_LIT:POST>', url, erc, json=json, data=data,<EOL>**kwargs)<EOL>return extract_and_parse_json(response)<EOL>

Sends a POST request.

        Args:
            url(basestring): The URL of the API endpoint.
            json: Data to be sent in JSON format in tbe body of the request.
            data: Data to be sent in the body of the request.
            **kwargs:
                erc(int): The expected (success) response code for the request.
                others: Passed on to the requests package.

        Raises:
            ApiError: If anything other than the expected response code is
                returned by the Webex Teams API endpoint.


check_type(value, bool, may_be_none=False)<EOL>self._wait_on_rate_limit = value<EOL>

Enable or disable automatic rate-limit handling.


assert isinstance(string, basestring)<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>if isinstance(string, str):<EOL><INDENT>return string.encode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>return string<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(string, unicode):<EOL><INDENT>return string.encode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>return string<EOL><DEDENT><DEDENT>

Convert a string (bytes, str or unicode) to bytes.


dt = self.astimezone(ZuluTimeZone())<EOL>return dt.strftime("<STR_LIT>").format(<EOL>self.microsecond // <NUM_LIT:1000><EOL>)<EOL>

Human readable string representation of this WebexTeamsDateTime.


return timedelta(<NUM_LIT:0>)<EOL>


api = WebexTeamsAPI()<EOL>delete_webhooks_with_name(api, name=WEBHOOK_NAME)<EOL>public_url = get_ngrok_public_url()<EOL>if public_url is not None:<EOL><INDENT>create_ngrok_webhook(api, public_url)<EOL><DEDENT>

Delete previous webhooks. If local ngrok tunnel, create a webhook.


<EOL>json_data = request.json<EOL>log.info("<STR_LIT:\n>")<EOL>log.info("<STR_LIT>")<EOL>log.info(json_data)<EOL>log.info("<STR_LIT:\n>")<EOL>webhook_obj = Webhook(json_data)<EOL>room = api.rooms.get(webhook_obj.data.roomId)<EOL>message = api.messages.get(webhook_obj.data.id)<EOL>person = api.people.get(message.personId)<EOL>log.info("<STR_LIT>".format(room.title))<EOL>log.info("<STR_LIT>".format(person.displayName))<EOL>log.info("<STR_LIT>".format(message.text))<EOL>me = api.people.me()<EOL>if message.personId == me.id:<EOL><INDENT>return {'<STR_LIT>': '<STR_LIT:OK>'}<EOL><DEDENT>else:<EOL><INDENT>if "<STR_LIT>" in message.text:<EOL><INDENT>log.info("<STR_LIT>")<EOL>catfact = get_catfact()<EOL>log.info("<STR_LIT>".format(catfact))<EOL>api.messages.create(room.id, text=catfact)<EOL><DEDENT>return {'<STR_LIT>': '<STR_LIT:OK>'}<EOL><DEDENT>

Respond to inbound webhook JSON HTTP POST from Webex Teams.


found = set()<EOL>setters = False<EOL>errors = <NUM_LIT:0><EOL>with open("<STR_LIT>", "<STR_LIT:r>") as f:<EOL><INDENT>for line in f.readlines():<EOL><INDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT><DEDENT><DEDENT>if len(found) != <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>if setters:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>return errors<EOL>

Validate the contents of setup.py against Versioneer's expectations.


if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>cmds = {}<EOL>from distutils.core import Command<EOL>class cmd_version(Command):<EOL><INDENT>description = "<STR_LIT>"<EOL>user_options = []<EOL>boolean_options = []<EOL>def initialize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def finalize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def run(self):<EOL><INDENT>vers = get_versions(verbose=True)<EOL>print("<STR_LIT>" % vers["<STR_LIT:version>"])<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT:date>"))<EOL>if vers["<STR_LIT:error>"]:<EOL><INDENT>print("<STR_LIT>" % vers["<STR_LIT:error>"])<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT:version>"] = cmd_version<EOL>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.build_py import build_py as _build_py<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.build_py import build_py as _build_py<EOL><DEDENT>class cmd_build_py(_build_py):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>_build_py.run(self)<EOL>if cfg.versionfile_build:<EOL><INDENT>target_versionfile = os.path.join(self.build_lib,<EOL>cfg.versionfile_build)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_py<EOL>if "<STR_LIT>" in sys.modules:  <EOL><INDENT>from cx_Freeze.dist import build_exe as _build_exe<EOL>class cmd_build_exe(_build_exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_build_exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_exe<EOL>del cmds["<STR_LIT>"]<EOL><DEDENT>if '<STR_LIT>' in sys.modules:  <EOL><INDENT>try:<EOL><INDENT>from py2exe.distutils_buildexe import py2exe as _py2exe  <EOL><DEDENT>except ImportError:<EOL><INDENT>from py2exe.build_exe import py2exe as _py2exe  <EOL><DEDENT>class cmd_py2exe(_py2exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_py2exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_py2exe<EOL><DEDENT>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.sdist import sdist as _sdist<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.sdist import sdist as _sdist<EOL><DEDENT>class cmd_sdist(_sdist):<EOL><INDENT>def run(self):<EOL><INDENT>versions = get_versions()<EOL>self._versioneer_generated_versions = versions<EOL>self.distribution.metadata.version = versions["<STR_LIT:version>"]<EOL>return _sdist.run(self)<EOL><DEDENT>def make_release_tree(self, base_dir, files):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>_sdist.make_release_tree(self, base_dir, files)<EOL>target_versionfile = os.path.join(base_dir, cfg.versionfile_source)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile,<EOL>self._versioneer_generated_versions)<EOL><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_sdist<EOL>return cmds<EOL>

Get the custom setuptools/distutils subclasses used by Versioneer.


try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL><DEDENT>if not mo:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return json.loads(mo.group(<NUM_LIT:1>))<EOL>

Try to determine the version from _version.py if present.


return get_versions()["<STR_LIT:version>"]<EOL>

Get the short version string for this project.


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>

Extract version information from the given file.


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL>

Write the given version number to the given _version.py file.


<EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>")  <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>return parser.get("<STR_LIT>", name)<EOL><DEDENT>return None<EOL><DEDENT>cfg = VersioneerConfig()<EOL>cfg.VCS = VCS<EOL>cfg.style = get(parser, "<STR_LIT>") or "<STR_LIT>"<EOL>cfg.versionfile_source = get(parser, "<STR_LIT>")<EOL>cfg.versionfile_build = get(parser, "<STR_LIT>")<EOL>cfg.tag_prefix = get(parser, "<STR_LIT>")<EOL>if cfg.tag_prefix in ("<STR_LIT>", '<STR_LIT>'):<EOL><INDENT>cfg.tag_prefix = "<STR_LIT>"<EOL><DEDENT>cfg.parentdir_prefix = get(parser, "<STR_LIT>")<EOL>cfg.verbose = get(parser, "<STR_LIT>")<EOL>return cfg<EOL>

Read the project setup.cfg file to determine Versioneer config.


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):

if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information from git keywords.


self._repo = repository<EOL>self._api = Github(token)<EOL>

Args:
    repository (str): a string in the form 'owner/repository-name'
        indicating the GitHub repository to report against.
    token (str): a GitHub token obtained following:
        https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/


def linear(times: np.ndarray, m: float, b: float = <NUM_LIT:0.1>) -> np.ndarray:

return m*times+b<EOL>

Linear test function
    Args:
        times: Input times.
        m: Slope.
        b: Intercept
    Returns:
        np.ndarray


z = np.asarray([<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>]).astype(np.bool)<EOL>x = np.asarray([<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>]).astype(np.bool)<EOL>self.ref_p = Pauli(z, x)<EOL>self.ref_label = '<STR_LIT>'<EOL>self.ref_matrix = np.array([[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>],<EOL>[<NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>,<EOL><NUM_LIT:0.> - <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>, <NUM_LIT:0.> + <NUM_LIT>]])<EOL>


qr = QuantumRegister(<NUM_LIT:2>)<EOL>cr = ClassicalRegister(<NUM_LIT:2>)<EOL>circ = QuantumCircuit(qr, cr)<EOL>circ.h(qr[<NUM_LIT:0>])<EOL>circ.x(qr[<NUM_LIT:1>])<EOL>circ.measure(qr, cr)<EOL>return circ<EOL>

Return a unitary circuit with measurement.


def _compare_multiply_to_superop(self, rep, dim, samples, unitary=False):

for _ in range(samples):<EOL><INDENT>if unitary:<EOL><INDENT>mat1 = self.rand_matrix(dim, dim)<EOL>sop1 = np.kron(np.conj(mat1), mat1)<EOL><DEDENT>else:<EOL><INDENT>sop1 = self.rand_matrix(dim * dim, dim * dim)<EOL><DEDENT>val = <NUM_LIT:2> * (np.random.rand() - <NUM_LIT:0.5>)<EOL>targ = SuperOp(val * sop1)<EOL>channel = SuperOp(rep(SuperOp(sop1)).multiply(val))<EOL>self.assertEqual(channel, targ)<EOL><DEDENT>

Test channel scalar multiplication is equivalent to SuperOp


current_rep = chan.__class__<EOL>other_reps = [Operator, Choi, SuperOp, Kraus, Stinespring, Chi, PTM]<EOL>for rep in other_reps:<EOL><INDENT>self.assertEqual(current_rep, chan.add(rep(chan)).__class__)<EOL><DEDENT>

Check addition works for other representations


def _compare_negate_to_superop(self, rep, dim, samples, unitary=False):

for _ in range(samples):<EOL><INDENT>if unitary:<EOL><INDENT>mat1 = self.rand_matrix(dim, dim)<EOL>sop1 = np.kron(np.conj(mat1), mat1)<EOL><DEDENT>else:<EOL><INDENT>sop1 = self.rand_matrix(dim * dim, dim * dim)<EOL><DEDENT>targ = SuperOp(-<NUM_LIT:1> * sop1)<EOL>channel = SuperOp(-rep(SuperOp(sop1)))<EOL>self.assertEqual(channel, targ)<EOL><DEDENT>

Test negative channel is equivalent to SuperOp


def rand_kraus(self, input_dim, output_dim, n):

return [self.rand_matrix(output_dim, input_dim) for _ in range(n)]<EOL>

Return a random (non-CPTP) Kraus operator map


return (<NUM_LIT:1> - p) * self.sopI + p * np.array(<EOL>[[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]]) / <NUM_LIT:2><EOL>

Depolarizing channel superoperator matrix


return (<NUM_LIT:1> - p) * self.choiI + p * np.eye(<NUM_LIT:4>) / <NUM_LIT:2><EOL>


current_rep = chan.__class__<EOL>other_reps = [Operator, Choi, SuperOp, Kraus, Stinespring, Chi, PTM]<EOL>for rep in other_reps:<EOL><INDENT>self.assertEqual(current_rep, chan.tensor(rep(chan)).__class__)<EOL><DEDENT>

Check tensor works for other representations


def assertFilesAreEqual(self, current, expected):

self.assertTrue(os.path.exists(current))<EOL>self.assertTrue(os.path.exists(expected))<EOL>with open(current, "<STR_LIT:r>", encoding='<STR_LIT>') as cur,open(expected, "<STR_LIT:r>", encoding='<STR_LIT>') as exp:<EOL><INDENT>self.assertEqual(cur.read(), exp.read())<EOL><DEDENT>


calib_time = datetime(year=<NUM_LIT>, month=<NUM_LIT:2>, day=<NUM_LIT:1>, hour=<NUM_LIT:0>, minute=<NUM_LIT:0>, second=<NUM_LIT:0>)<EOL>return [Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=<NUM_LIT>),<EOL>Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=<NUM_LIT>),<EOL>Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=<NUM_LIT>),<EOL>Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=readout_error)]<EOL>


def assertResult(self, result, circuit):

picklename = '<STR_LIT>' % (type(self).__name__, circuit.name)<EOL>filename = os.path.join(DIRNAME, picklename)<EOL>if self.regenerate_expected:<EOL><INDENT>self.generate_ground_truth(result, filename)<EOL><DEDENT>with open(filename, "<STR_LIT:rb>") as input_file:<EOL><INDENT>expected = pickle.load(input_file)<EOL><DEDENT>self.assertEqual(result, expected)<EOL>

Fetches the pickle in circuit.name file and compares it with result.


def create_passmanager(self, coupling_map, initial_layout=None):

passmanager = PassManager(<EOL>self.pass_class(CouplingMap(coupling_map),  <EOL>**self.additional_args))<EOL>if initial_layout:<EOL><INDENT>passmanager.property_set['<STR_LIT>'] = Layout(initial_layout)<EOL><DEDENT>return passmanager<EOL>

Returns a PassManager using self.pass_class(coupling_map, initial_layout)


def assertCommutationSet(self, result, expected):

result_to_compare = {}<EOL>for qbit_str, sets in result.items():<EOL><INDENT>if not isinstance(qbit_str, str):<EOL><INDENT>continue<EOL><DEDENT>result_to_compare[qbit_str] = []<EOL>for commutation_set in sets:<EOL><INDENT>result_to_compare[qbit_str].append(<EOL>sorted([node._node_id for node in commutation_set]))<EOL><DEDENT><DEDENT>for qbit_str, sets in expected.items():<EOL><INDENT>for commutation_set in sets:<EOL><INDENT>commutation_set.sort()<EOL><DEDENT><DEDENT>self.assertDictEqual(result_to_compare, expected)<EOL>

Compares the result of propertyset["commutation_set"] with a dictionary of the form
        {'q[0]': [ [node_id, ...], [node_id, ...] ]}


deprecation_filter = ('<STR_LIT>', None, DeprecationWarning,<EOL>re.compile(r'<STR_LIT>', re.UNICODE), <NUM_LIT:0>)<EOL>try:<EOL><INDENT>warnings._add_filter(*deprecation_filter, append=False)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>warnings.simplefilter('<STR_LIT:ignore>', category=ChangedInMarshmallow3Warning)<EOL>

Apply filters to deprecation warnings.

    Force the `DeprecationWarning` warnings to be displayed for the qiskit
    module, overriding the system configuration as they are ignored by default
    [1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
    messages.

    TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].

    [1] https://docs.python.org/3/library/warnings.html#default-warning-filters
    [2] https://www.python.org/dev/peps/pep-0565/


if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:5>):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>


def compile(circuits, backend,<EOL>config=None, basis_gates=None, coupling_map=None, initial_layout=None,<EOL>shots=<NUM_LIT>, max_credits=<NUM_LIT:10>, seed=None, qobj_id=None, seed_mapper=None,<EOL>pass_manager=None, memory=False):

Compile a list of circuits into a qobj.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        config (dict): dictionary of parameters (e.g. noise) used by runner
        basis_gates (list[str]): list of basis gates names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        initial_layout (list): initial layout of qubits in mapping
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        seed (int): random seed for simulators
        seed_mapper (int): random seed for swapper mapper
        qobj_id (int): identifier for the generated qobj
        pass_manager (PassManager): a pass manger for the transpiler pipeline
        memory (bool): if True, per-shot measurement bitstrings are returned as well

    Returns:
        Qobj: the qobj to be run on the backends

    Raises:
        QiskitError: if the desired options are not supported by backend


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning)<EOL>return random.random_unitary(dim, seed).data<EOL>


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning)<EOL>return new_purity(state)<EOL>

Calculate the purity of a quantum state.

    Args:
        state (np.array): a quantum state
    Returns:
        float: purity.


c = concurrence(rho)<EOL>c = <NUM_LIT:0.5> + <NUM_LIT:0.5> * np.sqrt(<NUM_LIT:1> - c * c)<EOL>return shannon_entropy([c, <NUM_LIT:1> - c])<EOL>

Compute the Entanglement of Formation of a 2-qubit density matrix.

Args:
    rho ((array_like): (4,4) array_like, input density matrix.

Returns:
    float: The entanglement of formation.


def __partial_trace_mat(mat, trace_systems, dimensions, reverse=True):

trace_systems = sorted(trace_systems, reverse=True)<EOL>for j in trace_systems:<EOL><INDENT>dimension_trace = int(dimensions[j])  <EOL>if reverse:<EOL><INDENT>left_dimensions = dimensions[j + <NUM_LIT:1>:]<EOL>right_dimensions = dimensions[:j]<EOL>dimensions = right_dimensions + left_dimensions<EOL><DEDENT>else:<EOL><INDENT>left_dimensions = dimensions[:j]<EOL>right_dimensions = dimensions[j + <NUM_LIT:1>:]<EOL>dimensions = left_dimensions + right_dimensions<EOL><DEDENT>dimension_left = int(np.prod(left_dimensions))<EOL>dimension_right = int(np.prod(right_dimensions))<EOL>mat = mat.reshape([dimension_left, dimension_trace, dimension_right,<EOL>dimension_left, dimension_trace, dimension_right])<EOL>mat = mat.trace(axis1=<NUM_LIT:1>, axis2=<NUM_LIT:4>).reshape(<EOL>dimension_left * dimension_right,<EOL>dimension_left * dimension_right)<EOL><DEDENT>return mat<EOL>

Partial trace over subsystems of multi-partite matrix.

Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.

Args:
    mat (matrix_like): a matrix NxN.
    trace_systems (list(int)): a list of subsystems (starting from 0) to
                              trace over.
    dimensions (list(int)): a list of the dimensions of the subsystems.
                            If this is not set it will assume all
                            subsystems are qubits.
    reverse (bool): ordering of systems in operator.
        If True system-0 is the right most system in tensor product.
        If False system-0 is the left most system in tensor product.

Returns:
    ndarray: A density matrix with the appropriate subsystems traced over.


density_matrix = np.array(density_matrix)<EOL>if method == '<STR_LIT>':<EOL><INDENT>return density_matrix.flatten(order='<STR_LIT:F>')<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return density_matrix.flatten(order='<STR_LIT:C>')<EOL><DEDENT>elif method in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>num = int(np.log2(len(density_matrix)))  <EOL>if len(density_matrix) != <NUM_LIT:2>**num:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>pgroup = pauli_group(num, case='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>pgroup = pauli_group(num, case='<STR_LIT>')<EOL><DEDENT>vals = [np.trace(np.dot(p.to_matrix(), density_matrix))<EOL>for p in pgroup]<EOL>return np.array(vals)<EOL><DEDENT>return None<EOL>

Flatten an operator to a vector in a specified basis.

    Args:
        density_matrix (ndarray): a density matrix.
        method (str): the method of vectorization. Allowed values are
            - 'col' (default) flattens to column-major vector.
            - 'row' flattens to row-major vector.
            - 'pauli'flattens in the n-qubit Pauli basis.
            - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
               weight.

    Returns:
        ndarray: the resulting vector.
    Raises:
        Exception: if input state is not a n-qubit state


def parallel_map(task, values, task_args=tuple(), task_kwargs={},  <EOL>num_processes=CPU_COUNT):

if len(values) == <NUM_LIT:1>:<EOL><INDENT>return [task(values[<NUM_LIT:0>], *task_args, **task_kwargs)]<EOL><DEDENT>Publisher().publish("<STR_LIT>", len(values))<EOL>nfinished = [<NUM_LIT:0>]<EOL>def _callback(_):<EOL><INDENT>nfinished[<NUM_LIT:0>] += <NUM_LIT:1><EOL>Publisher().publish("<STR_LIT>", nfinished[<NUM_LIT:0>])<EOL><DEDENT>if platform.system() != '<STR_LIT>' and num_processes > <NUM_LIT:1>and os.getenv('<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>os.environ['<STR_LIT>'] = '<STR_LIT>'<EOL>try:<EOL><INDENT>pool = Pool(processes=num_processes)<EOL>async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,<EOL>_callback) for value in values]<EOL>while not all([item.ready() for item in async_res]):<EOL><INDENT>for item in async_res:<EOL><INDENT>item.wait(timeout=<NUM_LIT:0.1>)<EOL><DEDENT><DEDENT>pool.terminate()<EOL>pool.join()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pool.terminate()<EOL>pool.join()<EOL>Publisher().publish("<STR_LIT>")<EOL>raise QiskitError('<STR_LIT>')<EOL><DEDENT>Publisher().publish("<STR_LIT>")<EOL>os.environ['<STR_LIT>'] = '<STR_LIT>'<EOL>return [ar.get() for ar in async_res]<EOL><DEDENT>results = []<EOL>for _, value in enumerate(values):<EOL><INDENT>result = task(value, *task_args, **task_kwargs)<EOL>results.append(result)<EOL>_callback(<NUM_LIT:0>)<EOL><DEDENT>Publisher().publish("<STR_LIT>")<EOL>return results<EOL>

Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::

    result = [task(value, *task_args, **task_kwargs) for value in values]

On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.

Args:
    task (func): Function that is to be called for each value in ``values``.
    values (array_like): List or array of values for which the ``task``
                        function is to be evaluated.
    task_args (list): Optional additional arguments to the ``task`` function.
    task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
    num_processes (int): Number of processes to spawn.

Returns:
    result: The result list contains the value of
            ``task(value, *task_args, **task_kwargs)`` for
                each value in ``values``.

Raises:
    QiskitError: If user interrupts via keyboard.

Events:
    terra.parallel.start: The collection of parallel tasks are about to start.
    terra.parallel.update: One of the parallel task has finished.
    terra.parallel.finish: All the parallel tasks have finished.


def dispatch(self, event, *args, **kwargs):

<EOL>if event not in self._subscribers:<EOL><INDENT>return<EOL><DEDENT>for subscriber in self._subscribers[event]:<EOL><INDENT>subscriber.callback(*args, **kwargs)<EOL><DEDENT>

Emits an event if there are any subscribers.

        Args
            event (String): The event to be emitted
            args: Arguments linked with the event
            kwargs: Named arguments linked with the event


Unsubscribe everything, leaving the Broker without subscribers/events.


return "<STR_LIT>" % (time.time() - self.t_start)<EOL>

Return the time elapsed since start.

        Returns:
            elapsed_time: Time since progress bar started.


if completed_iter:<EOL><INDENT>t_r_est = (time.time() - self.t_start) /completed_iter*(self.iter-completed_iter)<EOL><DEDENT>else:<EOL><INDENT>t_r_est = <NUM_LIT:0><EOL><DEDENT>date_time = datetime.datetime(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>) + datetime.timedelta(seconds=t_r_est)<EOL>time_string = "<STR_LIT>" %(date_time.day - <NUM_LIT:1>, date_time.hour, date_time.minute, date_time.second)<EOL>return time_string<EOL>

Estimate the remaining time left.

        Parameters:
            completed_iter (int): Number of iterations completed.

        Returns:
            est_time: Estimated time remaining.


def process_tomography_set(meas_qubits, meas_basis='<STR_LIT>',<EOL>prep_qubits=None, prep_basis='<STR_LIT>'):

return tomography_set(meas_qubits, meas_basis=meas_basis,<EOL>prep_qubits=prep_qubits, prep_basis=prep_basis)<EOL>

Generate a dictionary of process tomography experiment configurations.

 This returns a data structure that is used by other tomography functions
 to generate state and process tomography circuits, and extract tomography
 data from results after execution on a backend.

A quantum process tomography set is created by specifying a preparation
 basis along with a measurement basis. The preparation basis may be a
 user defined `tomography_basis`, or one of the two built in basis 'SIC'
 or 'Pauli'.
 - SIC: Is a minimal symmetric informationally complete preparation
        basis for 4 states for each qubit (4 ^ number of qubits total
        preparation states). These correspond to the |0> state and the 3
        other vertices of a tetrahedron on the Bloch-sphere.
 - Pauli: Is a tomographically overcomplete preparation basis of the six
          eigenstates of the 3 Pauli operators (6 ^ number of qubits
          total preparation states).

 Args:
     meas_qubits (list): The qubits being measured.
     meas_basis (tomography_basis or str): The qubit measurement basis.
         The default value is 'Pauli'.
     prep_qubits (list or None): The qubits being prepared. If None then
         meas_qubits will be used for process tomography experiments.
     prep_basis (tomography_basis or str): The qubit preparation basis.
         The default value is 'SIC'.

 Returns:
     dict: A dict of tomography configurations that can be parsed by
     `create_tomography_circuits` and `tomography_data` functions
     for implementing quantum tomography experiments. This output contains
     fields "qubits", "meas_basis", "prep_basus", circuits".
     ```
     {
         'qubits': qubits (list[ints]),
         'meas_basis': meas_basis (tomography_basis),
         'prep_basis': prep_basis (tomography_basis),
         'circuit_labels': (list[string]),
         'circuits': (list[dict])  # prep and meas configurations
     }
     ```


if self.meas_fun is None:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.meas_fun(circuit, qreg, op)<EOL><DEDENT>

Add measurement gates to a circuit.

Args:
    circuit (QuantumCircuit): circuit to add measurement to.
    qreg (tuple(QuantumRegister,int)): quantum register being measured.
    op (str): the basis label for the measurement.


return tomography_set(qubits, meas_basis=meas_basis)<EOL>

Generate a dictionary of state tomography experiment configurations.

This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.

Quantum State Tomography:
    Be default it will return a set for performing Quantum State
    Tomography where individual qubits are measured in the Pauli basis.
    A custom measurement basis may also be used by defining a user
    `tomography_basis` and passing this in for the `meas_basis` argument.

Quantum Process Tomography:
    A quantum process tomography set is created by specifying a preparation
    basis along with a measurement basis. The preparation basis may be a
    user defined `tomography_basis`, or one of the two built in basis 'SIC'
    or 'Pauli'.
    - SIC: Is a minimal symmetric informationally complete preparation
           basis for 4 states for each qubit (4 ^ number of qubits total
           preparation states). These correspond to the |0> state and the 3
           other vertices of a tetrahedron on the Bloch-sphere.
    - Pauli: Is a tomographically overcomplete preparation basis of the six
             eigenstates of the 3 Pauli operators (6 ^ number of qubits
             total preparation states).

Args:
    qubits (list): The qubits being measured.
    meas_basis (tomography_basis or str): The qubit measurement basis.
        The default value is 'Pauli'.

Returns:
    dict: A dict of tomography configurations that can be parsed by
    `create_tomography_circuits` and `tomography_data` functions
    for implementing quantum tomography experiments. This output contains
    fields "qubits", "meas_basis", "circuits".
    ```
    {
        'qubits': qubits (list[ints]),
        'meas_basis': meas_basis (tomography_basis),
        'circuit_labels': (list[string]),
        'circuits': (list[dict])  # prep and meas configurations
    }
    ```


def fit_tomography_data(tomo_data, method='<STR_LIT>', options=None):

if isinstance(method, str) and method.lower() in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>trace = __get_option('<STR_LIT>', options)<EOL>beta = __get_option('<STR_LIT>', options)<EOL>rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)<EOL>if method == '<STR_LIT>':<EOL><INDENT>epsilon = __get_option('<STR_LIT>', options)<EOL>rho = __wizard(rho, epsilon=epsilon)<EOL><DEDENT>return rho<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>' % method)<EOL><DEDENT>

Reconstruct a density matrix or process-matrix from tomography data.

If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator will be a Choi-matrix in the column-vectorization
convention.

Args:
    tomo_data (dict): process tomography measurement data.
    method (str): the fitting method to use.
        Available methods:
            - 'wizard' (default)
            - 'leastsq'
    options (dict or None): additional options for fitting method.

Returns:
    numpy.array: The fitted operator.

Available methods:
    - 'wizard' (Default): The returned operator will be constrained to be
                          positive-semidefinite.
        Options:
        - 'trace': the trace of the returned operator.
                   The default value is 1.
        - 'beta': hedging parameter for computing frequencies from
                  zero-count data. The default value is 0.50922.
        - 'epsilon: threshold for truncating small eigenvalues to zero.
                    The default value is 0
    - 'leastsq': Fitting without positive-semidefinite constraint.
        Options:
        - 'trace': Same as for 'wizard' method.
        - 'beta': Same as for 'wizard' method.
Raises:
    Exception: if the `method` parameter is not valid.


return [bin(j)[<NUM_LIT:2>:].zfill(n) for j in range(<NUM_LIT:2>**n)]<EOL>

Generate outcome bitstrings for n-qubits.

    Args:
        n (int): the number of qubits.

    Returns:
        list: A list of bitstrings ordered as follows:
        Example: n=2 returns ['00', '01', '10', '11'].


def __pauli_meas_gates(circuit, qreg, op):

if op not in ['<STR_LIT:X>', '<STR_LIT:Y>', '<STR_LIT>']:<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if op == "<STR_LIT:X>":<EOL><INDENT>circuit.u2(<NUM_LIT:0.>, np.pi, qreg)  <EOL><DEDENT>elif op == "<STR_LIT:Y>":<EOL><INDENT>circuit.u2(<NUM_LIT:0.>, <NUM_LIT:0.5> * np.pi, qreg)<EOL><DEDENT>

Add state measurement gates to a circuit.


if self.prep_fun is None:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.prep_fun(circuit, qreg, op)<EOL><DEDENT>

Add state preparation gates to a circuit.

Args:
    circuit (QuantumCircuit): circuit to add a preparation to.
    qreg (tuple(QuantumRegister,int)): quantum register to apply
    preparation to.
    op (tuple(str, int)): the basis label and index for the
    preparation op.


def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):

if trace is None:<EOL><INDENT>trace = <NUM_LIT:1.>  <EOL><DEDENT>data = tomo_data['<STR_LIT:data>']<EOL>keys = data[<NUM_LIT:0>]['<STR_LIT>'].keys()<EOL>counts = []<EOL>shots = []<EOL>ops = []<EOL>for dat in data:<EOL><INDENT>for key in keys:<EOL><INDENT>counts.append(dat['<STR_LIT>'][key])<EOL>shots.append(dat['<STR_LIT>'])<EOL>projectors = dat['<STR_LIT>'][key]<EOL>op = __projector(projectors['<STR_LIT>'], tomo_data['<STR_LIT>'])<EOL>if '<STR_LIT>' in projectors:<EOL><INDENT>op_prep = __projector(projectors['<STR_LIT>'],<EOL>tomo_data['<STR_LIT>'])<EOL>op = np.kron(op_prep.conj(), op)<EOL><DEDENT>ops.append(op)<EOL><DEDENT><DEDENT>counts = np.array(counts)<EOL>shots = np.array(shots)<EOL>freqs = counts / shots<EOL>if weights is None:<EOL><INDENT>if beta is None:<EOL><INDENT>beta = <NUM_LIT><EOL><DEDENT>K = len(keys)<EOL>freqs_hedged = (counts + beta) / (shots + K * beta)<EOL>weights = np.sqrt(shots / (freqs_hedged * (<NUM_LIT:1> - freqs_hedged)))<EOL><DEDENT>return __tomo_linear_inv(freqs, ops, weights, trace=trace)<EOL>

Reconstruct a state from unconstrained least-squares fitting.

Args:
    tomo_data (list[dict]): state or process tomography data.
    weights (list or array or None): weights to use for least squares
        fitting. The default is standard deviation from a binomial
        distribution.
    trace (float or None): trace of returned operator. The default is 1.
    beta (float or None): hedge parameter (>=0) for computing frequencies
        from zero-count data. The default value is 0.50922.

Returns:
    numpy.array: A numpy array of the reconstructed operator.


def create_tomography_circuits(circuit, qreg, creg, tomoset):

if not isinstance(circuit, QuantumCircuit):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>dics = tomoset['<STR_LIT>']<EOL>labels = tomography_circuit_names(tomoset, circuit.name)<EOL>tomography_circuits = []<EOL>for label, conf in zip(labels, dics):<EOL><INDENT>tmp = circuit<EOL>if '<STR_LIT>' in conf:<EOL><INDENT>prep = QuantumCircuit(qreg, creg, name='<STR_LIT>')<EOL>for qubit, op in conf['<STR_LIT>'].items():<EOL><INDENT>tomoset['<STR_LIT>'].prep_gate(prep, qreg[qubit], op)<EOL>prep.barrier(qreg[qubit])<EOL><DEDENT>tmp = prep + tmp<EOL><DEDENT>meas = QuantumCircuit(qreg, creg, name='<STR_LIT>')<EOL>for qubit, op in conf['<STR_LIT>'].items():<EOL><INDENT>meas.barrier(qreg[qubit])<EOL>tomoset['<STR_LIT>'].meas_gate(meas, qreg[qubit], op)<EOL>meas.measure(qreg[qubit], creg[qubit])<EOL><DEDENT>tmp = tmp + meas<EOL>tmp.name = label<EOL>tomography_circuits.append(tmp)<EOL><DEDENT>logger.info('<STR_LIT>', circuit.name)<EOL>return tomography_circuits<EOL>

Add tomography measurement circuits to a QuantumProgram.

The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography. This function then appends the circuit
with a set of measurements specified by the input `tomography_set`,
optionally it also prepends the circuit with state preparation circuits if
they are specified in the `tomography_set`.

For n-qubit tomography with a tomographically complete set of preparations
and measurements this results in $4^n 3^n$ circuits being added to the
quantum program.

Args:
    circuit (QuantumCircuit): The circuit to be appended with tomography
                              state preparation and/or measurements.
    qreg (QuantumRegister): the quantum register containing qubits to be
                            measured.
    creg (ClassicalRegister): the classical register containing bits to
                              store measurement outcomes.
    tomoset (tomography_set): the dict of tomography configurations.

Returns:
    list: A list of quantum tomography circuits for the input circuit.

Raises:
    QiskitError: if circuit is not a valid QuantumCircuit

Example:
    For a tomography set specifying state tomography of qubit-0 prepared
    by a circuit 'circ' this would return:
    ```
    ['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
    ```
    For process tomography of the same circuit with preparation in the
    SIC-POVM basis it would return:
    ```
    [
        'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
        'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
        'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
        'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
        'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
        'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
    ]
    ```


def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str,<EOL>qubit_label):

if not HAS_MATPLOTLIB:<EOL><INDENT>raise ImportError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>plt.errorbar(xdata, ydata, std_error, marker='<STR_LIT:.>',<EOL>markersize=<NUM_LIT:9>, c='<STR_LIT:b>', linestyle='<STR_LIT>')<EOL>plt.plot(xdata, fit_function(xdata, *fit), c='<STR_LIT:r>', linestyle='<STR_LIT>',<EOL>label=(exp_str + '<STR_LIT>' % (str(round(fit[<NUM_LIT:1>])), xunit)))<EOL>plt.xticks(fontsize=<NUM_LIT>, rotation=<NUM_LIT>)<EOL>plt.yticks(fontsize=<NUM_LIT>)<EOL>plt.xlabel('<STR_LIT>' % (xunit), fontsize=<NUM_LIT:16>)<EOL>plt.ylabel('<STR_LIT>', fontsize=<NUM_LIT:16>)<EOL>plt.title(exp_str + '<STR_LIT>' % (str(qubit_label)), fontsize=<NUM_LIT>)<EOL>plt.legend(fontsize=<NUM_LIT:12>)<EOL>plt.grid(True)<EOL>plt.show()<EOL>

Plot coherence data.

    Args:
        xdata
        ydata
        std_error
        fit
        fit_function
        xunit
        exp_str
        qubit_label
    Raises:
        ImportError: If matplotlib is not installed.


args = magic_arguments.parse_argstring(self.qiskit_job_status, line)<EOL>if args.interval is None:<EOL><INDENT>args.interval = <NUM_LIT:2><EOL>_interval_set = False<EOL><DEDENT>else:<EOL><INDENT>_interval_set = True<EOL><DEDENT>cell_lines = cell.split('<STR_LIT:\n>')<EOL>line_vars = []<EOL>for cline in cell_lines:<EOL><INDENT>if '<STR_LIT:=>' in cline and '<STR_LIT>' not in cline:<EOL><INDENT>line_vars.append(cline.replace('<STR_LIT:U+0020>', '<STR_LIT>').split('<STR_LIT:=>')[<NUM_LIT:0>])<EOL><DEDENT>elif '<STR_LIT>' in cline:<EOL><INDENT>line_vars.append(cline.replace('<STR_LIT:U+0020>', '<STR_LIT>').split('<STR_LIT:(>')[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>self.shell.ex(cell)<EOL>jobs = []<EOL>for var in line_vars:<EOL><INDENT>iter_var = False<EOL>if '<STR_LIT:#>' not in var:<EOL><INDENT>if '<STR_LIT:[>' in var:<EOL><INDENT>var = var.split('<STR_LIT:[>')[<NUM_LIT:0>]<EOL>iter_var = True<EOL><DEDENT>elif '<STR_LIT>' in var:<EOL><INDENT>var = var.split('<STR_LIT>')[<NUM_LIT:0>]<EOL>iter_var = True<EOL><DEDENT>if iter_var:<EOL><INDENT>for item in self.shell.user_ns[var]:<EOL><INDENT>if isinstance(item, qiskit.providers.basejob.BaseJob):<EOL><INDENT>jobs.append(item)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(self.shell.user_ns[var],<EOL>qiskit.providers.basejob.BaseJob):<EOL><INDENT>jobs.append(self.shell.user_ns[var])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not any(jobs):<EOL><INDENT>raise Exception(<EOL>"<STR_LIT>")<EOL><DEDENT>multi_job = False<EOL>if len(jobs) > <NUM_LIT:1>:<EOL><INDENT>multi_job = True<EOL><DEDENT>job_checkers = []<EOL>for idx, job_var in enumerate(jobs):<EOL><INDENT>style = "<STR_LIT>"<EOL>if multi_job:<EOL><INDENT>idx_str = '<STR_LIT>' % idx<EOL><DEDENT>else:<EOL><INDENT>idx_str = '<STR_LIT>'<EOL><DEDENT>header = "<STR_LIT>".format(id=idx_str,<EOL>style=style)<EOL>status = widgets.HTML(<EOL>value=header % job_var.status().value)<EOL>thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,<EOL>status, header,<EOL>_interval_set))<EOL>thread.start()<EOL>job_checkers.append(status)<EOL><DEDENT>box = widgets.VBox(job_checkers)<EOL>display(box)<EOL>

A Jupyter magic function to check the status of a Qiskit job instance.


def _html_checker(job_var, interval, status, header,<EOL>_interval_set=False):

job_status = job_var.status()<EOL>job_status_name = job_status.name<EOL>job_status_msg = job_status.value<EOL>status.value = header % (job_status_msg)<EOL>while job_status_name not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>time.sleep(interval)<EOL>job_status = job_var.status()<EOL>job_status_name = job_status.name<EOL>job_status_msg = job_status.value<EOL>if job_status_name == '<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>if job_status_name == '<STR_LIT>':<EOL><INDENT>job_status_msg += '<STR_LIT>' % job_var.queue_position()<EOL>if not _interval_set:<EOL><INDENT>interval = max(job_var.queue_position(), <NUM_LIT:2>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not _interval_set:<EOL><INDENT>interval = <NUM_LIT:2><EOL><DEDENT><DEDENT>status.value = header % (job_status_msg)<EOL><DEDENT><DEDENT>status.value = header % (job_status_msg)<EOL>

Internal function that updates the status
    of a HTML job monitor.

    Args:
        job_var (BaseJob): The job to keep track of.
        interval (int): The status check interval
        status (widget): HTML ipywidget for output ot screen
        header (str): String representing HTML code for status.
        _interval_set (bool): Was interval set by user?


args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)<EOL>if args.type == '<STR_LIT:html>':<EOL><INDENT>HTMLProgressBar()<EOL><DEDENT>elif args.type == '<STR_LIT:text>':<EOL><INDENT>TextProgressBar()<EOL><DEDENT>else:<EOL><INDENT>raise qiskit.QiskitError('<STR_LIT>')<EOL><DEDENT>self.shell.ex(cell)<EOL>

A Jupyter magic function to generate progressbar.


config = backend.configuration().to_dict()<EOL>props = backend.properties().to_dict()<EOL>multi_qubit_gates = props['<STR_LIT>'][<NUM_LIT:3>*config['<STR_LIT>']:]<EOL>header_html = "<STR_LIT>"<EOL>header_html = header_html.format(key='<STR_LIT>',<EOL>value=props['<STR_LIT>'])<EOL>update_date_widget = widgets.HTML(value=header_html,<EOL>layout=widgets.Layout(grid_area='<STR_LIT>'))<EOL>gate_html = "<STR_LIT>"<EOL>gate_html += """<STR_LIT>"""<EOL>gate_html += "<STR_LIT>"<EOL>gate_footer = "<STR_LIT>"<EOL>left_num = math.ceil(len(multi_qubit_gates)/<NUM_LIT:3>)<EOL>mid_num = math.ceil((len(multi_qubit_gates)-left_num)/<NUM_LIT:2>)<EOL>left_table = gate_html<EOL>for qub in range(left_num):<EOL><INDENT>gate = multi_qubit_gates[qub]<EOL>name = gate['<STR_LIT:name>']<EOL>ttype = gate['<STR_LIT>']<EOL>error = round(gate['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>left_table += "<STR_LIT>"<EOL>left_table += "<STR_LIT>"<EOL>left_table = left_table % (name, ttype, error)<EOL><DEDENT>left_table += gate_footer<EOL>middle_table = gate_html<EOL>for qub in range(left_num, left_num+mid_num):<EOL><INDENT>gate = multi_qubit_gates[qub]<EOL>name = gate['<STR_LIT:name>']<EOL>ttype = gate['<STR_LIT>']<EOL>error = round(gate['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>middle_table += "<STR_LIT>"<EOL>middle_table += "<STR_LIT>"<EOL>middle_table = middle_table % (name, ttype, error)<EOL><DEDENT>middle_table += gate_footer<EOL>right_table = gate_html<EOL>for qub in range(left_num+mid_num, len(multi_qubit_gates)):<EOL><INDENT>gate = multi_qubit_gates[qub]<EOL>name = gate['<STR_LIT:name>']<EOL>ttype = gate['<STR_LIT>']<EOL>error = round(gate['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>right_table += "<STR_LIT>"<EOL>right_table += "<STR_LIT>"<EOL>right_table = right_table % (name, ttype, error)<EOL><DEDENT>right_table += gate_footer<EOL>left_table_widget = widgets.HTML(value=left_table,<EOL>layout=widgets.Layout(grid_area='<STR_LIT:left>'))<EOL>middle_table_widget = widgets.HTML(value=middle_table,<EOL>layout=widgets.Layout(grid_area='<STR_LIT>'))<EOL>right_table_widget = widgets.HTML(value=right_table,<EOL>layout=widgets.Layout(grid_area='<STR_LIT:right>'))<EOL>grid = widgets.GridBox(children=[update_date_widget,<EOL>left_table_widget,<EOL>middle_table_widget,<EOL>right_table_widget],<EOL>layout=widgets.Layout(<EOL>grid_template_rows='<STR_LIT>',<EOL>grid_template_columns='<STR_LIT>',<EOL>grid_template_areas='''<STR_LIT>''',<EOL>grid_gap='<STR_LIT>'))<EOL>return grid<EOL>

The multiple qubit gate error widget.

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        VBox: A VBox widget.


props = backend.properties().to_dict()<EOL>header_html = "<STR_LIT>"<EOL>header_html = header_html.format(key='<STR_LIT>',<EOL>value=props['<STR_LIT>'])<EOL>update_date_widget = widgets.HTML(value=header_html)<EOL>qubit_html = "<STR_LIT>"<EOL>qubit_html += """<STR_LIT>"""<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_footer = "<STR_LIT>"<EOL>for qub in range(len(props['<STR_LIT>'])):<EOL><INDENT>name = '<STR_LIT>' % qub<EOL>qubit_data = props['<STR_LIT>'][qub]<EOL>gate_data = props['<STR_LIT>'][<NUM_LIT:3>*qub:<NUM_LIT:3>*qub+<NUM_LIT:3>]<EOL>t1_info = qubit_data[<NUM_LIT:0>]<EOL>t2_info = qubit_data[<NUM_LIT:1>]<EOL>freq_info = qubit_data[<NUM_LIT:2>]<EOL>readout_info = qubit_data[<NUM_LIT:3>]<EOL>freq = str(round(freq_info['<STR_LIT:value>'], <NUM_LIT:5>))+'<STR_LIT:U+0020>'+freq_info['<STR_LIT>']<EOL>T1 = str(round(t1_info['<STR_LIT:value>'],  <EOL><NUM_LIT:5>))+'<STR_LIT:U+0020>' + t1_info['<STR_LIT>']<EOL>T2 = str(round(t2_info['<STR_LIT:value>'],  <EOL><NUM_LIT:5>))+'<STR_LIT:U+0020>' + t2_info['<STR_LIT>']<EOL>U1 = str(round(gate_data[<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>U2 = str(round(gate_data[<NUM_LIT:1>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>U3 = str(round(gate_data[<NUM_LIT:2>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>readout_error = round(readout_info['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html = qubit_html % (name, freq, T1, T2, U1, U2, U3, readout_error)<EOL><DEDENT>qubit_html += qubit_footer<EOL>qubit_widget = widgets.HTML(value=qubit_html)<EOL>out = widgets.VBox([update_date_widget,<EOL>qubit_widget])<EOL>return out<EOL>

The qubits properties widget

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        VBox: A VBox widget.


@line_magic<EOL><INDENT>def qiskit_backend_monitor(self, line='<STR_LIT>', cell=None):  <DEDENT>

backend = self.shell.user_ns[line]<EOL>if not isinstance(backend, IBMQBackend):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>title_style = "<STR_LIT>"<EOL>title_style += "<STR_LIT>"<EOL>title_html = "<STR_LIT>".format(<EOL>style=title_style, name=backend.name())<EOL>details = [config_tab(backend)]<EOL>tab_contents = ['<STR_LIT>']<EOL>if not backend.configuration().simulator:<EOL><INDENT>tab_contents.extend(['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'])<EOL>details.extend([qubits_tab(backend), gates_tab(backend),<EOL>detailed_map(backend), job_history(backend)])<EOL><DEDENT>tabs = widgets.Tab(layout=widgets.Layout(overflow_y='<STR_LIT>'))<EOL>tabs.children = details<EOL>for i in range(len(details)):<EOL><INDENT>tabs.set_title(i, tab_contents[i])<EOL><DEDENT>title_widget = widgets.HTML(value=title_html,<EOL>layout=widgets.Layout(margin='<STR_LIT>'))<EOL>backend_monitor = widgets.VBox([title_widget, tabs],<EOL>layout=widgets.Layout(border='<STR_LIT>',<EOL>max_height='<STR_LIT>', min_height='<STR_LIT>',<EOL>overflow_y='<STR_LIT>'))<EOL>display(backend_monitor)<EOL>

A Jupyter magic function to monitor backends.


my_thread = threading.currentThread()<EOL>current_interval = <NUM_LIT:0><EOL>started = False<EOL>all_dead = False<EOL>stati = [None]*len(self._backends)<EOL>while getattr(my_thread, "<STR_LIT>", True) and not all_dead:<EOL><INDENT>if current_interval == interval or started is False:<EOL><INDENT>for ind, back in enumerate(self._backends):<EOL><INDENT>_value = self.children[ind].children[<NUM_LIT:2>].value<EOL>_head = _value.split('<STR_LIT>')[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>_status = back.status()<EOL>stati[ind] = _status<EOL><DEDENT>except Exception:  <EOL><INDENT>self.children[ind].children[<NUM_LIT:2>].value = _value.replace(<EOL>_head, "<STR_LIT>")<EOL>self.children[ind]._is_alive = False<EOL><DEDENT>else:<EOL><INDENT>self.children[ind]._is_alive = True<EOL>self.children[ind].children[<NUM_LIT:2>].value = _value.replace(<EOL>_head, "<STR_LIT>")<EOL><DEDENT><DEDENT>idx = list(range(len(self._backends)))<EOL>pending = [s.pending_jobs for s in stati]<EOL>_, least_idx = zip(*sorted(zip(pending, idx)))<EOL>for ind in least_idx:<EOL><INDENT>if stati[ind].operational:<EOL><INDENT>least_pending_idx = ind<EOL>break<EOL><DEDENT><DEDENT>for var in idx:<EOL><INDENT>if var == least_pending_idx:<EOL><INDENT>self.children[var].children[<NUM_LIT:4>].value = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>self.children[var].children[<NUM_LIT:4>].value = "<STR_LIT>"<EOL><DEDENT>self.children[var].children[<NUM_LIT:3>].children[<NUM_LIT:1>].value = pending[var]<EOL>self.children[var].children[<NUM_LIT:3>].children[<NUM_LIT:1>].max = max(<EOL>self.children[var].children[<NUM_LIT:3>].children[<NUM_LIT:1>].max, pending[var]+<NUM_LIT:10>)<EOL>if stati[var].operational:<EOL><INDENT>self.children[var].children[<NUM_LIT:5>].value = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>self.children[var].children[<NUM_LIT:5>].value = "<STR_LIT>"<EOL><DEDENT><DEDENT>started = True<EOL>current_interval = <NUM_LIT:0><EOL><DEDENT>time.sleep(<NUM_LIT:1>)<EOL>all_dead = not any([wid._is_alive for wid in self.children])<EOL>current_interval += <NUM_LIT:1><EOL><DEDENT>

Updates the monitor info
    Called from another thread.


memory_list = []<EOL>for shot_memory in memory:<EOL><INDENT>memory_list.append(format_counts_memory(shot_memory, header))<EOL><DEDENT>return memory_list<EOL>

Format an experiment result memory object for measurement level 2.

    Args:
        memory (list): Memory from experiment with `meas_level==2` and `memory==True`.
        header (dict): the experiment header dictionary containing
            useful information for postprocessing.

    Returns:
        list[str]: List of bitstrings


arr = np.asarray(complex_list, dtype=np.complex_)<EOL>if not arr.shape[-<NUM_LIT:1>] == <NUM_LIT:2>:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>return arr[..., <NUM_LIT:0>] + <NUM_LIT>*arr[..., <NUM_LIT:1>]<EOL>

Convert nested list of shape (..., 2) to complex numpy array with shape (...)

    Args:
        complex_list (list): List to convert.

    Returns:
        np.ndarray: Complex numpy aray

    Raises:
        QiskitError: If inner most array of input nested list is not of length 2.


formatted_memory = _list_to_complex_array(memory)<EOL>if not <NUM_LIT:1> <= len(formatted_memory.shape) <= <NUM_LIT:2>:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>return formatted_memory<EOL>

Format an experiment result memory object for measurement level 1.

    Args:
        memory (list): Memory from experiment with `meas_level==1`. `avg` or
            `single` will be inferred from shape of result memory.

    Returns:
        np.ndarray: Measurement level 1 complex numpy array

    Raises:
        QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
            indicies.


return format(int(bitstring, <NUM_LIT:2>), '<STR_LIT>'.format(memory_slots))<EOL>

If the bitstring is truncated, pad extra zeros to make its
    length equal to memory_slots


try:<EOL><INDENT>exp = self._get_experiment(experiment)<EOL>try:<EOL><INDENT>header = exp.header.to_dict()<EOL><DEDENT>except (AttributeError, QiskitError):  <EOL><INDENT>header = None<EOL><DEDENT>return postprocess.format_counts(self.data(experiment)['<STR_LIT>'],<EOL>header)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(experiment))<EOL><DEDENT>

Get the histogram data of an experiment.

        Args:
            experiment (str or QuantumCircuit or Schedule or int or None): the index of the
                experiment, as specified by ``get_data()``.

        Returns:
            dict[str:int]: a dictionary with the counts for each qubit, with
                the keys containing a string in binary format and separated
                according to the registers in circuit (e.g. ``0100 1110``).
                The string is little-endian (cr[0] on the right hand side).

        Raises:
            QiskitError: if there are no counts for the experiment.


self._definition = array<EOL>


instruction = QasmQobjInstruction(name=self.name)<EOL>if self.params:<EOL><INDENT>params = [<EOL>x.evalf() if hasattr(x, '<STR_LIT>') else x for x in self.params<EOL>]<EOL>params = [<EOL>sympy.matrix2numpy(x, dtype=complex) if isinstance(<EOL>x, sympy.Matrix) else x for x in params<EOL>]<EOL>instruction.params = params<EOL><DEDENT>if self.num_qubits:<EOL><INDENT>instruction.qubits = list(range(self.num_qubits))<EOL><DEDENT>if self.num_clbits:<EOL><INDENT>instruction.memory = list(range(self.num_clbits))<EOL><DEDENT>if self.control:<EOL><INDENT>instruction._control = self.control<EOL><DEDENT>return instruction<EOL>


if type(self) is not type(other) orself.name != other.name orself.num_qubits != other.num_qubits orself.num_clbits != other.num_clbits orself.definition != other.definition:<EOL><INDENT>return False<EOL><DEDENT>for self_param, other_param in zip_longest(self.params, other.params):<EOL><INDENT>if self_param == other_param:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>if numpy.isclose(float(self_param), float(other_param),<EOL>atol=_CUTOFF_PRECISION):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>return False<EOL><DEDENT>return True<EOL>

Two instructions are the same if they have the same name,
        same dimensions, and same params.

        Args:
            other (instruction): other instruction

        Returns:
            bool: are self and other equal.


def __init__(self, name, num_qubits, num_clbits, params):

if not isinstance(num_qubits, int) or not isinstance(num_clbits, int):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if num_qubits < <NUM_LIT:0> or num_clbits < <NUM_LIT:0>:<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>" %<EOL>num_qubits, num_clbits)<EOL><DEDENT>self.name = name<EOL>self.num_qubits = num_qubits<EOL>self.num_clbits = num_clbits<EOL>self._params = []  <EOL>self.control = None<EOL>self._definition = None<EOL>self.params = params<EOL>

Create a new instruction.
        Args:
            name (str): instruction name
            num_qubits (int): instruction's qubit width
            num_clbits (int): instructions's clbit width
            params (list[sympy.Basic|qasm.Node|int|float|complex|str|ndarray]): list of parameters
        Raises:
            QiskitError: when the register is not in the correct format.


name_param = self.name<EOL>if self.params:<EOL><INDENT>name_param = "<STR_LIT>" % (name_param, "<STR_LIT:U+002C>".join(<EOL>[str(i) for i in self.params]))<EOL><DEDENT>return self._qasmif(name_param)<EOL>

Return a default OpenQASM string for the instruction.

        Derived instructions may override this to print in a
        different format (e.g. measure q[0] -> c[0];).


<EOL>if self._definition and not self._params:<EOL><INDENT>self._params = []<EOL>for sub_instr, _, _ in self._definition:<EOL><INDENT>self._params.extend(sub_instr.params)  <EOL><DEDENT>return self._params<EOL><DEDENT>else:<EOL><INDENT>return self._params<EOL><DEDENT>


super().__init__("<STR_LIT>", <NUM_LIT:1>, <NUM_LIT:0>, [])<EOL>


return "<STR_LIT>" % (self.name, self.size)<EOL>

Return OPENQASM string for this register.


def __setitem__(self, parameter, instr_params):

for instruction, param_index in instr_params:<EOL><INDENT>assert isinstance(instruction, Instruction)<EOL>assert isinstance(param_index, int)<EOL><DEDENT>self._table[parameter] = instr_params<EOL>

Sets list of Instructions that depend on Parameter.

        Args:
            parameter (Parameter): the parameter to set
            instr_params (list): List of (Instruction, int) tuples. Int is the
              parameter index at which the parameter appears in the instruction.


return zip([self]*self.size, range(self.size))<EOL>

Returns:
    iterator: an iterator over the bits/qubits of the register, in the
        form `tuple (Register, int)`.


return hash((type(self), self.name, self.size))<EOL>

Make object hashable, based on the name and size to hash.


return len(self.instructions)<EOL>


raise QiskitError("<STR_LIT>".format(type(self)))<EOL>

Return a Numpy.array for the gate unitary matrix.

        Additional Information
        ----------------------
        If a Gate subclass does not implement this method an exception
        will be raised when this base class method is called.


return [cbit for creg in self.cregs for cbit in creg]<EOL>

Returns a list of classical bits in the order that the registers had been added.


return self.combine(rhs)<EOL>


<EOL>reg_offset = <NUM_LIT:0><EOL>reg_map = {}<EOL>for reg in self.qregs+self.cregs:<EOL><INDENT>reg_map[reg.name] = reg_offset<EOL>reg_offset += reg.size<EOL><DEDENT>op_stack = [<NUM_LIT:0>]*reg_offset<EOL>for instr, qargs, cargs in self.data:<EOL><INDENT>if instr.name not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>levels = []<EOL>reg_ints = []<EOL>for ind, reg in enumerate(qargs+cargs):<EOL><INDENT>reg_ints.append(reg_map[reg[<NUM_LIT:0>].name]+reg[<NUM_LIT:1>])<EOL>levels.append(op_stack[reg_ints[ind]] + <NUM_LIT:1>)<EOL><DEDENT>if instr.control:<EOL><INDENT>cint = reg_map[instr.control[<NUM_LIT:0>].name]<EOL>for off in range(instr.control[<NUM_LIT:0>].size):<EOL><INDENT>if cint+off not in reg_ints:<EOL><INDENT>reg_ints.append(cint+off)<EOL>levels.append(op_stack[cint+off]+<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>max_level = max(levels)<EOL>for ind in reg_ints:<EOL><INDENT>op_stack[ind] = max_level<EOL><DEDENT><DEDENT><DEDENT>return max(op_stack)<EOL>

Return circuit depth (i.e. length of critical path).
        This does not include compiler or simulator directives
        such as 'barrier' or 'snapshot'.

        Returns:
            int: Depth of circuit.

        Notes:
            The circuit depth and the DAG depth need not bt the
            same.


has_reg = False<EOL>if (isinstance(register, QuantumRegister) and<EOL>register in self.qregs):<EOL><INDENT>has_reg = True<EOL><DEDENT>elif (isinstance(register, ClassicalRegister) and<EOL>register in self.cregs):<EOL><INDENT>has_reg = True<EOL><DEDENT>return has_reg<EOL>

Test if this circuit has the register r.

Args:
    register (Register): a quantum or classical register.

Returns:
    bool: True if the register is contained in this circuit.


qasm = Qasm(filename=path)<EOL>return _circuit_from_qasm(qasm)<EOL>

Take in a QASM file and generate a QuantumCircuit object.

        Args:
          path (str): Path to the file for a QASM program
        Return:
          QuantumCircuit: The QuantumCircuit object for the input QASM


gate_ops = <NUM_LIT:0><EOL>for instr, _, _ in self.data:<EOL><INDENT>if instr.name not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>gate_ops += <NUM_LIT:1><EOL><DEDENT><DEDENT>return gate_ops<EOL>

Returns total number of gate operations in circuit.

        Returns:
            int: Total number of gate operations.


return self.num_unitary_factors()<EOL>

Computes the number of tensor factors in the unitary
        (quantum) part of the circuit only.

        Notes:
            This is here for backwards compatibility, and will be
            removed in a future release of qiskit. You should call
            `num_unitary_factors` instead.


list1 = self.qregs + self.cregs<EOL>list2 = rhs.qregs + rhs.cregs<EOL>for element1 in list1:<EOL><INDENT>for element2 in list2:<EOL><INDENT>if element2.name == element1.name:<EOL><INDENT>if element1 != element2:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Raise exception if the circuits are defined on incompatible registers


<EOL>self._check_compatible_regs(rhs)<EOL>combined_qregs = deepcopy(self.qregs)<EOL>combined_cregs = deepcopy(self.cregs)<EOL>for element in rhs.qregs:<EOL><INDENT>if element not in self.qregs:<EOL><INDENT>combined_qregs.append(element)<EOL><DEDENT><DEDENT>for element in rhs.cregs:<EOL><INDENT>if element not in self.cregs:<EOL><INDENT>combined_cregs.append(element)<EOL><DEDENT><DEDENT>circuit = QuantumCircuit(*combined_qregs, *combined_cregs)<EOL>for instruction_context in itertools.chain(self.data, rhs.data):<EOL><INDENT>circuit.append(*instruction_context)<EOL><DEDENT>return circuit<EOL>

Append rhs to self if self contains compatible registers.

Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.

Return self + rhs as a new object.


string_temp = self.header + "<STR_LIT:\n>"<EOL>string_temp += self.extension_lib + "<STR_LIT:\n>"<EOL>for register in self.qregs:<EOL><INDENT>string_temp += register.qasm() + "<STR_LIT:\n>"<EOL><DEDENT>for register in self.cregs:<EOL><INDENT>string_temp += register.qasm() + "<STR_LIT:\n>"<EOL><DEDENT>for instruction, qargs, cargs in self.data:<EOL><INDENT>if instruction.name == '<STR_LIT>':<EOL><INDENT>qubit = qargs[<NUM_LIT:0>]<EOL>clbit = cargs[<NUM_LIT:0>]<EOL>string_temp += "<STR_LIT>" % (instruction.qasm(),<EOL>qubit[<NUM_LIT:0>].name, qubit[<NUM_LIT:1>],<EOL>clbit[<NUM_LIT:0>].name, clbit[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>string_temp += "<STR_LIT>" % (instruction.qasm(),<EOL>"<STR_LIT:U+002C>".join(["<STR_LIT>" % (j[<NUM_LIT:0>].name, j[<NUM_LIT:1>])<EOL>for j in qargs + cargs]))<EOL><DEDENT><DEDENT>return string_temp<EOL>


self.append(gate)<EOL>


self.data.append(gate)<EOL>return gate<EOL>


def __init__(self, name, params, inverse_name=None):

warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', DeprecationWarning)<EOL>super().__init__(name, params)<EOL>self.data = []  <EOL>self.inverse_flag = False<EOL>self.inverse_name = inverse_name or (name + '<STR_LIT>')<EOL>

Create a new composite gate.

        name = instruction name string
        params = list of real parameters


if type(self) is type(other) andself._qubits == other._qubits:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two device specs are the same if they have the same qubits.

        Args:
            other (DeviceSpecification): other DeviceSpecification

        Returns:
            bool: are self and other equal.


def __init__(self,<EOL>qubits: List[Qubit],<EOL>registers: List[RegisterSlot],<EOL>mem_slots: List[MemorySlot]):

self._qubits = qubits<EOL>self._reg_slots = registers<EOL>self._mem_slots = mem_slots<EOL>

Create device specification with specified `qubits`.
Args:
    qubits:


if (type(self) is type(other) and<EOL>self._ub == other._ub and<EOL>self._lb == other._lb):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two LO ranges are the same if they are of the same type, and
        have the same frequency range

        Args:
            other (LoRange): other LoRange

        Returns:
            bool: are self and other equal.


def __init__(self, index: int,<EOL>lo_freq: float = None,<EOL>lo_freq_range: Tuple[float, float] = (<NUM_LIT:0>, float("<STR_LIT>"))):

super().__init__(index, lo_freq, lo_freq_range)<EOL>

Create new measurement (m) channel.

        Args:
            index (int): index of the channel
            lo_freq (float): default frequency of LO (local oscillator)
            lo_freq_range (tuple): feasible range of LO frequency


@property<EOL><INDENT>def lo_freq(self) -> float:<DEDENT>

return self._lo_freq<EOL>


Create new register slot.

        Args:
            index (int): Index of the channel.


@property<EOL><INDENT>def measure(self) -> MeasureChannel:<DEDENT>

if self._measures:<EOL><INDENT>return self._measures[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise PulseError("<STR_LIT>" % self._index)<EOL><DEDENT>

Return the primary measure channel of this qubit.


def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],<EOL>name: str = None) -> Schedule:

if name is None and schedules:<EOL><INDENT>sched = schedules[<NUM_LIT:0>]<EOL>if isinstance(sched, (list, tuple)):<EOL><INDENT>name = sched[<NUM_LIT:1>].name<EOL><DEDENT>else:<EOL><INDENT>name = sched.name<EOL><DEDENT><DEDENT>return Schedule(*schedules, name=name)<EOL>

Create a union (and also shift if desired) of all input `Schedule`s.

    Args:
        *schedules: Schedules to take the union of
        name: Name of the new schedule. Defaults to first element of `schedules`


def right_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:

times = np.arange(<NUM_LIT:1>, duration+<NUM_LIT:1>)<EOL>return continuous_pulse(times, *args, **kwargs)<EOL>

Sampling strategy for decorator.
    Args:
        continuous_pulse: Continuous pulse function to sample.
        duration: Duration to sample for.
        *args: Continuous pulse function args.
        **kwargs: Continuous pulse function kwargs.


def right(continuous_pulse: Callable) -> Callable:

return sampler(strategies.right_sample)(continuous_pulse)<EOL>

r"""Right sampling strategy decorator.

    See `pulse.samplers.sampler` for more information.

    For `duration`, return:
        $$\{f(t) \in \mathbb{C} | t \in \mathbb{Z} \wedge  0<t<=\texttt{duration}\}$$

    Args:
        continuous_pulse: To sample.


def sampler(sample_function: Callable) -> Callable:

def generate_sampler(continuous_pulse: Callable) -> Callable:<EOL><INDENT>"""<STR_LIT>"""<EOL>@functools.wraps(continuous_pulse)<EOL>def call_sampler(duration: int, *args, **kwargs) -> commands.SamplePulse:<EOL><INDENT>"""<STR_LIT>"""<EOL>sampled_pulse = sample_function(continuous_pulse, duration, *args, **kwargs)<EOL>return np.asarray(sampled_pulse, dtype=np.complex_)<EOL><DEDENT>call_sampler = _update_annotations(call_sampler)<EOL>call_sampler = _update_docstring(call_sampler, sample_function)<EOL>call_sampler.__dict__.pop('<STR_LIT>')<EOL>return commands.functional_pulse(call_sampler)<EOL><DEDENT>return generate_sampler<EOL>

Sampler decorator base method.

    Samplers are used for converting an continuous function to a discretized pulse.

    They operate on a function with the signature:
        `def f(times: np.ndarray, *args, **kwargs) -> np.ndarray`
    Where `times` is a numpy array of floats with length n_times and the output array
    is a complex numpy array with length n_times. The output of the decorator is an
    instance of `FunctionalPulse` with signature:
        `def g(duration: int, *args, **kwargs) -> SamplePulse`

    Note if your continuous pulse function outputs a `complex` scalar rather than a
    `np.ndarray`, you should first vectorize it before applying a sampler.

    This class implements the sampler boilerplate for the sampler.

    Args:
        sample_function: A sampler function to be decorated.


def triangle(times: np.ndarray, amp: complex, period: float, phase: float = <NUM_LIT:0>) -> np.ndarray:

return amp*(-<NUM_LIT:2>*np.abs(sawtooth(times, <NUM_LIT:1>, period, (phase-np.pi/<NUM_LIT:2>)/<NUM_LIT:2>)) + <NUM_LIT:1>).astype(np.complex_)<EOL>

Continuous triangle wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt.
        phase: Pulse phase.


def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float,<EOL>ret_gaussian: bool = False) -> np.ndarray:

gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True)<EOL>gauss_deriv = -x/sigma*gauss<EOL>if ret_gaussian:<EOL><INDENT>return gauss_deriv, gauss<EOL><DEDENT>return gauss_deriv<EOL>

Continuous unnormalized gaussian derivative pulse.

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        ret_gaussian: Return gaussian with which derivative was taken with.


def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,<EOL>sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:

square_start = center-width/<NUM_LIT:2><EOL>square_stop = center+width/<NUM_LIT:2><EOL>if zeroed_width:<EOL><INDENT>zeroed_width = min(width, zeroed_width)<EOL>gauss_zeroed_width = zeroed_width-width<EOL><DEDENT>else:<EOL><INDENT>gauss_zeroed_width = None<EOL><DEDENT>funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma,<EOL>zeroed_width=gauss_zeroed_width, rescale_amp=True),<EOL>functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma,<EOL>zeroed_width=gauss_zeroed_width, rescale_amp=True),<EOL>functools.partial(constant, amp=amp)]<EOL>condlist = [times <= square_start, times >= square_stop]<EOL>return np.piecewise(times.astype(np.complex_), condlist, funclist)<EOL>

r"""Continuous gaussian square pulse.

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude.
        center: Center of the square pulse component.
        width: Width of the square pulse component.
        sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
        zeroed_width: Subtract baseline of gaussian square pulse
                      to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.


def sin(times: np.ndarray, amp: complex, freq: float, phase: float = <NUM_LIT:0>) -> np.ndarray:

return amp*np.sin(<NUM_LIT:2>*np.pi*freq*times+phase).astype(np.complex_)<EOL>

Continuous cosine wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt.
        phase: Pulse phase.


def gaussian(duration: int, amp: complex, sigma: float, name: str = None) -> SamplePulse:

center = duration/<NUM_LIT:2><EOL>zeroed_width = duration + <NUM_LIT:2><EOL>return _sampled_gaussian_pulse(duration, amp, center, sigma,<EOL>zeroed_width=zeroed_width, rescale_amp=True, name=name)<EOL>

r"""Generates unnormalized gaussian `SamplePulse`.

    Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude at `duration/2`.
        sigma: Width (standard deviation) of pulse.
        name: Name of pulse.


def sin(duration: int, amp: complex, freq: float = None,<EOL>phase: float = <NUM_LIT:0>, name: str = None) -> SamplePulse:

if freq is None:<EOL><INDENT>freq = <NUM_LIT:1>/duration<EOL><DEDENT>return _sampled_sin_pulse(duration, amp, freq, phase=phase, name=name)<EOL>

Generates sine wave `SamplePulse`.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.


@abstractmethod<EOL><INDENT>def __lshift__(self, time: int) -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule which is shifted forward by `time`.


@abstractmethod<EOL><INDENT>def append(self, schedule: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule with `schedule` inserted at the maximum time over
        all channels shared between `self` and `schedule`.
        Args:
            schedule: schedule to be appended


@property<EOL><INDENT>@abstractmethod<EOL>def name(self) -> str:<DEDENT>

pass<EOL>


@abstractmethod<EOL><INDENT>def insert(self, start_time: int, schedule: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule with `schedule` inserted at `start_time` of `self`.
        Args:
            start_time: time to be inserted
            schedule: schedule to be inserted


@property<EOL><INDENT>@abstractmethod<EOL>def instructions(self) -> Tuple[Tuple[int, '<STR_LIT>']]:<DEDENT>

pass<EOL>

Return iterable for all `Instruction`s in `Schedule` tree.


@property<EOL><INDENT>@abstractmethod<EOL>def children(self) -> Tuple[Union[int, '<STR_LIT>']]:<DEDENT>

pass<EOL>


@property<EOL><INDENT>@abstractmethod<EOL>def channels(self) -> List[Channel]:<DEDENT>

pass<EOL>


@abstractmethod<EOL><INDENT>def __add__(self, schedule: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule with `schedule` inserted within `self` at `start_time`.


@property<EOL><INDENT>def type(self) -> str:<DEDENT>

return self._type<EOL>


if type(self) is type(other) andself._name == other._name andself._params == other._params:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two measurement options are the same if they are of the same type
        and have the same name and params.

        Args:
            other (MeasOpts): Other Discriminator/Kernel.

        Returns:
            bool: are self and other equal.


return self._name<EOL>


if type(self) is type(other) andself.phase == other.phase:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two FrameChanges are the same if they are of the same type
        and have the same phase.

        Args:
            other (FrameChange): other FrameChange

        Returns:
            bool: are self and other equal.


def insert(self, start_time: int, schedule: ScheduleComponent) -> '<STR_LIT>':

return ops.insert(self, start_time, schedule)<EOL>

Return a new schedule with `schedule` inserted within `self` at `start_time`.

        Args:
            start_time: time to be inserted
            schedule: schedule to be inserted


def __add__(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return self.append(schedule)<EOL>


@property<EOL><INDENT>def stop_time(self) -> int:<DEDENT>

return self.timeslots.stop_time<EOL>


def _instructions(self, time: int = <NUM_LIT:0>) -> Iterable[Tuple[int, '<STR_LIT>']]:

yield (time, self)<EOL>

Iterable for flattening Schedule tree.

        Args:
            time: Shifted time of this node due to parent

        Yields:
            Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
                at and the flattened `ScheduleComponent`.


def append(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return ops.append(self, schedule)<EOL>

Return a new schedule with `schedule` inserted at the maximum time over
        all channels shared between `self` and `schedule`.

        Args:
            schedule: schedule to be appended


def ch_duration(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_duration(*channels)<EOL>

Return duration of the supplied channels in this Instruction.

        Args:
            *channels: Supplied channels


def ch_stop_time(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_stop_time(*channels)<EOL>

Return maximum start time for supplied channels.

        Args:
            *channels: Supplied channels


return self._discriminator<EOL>


if type(self) is type(other) andself.kernel == other.kernel andself.discriminator == other.discriminator:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two Acquires are the same if they are of the same type
        and have the same kernel and discriminator.

        Args:
            other (Acquire): Other Acquire

        Returns:
            bool: are self and other equal.


return self._kernel<EOL>


return self.to_instruction(*args, **kwargs)<EOL>

Creates an Instruction obtained from call to `to_instruction` wrapped in a Schedule.


if super().__eq__(other) and(self._samples == other._samples).all():<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two SamplePulses are the same if they are of the same type
        and have the same name and samples.

        Args:
            other (SamplePulse): other SamplePulse

        Returns:
            bool: are self and other equal.


return self._samples<EOL>


return self._m_lo_freq<EOL>


return self._q_lo_freq<EOL>


return ops.append(self, schedule)<EOL>


def __lshift__(self, time: int) -> '<STR_LIT>':

return self.shift(time)<EOL>


@property<EOL><INDENT>def start_time(self) -> int:<DEDENT>

return self.ch_start_time(*self.channels)<EOL>

Return earliest start time in this collection.


def __init__(self, *timeslots: List[Timeslot]):

self._table = defaultdict(list)<EOL>for slot in timeslots:<EOL><INDENT>for interval in self._table[slot.channel]:<EOL><INDENT>if slot.interval.has_overlap(interval):<EOL><INDENT>raise PulseError("<STR_LIT>")<EOL><DEDENT><DEDENT>self._table[slot.channel].append(slot.interval)<EOL><DEDENT>self._timeslots = tuple(timeslots)<EOL>

Create a new time-slot collection.

        Args:
            *timeslots: list of time slots
        Raises:
            PulseError: when overlapped time slots are specified


return self._channel<EOL>


@property<EOL><INDENT>def timeslots(self) -> Tuple[Timeslot]:<DEDENT>

return self._timeslots<EOL>


if self._begin == other._begin and self._end == other._end:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two intervals are the same if they have the same begin and end.

        Args:
            other (Interval): other Interval

        Returns:
            bool: are self and other equal.


return self.ch_stop_time(*channels)<EOL>

Return maximum duration of timeslots over all channels.

        Args:
            *channels: Channels over which to obtain the duration.


return self._end - self._begin<EOL>


return nx.lexicographical_topological_sort(self._multi_graph,<EOL>key=lambda x: str(x.qargs))<EOL>

Yield nodes in topological order.

Returns:
    generator(DAGNode): node in topological order


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>return len(self._multi_graph)<EOL>

Deprecated usage to return max node id, now returns size of DAG


<EOL>for wire in args:<EOL><INDENT>if wire not in amap:<EOL><INDENT>raise DAGCircuitError("<STR_LIT>" %<EOL>(wire[<NUM_LIT:0>].name, wire[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>

Check the values of a list of (qu)bit arguments.

        For each element of args, check that amap contains it.

        Args:
            args (list): (register,idx) tuples
            amap (dict): a dictionary keyed on (register,idx) tuples

        Raises:
            DAGCircuitError: if a qubit is not contained in amap


warnings.warn('<STR_LIT>',<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning, <NUM_LIT:2>)<EOL>two_q_nodes = []<EOL>for node in self._multi_graph.nodes():<EOL><INDENT>if node.type == '<STR_LIT>' and len(node.qargs) == <NUM_LIT:2>:<EOL><INDENT>two_q_nodes.append(node.data_dict)<EOL><DEDENT><DEDENT>return two_q_nodes<EOL>