<commit_before># Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
from typing import Dict, Optional, List, Any, Iterable, Callable, Tuple, Union
import numpy as np
from ply import yacc

import cirq
from cirq import Circuit, NamedQubit, CX
from cirq.circuits.qasm_output import QasmUGate
from cirq.contrib.qasm_import._lexer import QasmLexer
from cirq.contrib.qasm_import.exception import QasmException


class Qasm:
    """Qasm stores the final result of the Qasm parsing."""

    def __init__(self, supported_format: bool, qelib1_include: bool,
                 qregs: dict, cregs: dict, c: Circuit):
        # defines whether the Quantum Experience standard header
        # is present or not
        self.qelib1Include = qelib1_include
        # defines if it has a supported format or not
        self.supportedFormat = supported_format
        # circuit
        self.qregs = qregs
        self.cregs = cregs
        self.circuit = c


class QasmGateStatement:
    """Specifies how to convert a call to an OpenQASM gate
    to a list of `cirq.GateOperation`s.

    Has the responsibility to validate the arguments
    and parameters of the call and to generate a list of corresponding
    `cirq.GateOperation`s in the `on` method.
    """

    def __init__(
            self, qasm_gate: str,
            cirq_gate: Union[cirq.Gate, Callable[[List[float]], cirq.Gate]],
            num_params: int, num_args: int):
        """Initializes a Qasm gate statement.

       Args:
           qasm_gate: the symbol of the QASM gate
           cirq_gate: the gate class on the cirq side
           num_args: the number of qubits (used in validation) this
                       gate takes
       """
        self.qasm_gate = qasm_gate
        self.cirq_gate = cirq_gate
        self.num_params = num_params
        self.num_args = num_args

    def _validate_args(self, args: List[List[cirq.Qid]], lineno: int):
        if len(args) != self.num_args:
            raise QasmException(
                "{} only takes {} arg(s) (qubits and/or registers), "
                "got: {}, at line {}".format(self.qasm_gate, self.num_args,
                                             len(args), lineno))

    def _validate_params(self, params: List[float], lineno: int):
        if len(params) != self.num_params:
            raise QasmException(
                "{} takes {} parameter(s), got: {}, at line {}".format(
                    self.qasm_gate, self.num_params, len(params), lineno))

    def on(self, params: List[float], args: List[List[cirq.Qid]],
           lineno: int) -> Iterable[cirq.Operation]:
        self._validate_args(args, lineno)
        self._validate_params(params, lineno)

        reg_sizes = np.unique([len(reg) for reg in args])
        if len(reg_sizes) > 2 or (len(reg_sizes) > 1 and reg_sizes[0] != 1):
            raise QasmException("Non matching quantum registers of length {} "
                                "at line {}".format(reg_sizes, lineno))

        # the actual gate we'll apply the arguments to might be a parameterized
        # or non-parametrized gate
        final_gate = (self.cirq_gate if isinstance(self.cirq_gate, cirq.Gate)
                      else self.cirq_gate(params))  # type: cirq.Gate
        # OpenQASM gates can be applied on single qubits and qubit registers.
        # We represent single qubits as registers of size 1.
        # Based on the OpenQASM spec (https://arxiv.org/abs/1707.03429),
        # single qubit arguments can be mixed with qubit registers.
        # Given quantum registers of length reg_size and single qubits are both
        # used as arguments, we generate reg_size GateOperations via iterating
        # through each qubit of the registers 0 to n-1 and use the same one
        # qubit from the "single-qubit registers" for each operation.
        op_qubits = functools.reduce(np.broadcast, args)  # type: np.broadcast
        for qubits in op_qubits:  # type: Tuple[cirq.Qid]
            if isinstance(qubits, cirq.Qid):
                yield final_gate.on(qubits)
            elif len(np.unique(qubits)) < len(qubits):<commit_msg>Fixes type import in QASM parser (#1754)<commit_after># Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
from typing import (Any, Callable, cast, Dict, Iterable, List, Optional,
                    Sequence, Union)

import numpy as np
from ply import yacc

import cirq
from cirq import Circuit, NamedQubit, CX
from cirq.circuits.qasm_output import QasmUGate
from cirq.contrib.qasm_import._lexer import QasmLexer
from cirq.contrib.qasm_import.exception import QasmException


class Qasm:
    """Qasm stores the final result of the Qasm parsing."""

    def __init__(self, supported_format: bool, qelib1_include: bool,
                 qregs: dict, cregs: dict, c: Circuit):
        # defines whether the Quantum Experience standard header
        # is present or not
        self.qelib1Include = qelib1_include
        # defines if it has a supported format or not
        self.supportedFormat = supported_format
        # circuit
        self.qregs = qregs
        self.cregs = cregs
        self.circuit = c


class QasmGateStatement:
    """Specifies how to convert a call to an OpenQASM gate
    to a list of `cirq.GateOperation`s.

    Has the responsibility to validate the arguments
    and parameters of the call and to generate a list of corresponding
    `cirq.GateOperation`s in the `on` method.
    """

    def __init__(
            self, qasm_gate: str,
            cirq_gate: Union[cirq.Gate, Callable[[List[float]], cirq.Gate]],
            num_params: int, num_args: int):
        """Initializes a Qasm gate statement.

       Args:
           qasm_gate: the symbol of the QASM gate
           cirq_gate: the gate class on the cirq side
           num_args: the number of qubits (used in validation) this
                       gate takes
       """
        self.qasm_gate = qasm_gate
        self.cirq_gate = cirq_gate
        self.num_params = num_params
        self.num_args = num_args

    def _validate_args(self, args: List[List[cirq.Qid]], lineno: int):
        if len(args) != self.num_args:
            raise QasmException(
                "{} only takes {} arg(s) (qubits and/or registers), "
                "got: {}, at line {}".format(self.qasm_gate, self.num_args,
                                             len(args), lineno))

    def _validate_params(self, params: List[float], lineno: int):
        if len(params) != self.num_params:
            raise QasmException(
                "{} takes {} parameter(s), got: {}, at line {}".format(
                    self.qasm_gate, self.num_params, len(params), lineno))

    def on(self, params: List[float], args: List[List[cirq.Qid]],
           lineno: int) -> Iterable[cirq.Operation]:
        self._validate_args(args, lineno)
        self._validate_params(params, lineno)

        reg_sizes = np.unique([len(reg) for reg in args])
        if len(reg_sizes) > 2 or (len(reg_sizes) > 1 and reg_sizes[0] != 1):
            raise QasmException("Non matching quantum registers of length {} "
                                "at line {}".format(reg_sizes, lineno))

        # the actual gate we'll apply the arguments to might be a parameterized
        # or non-parametrized gate
        final_gate = (self.cirq_gate if isinstance(self.cirq_gate, cirq.Gate)
                      else self.cirq_gate(params))  # type: cirq.Gate
        # OpenQASM gates can be applied on single qubits and qubit registers.
        # We represent single qubits as registers of size 1.
        # Based on the OpenQASM spec (https://arxiv.org/abs/1707.03429),
        # single qubit arguments can be mixed with qubit registers.
        # Given quantum registers of length reg_size and single qubits are both
        # used as arguments, we generate reg_size GateOperations via iterating
        # through each qubit of the registers 0 to n-1 and use the same one
        # qubit from the "single-qubit registers" for each operation.
        op_qubits = cast(Sequence[Sequence[cirq.Qid]],
                         functools.reduce(np.broadcast, args))
        for qubits in op_qubits:
            if isinstance(qubits, cirq.Qid):
                yield final_gate.on(qubits)
            elif len(np.unique(qubits)) < len(qubits):
{'fraction_non_alphanumeric': 0.08293460925039872, 'fraction_numerical': 0.006166932482721956, 'mean_word_length': 2.491462509279881, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1990588', 'n_tokens_mistral': 2758, 'n_tokens_neox': 2613, 'n_words': 957}