code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def is_available(self, cmd): # pylint: disable=too-many-return-statements,too-many-branches """ Return true if the command can be executed. Depending on the device chosen, the operations available differ. The operations available for the Aspen-8 Rigetti device are: - "cz" = Control Z, "xy" = Not available in ProjectQ, "ccnot" = Toffoli (ie. controlled CNOT), "cnot" = Control X, "cphaseshift" = Control R, "cphaseshift00" "cphaseshift01" "cphaseshift10" = Not available in ProjectQ, "cswap" = Control Swap, "h" = H, "i" = Identity, not in ProjectQ, "iswap" = Not available in ProjectQ, "phaseshift" = R, "pswap" = Not available in ProjectQ, "rx" = Rx, "ry" = Ry, "rz" = Rz, "s" = S, "si" = Sdag, "swap" = Swap, "t" = T, "ti" = Tdag, "x" = X, "y" = Y, "z" = Z The operations available for the IonQ Device are: - "x" = X, "y" = Y, "z" = Z, "rx" = Rx, "ry" = Ry, "rz" = Rz, "h", H, "cnot" = Control X, "s" = S, "si" = Sdag, "t" = T, "ti" = Tdag, "v" = SqrtX, "vi" = Not available in ProjectQ, "xx" "yy" "zz" = Not available in ProjectQ, "swap" = Swap, "i" = Identity, not in ProjectQ The operations available for the StateVector simulator (SV1) are the union of the ones for Rigetti Aspen-8 and IonQ Device plus some more: - "cy" = Control Y, "unitary" = Arbitrary unitary gate defined as a matrix equivalent to the MatrixGate in ProjectQ, "xy" = Not available in ProjectQ Args: cmd (Command): Command for which to check availability """ gate = cmd.gate if gate in (Measure, Allocate, Deallocate, Barrier): return True if has_negative_control(cmd): return False if self.device == 'Aspen-8': if get_control_count(cmd) == 2: return isinstance(gate, XGate) if get_control_count(cmd) == 1: return isinstance(gate, (R, ZGate, XGate, SwapGate)) if get_control_count(cmd) == 0: return isinstance( gate, ( R, Rx, Ry, Rz, XGate, YGate, ZGate, HGate, SGate, TGate, SwapGate, ), ) or gate in (Sdag, Tdag) if self.device == 'IonQ Device': if get_control_count(cmd) == 1: return isinstance(gate, XGate) if get_control_count(cmd) == 0: return isinstance( gate, ( Rx, Ry, Rz, XGate, YGate, ZGate, HGate, SGate, TGate, SqrtXGate, SwapGate, ), ) or gate in (Sdag, Tdag) if self.device == 'SV1': if get_control_count(cmd) == 2: return isinstance(gate, XGate) if get_control_count(cmd) == 1: return isinstance(gate, (R, ZGate, YGate, XGate, SwapGate)) if get_control_count(cmd) == 0: # TODO: add MatrixGate to cover the unitary operation # TODO: Missing XY gate in ProjectQ return isinstance( gate, ( R, Rx, Ry, Rz, XGate, YGate, ZGate, HGate, SGate, TGate, SqrtXGate, SwapGate, ), ) or gate in (Sdag, Tdag) return False
Return true if the command can be executed. Depending on the device chosen, the operations available differ. The operations available for the Aspen-8 Rigetti device are: - "cz" = Control Z, "xy" = Not available in ProjectQ, "ccnot" = Toffoli (ie. controlled CNOT), "cnot" = Control X, "cphaseshift" = Control R, "cphaseshift00" "cphaseshift01" "cphaseshift10" = Not available in ProjectQ, "cswap" = Control Swap, "h" = H, "i" = Identity, not in ProjectQ, "iswap" = Not available in ProjectQ, "phaseshift" = R, "pswap" = Not available in ProjectQ, "rx" = Rx, "ry" = Ry, "rz" = Rz, "s" = S, "si" = Sdag, "swap" = Swap, "t" = T, "ti" = Tdag, "x" = X, "y" = Y, "z" = Z The operations available for the IonQ Device are: - "x" = X, "y" = Y, "z" = Z, "rx" = Rx, "ry" = Ry, "rz" = Rz, "h", H, "cnot" = Control X, "s" = S, "si" = Sdag, "t" = T, "ti" = Tdag, "v" = SqrtX, "vi" = Not available in ProjectQ, "xx" "yy" "zz" = Not available in ProjectQ, "swap" = Swap, "i" = Identity, not in ProjectQ The operations available for the StateVector simulator (SV1) are the union of the ones for Rigetti Aspen-8 and IonQ Device plus some more: - "cy" = Control Y, "unitary" = Arbitrary unitary gate defined as a matrix equivalent to the MatrixGate in ProjectQ, "xy" = Not available in ProjectQ Args: cmd (Command): Command for which to check availability
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0
def _reset(self): """Reset all temporary variables (after flush gate).""" self._clear = True self._measured_ids = []
Reset all temporary variables (after flush gate).
_reset
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0
def _store(self, cmd): # pylint: disable=too-many-branches """ Temporarily store the command cmd. Translates the command and stores it in a local variable (self._circuit) in JSON format. Args: cmd: Command to store """ gate = cmd.gate # Do not clear the self._clear flag for those gates if gate in (Deallocate, Barrier): return num_controls = get_control_count(cmd) gate_type = ( type(gate) if not isinstance(gate, DaggeredGate) else type(gate._gate) # pylint: disable=protected-access ) if self._clear: self._probabilities = {} self._clear = False self._circuit = "" self._allocated_qubits = set() if gate == Allocate: self._allocated_qubits.add(cmd.qubits[0][0].id) return if gate == Measure: qb_id = cmd.qubits[0][0].id logical_id = None for tag in cmd.tags: if isinstance(tag, LogicalQubitIDTag): logical_id = tag.logical_qubit_id break self._measured_ids.append(logical_id if logical_id is not None else qb_id) return # All other supported gate types json_cmd = {} if num_controls > 1: json_cmd['controls'] = [qb.id for qb in cmd.control_qubits] elif num_controls == 1: json_cmd['control'] = cmd.control_qubits[0].id qubits = [qb.id for qureg in cmd.qubits for qb in qureg] if len(qubits) > 1: json_cmd['targets'] = qubits else: json_cmd['target'] = qubits[0] if isinstance(gate, (R, Rx, Ry, Rz)): json_cmd['angle'] = gate.angle if isinstance(gate, DaggeredGate): json_cmd['type'] = f"{'c' * num_controls + self._gationary[gate_type]}i" elif isinstance(gate, (XGate)) and num_controls > 0: json_cmd['type'] = f"{'c' * (num_controls - 1)}cnot" else: json_cmd['type'] = 'c' * num_controls + self._gationary[gate_type] self._circuit += f"{json.dumps(json_cmd)}, " # TODO: Add unitary for the SV1 simulator as MatrixGate
Temporarily store the command cmd. Translates the command and stores it in a local variable (self._circuit) in JSON format. Args: cmd: Command to store
_store
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0
def _logical_to_physical(self, qb_id): """ Return the physical location of the qubit with the given logical id. Args: qb_id (int): ID of the logical qubit whose position should be returned. """ if self.main_engine.mapper is not None: mapping = self.main_engine.mapper.current_mapping if qb_id not in mapping: raise RuntimeError( f"Unknown qubit id {qb_id} in current mapping. " "Please make sure eng.flush() was called and that the qubit was eliminated during optimization." ) return mapping[qb_id] return qb_id
Return the physical location of the qubit with the given logical id. Args: qb_id (int): ID of the logical qubit whose position should be returned.
_logical_to_physical
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0
def get_probabilities(self, qureg): """ Return the list of basis states with corresponding probabilities. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states. The measured bits are ordered according to the supplied quantum register, i.e., the left-most bit in the state-string corresponds to the first qubit in the supplied quantum register. Args: qureg (list<Qubit>): Quantum register determining the order of the qubits. Returns: probability_dict (dict): Dictionary mapping n-bit strings to probabilities. Raises: RuntimeError: If no data is available (i.e., if the circuit has not been executed). Or if a qubit was supplied which was not present in the circuit (might have gotten optimized away). Warning: Only call this function after the circuit has been executed! This is maintained in the same form of IBM and AQT for compatibility but in AWSBraket, a previously executed circuit will store the results in the S3 bucket and it can be retrieved at any point in time thereafter. No circuit execution should be required at the time of retrieving the results and probabilities if the circuit has already been executed. In order to obtain the probabilities of a previous job you have to get the TaskArn and remember the qubits and ordering used in the original job. """ if len(self._probabilities) == 0: raise RuntimeError("Please, run the circuit first!") probability_dict = {} for state, probability in self._probabilities.items(): mapped_state = ['0'] * len(qureg) for i, qubit in enumerate(qureg): if self._logical_to_physical(qubit.id) >= len(state): # pragma: no cover raise IndexError(f'Physical ID {qubit.id} > length of internal probabilities array') mapped_state[i] = state[self._logical_to_physical(qubit.id)] mapped_state = "".join(mapped_state) if mapped_state not in probability_dict: probability_dict[mapped_state] = probability else: probability_dict[mapped_state] += probability return probability_dict
Return the list of basis states with corresponding probabilities. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states. The measured bits are ordered according to the supplied quantum register, i.e., the left-most bit in the state-string corresponds to the first qubit in the supplied quantum register. Args: qureg (list<Qubit>): Quantum register determining the order of the qubits. Returns: probability_dict (dict): Dictionary mapping n-bit strings to probabilities. Raises: RuntimeError: If no data is available (i.e., if the circuit has not been executed). Or if a qubit was supplied which was not present in the circuit (might have gotten optimized away). Warning: Only call this function after the circuit has been executed! This is maintained in the same form of IBM and AQT for compatibility but in AWSBraket, a previously executed circuit will store the results in the S3 bucket and it can be retrieved at any point in time thereafter. No circuit execution should be required at the time of retrieving the results and probabilities if the circuit has already been executed. In order to obtain the probabilities of a previous job you have to get the TaskArn and remember the qubits and ordering used in the original job.
get_probabilities
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0
def _run(self): """ Run the circuit. Send the circuit via the AWS Boto3 SDK. Use the provided Access Key and Secret key or ask for them if not provided """ # NB: the AWS Braket API does not require explicit measurement commands at the end of a circuit; after running # any circuit, all qubits are implicitly measured. Also, AWS Braket currently does not support intermediate # measurements. # If the clear flag is set, nothing to do here... if self._clear: return # In Braket the results for the jobs are stored in S3. You can recover the results from previous jobs using # the TaskArn (self._retrieve_execution). if self._retrieve_execution is not None: res = retrieve( credentials=self._credentials, task_arn=self._retrieve_execution, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) else: # Return if no operations have been added. if not self._circuit: return n_qubit = len(self._allocated_qubits) info = {} info['circuit'] = self._circuithead + self._circuit.rstrip(', ') + self._circuittail info['nq'] = n_qubit info['shots'] = self._num_runs info['backend'] = {'name': self.device} res = send( info, device=self.device, credentials=self._credentials, s3_folder=self._s3_folder, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) counts = res # Determine random outcome random_outcome = random.random() p_sum = 0.0 measured = "" for state in counts: probability = counts[state] p_sum += probability star = "" if p_sum >= random_outcome and measured == "": measured = state star = "*" self._probabilities[state] = probability if self._verbose and probability > 0: print(f"{state} with p = {probability}{star}") # register measurement result for qubit_id in self._measured_ids: result = int(measured[self._logical_to_physical(qubit_id)]) self.main_engine.set_measurement_result(WeakQubitRef(self.main_engine, qubit_id), result) self._reset()
Run the circuit. Send the circuit via the AWS Boto3 SDK. Use the provided Access Key and Secret key or ask for them if not provided
_run
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0
def receive(self, command_list): """ Receives a command list and, for each command, stores it until completion. Args: command_list: List of commands to execute """ for cmd in command_list: if not isinstance(cmd.gate, FlushGate): self._store(cmd) else: self._run() self._reset() if not self.is_last_engine: self.send([cmd])
Receives a command list and, for each command, stores it until completion. Args: command_list: List of commands to execute
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0
def __init__(self): """Initialize a session with the AWS Braket Web APIs.""" self.backends = {} self.timeout = 5.0 self._credentials = {} self._s3_folder = []
Initialize a session with the AWS Braket Web APIs.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def authenticate(self, credentials=None): """ Authenticate with AWSBraket Web APIs. Args: credentials (dict): mapping the AWS key credentials as the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. """ if credentials is None: # pragma: no cover credentials['AWS_ACCESS_KEY_ID'] = getpass.getpass(prompt="Enter AWS_ACCESS_KEY_ID: ") credentials['AWS_SECRET_KEY'] = getpass.getpass(prompt="Enter AWS_SECRET_KEY: ") self._credentials = credentials
Authenticate with AWSBraket Web APIs. Args: credentials (dict): mapping the AWS key credentials as the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY.
authenticate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def get_s3_folder(self, s3_folder=None): """ Get the S3 bucket that contains the results. Args: s3_folder (list): contains the S3 bucket and directory to store the results. """ if s3_folder is None: # pragma: no cover s3_bucket = input("Enter the S3 Bucket configured in Braket: ") s3_directory = input("Enter the Directory created in the S3 Bucket: ") s3_folder = [s3_bucket, s3_directory] self._s3_folder = s3_folder
Get the S3 bucket that contains the results. Args: s3_folder (list): contains the S3 bucket and directory to store the results.
get_s3_folder
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def get_list_devices(self, verbose=False): """ Get the list of available devices with their basic properties. Args: verbose (bool): print the returned dictionary if True Returns: (dict) backends dictionary by deviceName, containing the qubit size 'nq', the coupling map 'coupling_map' if applicable (IonQ Device as an ion device is having full connectivity) and the Schema Header version 'version', because it seems that no device version is available by now """ # TODO: refresh region_names if more regions get devices available self.backends = {} region_names = ['us-west-1', 'us-east-1'] for region in region_names: client = boto3.client( 'braket', region_name=region, aws_access_key_id=self._credentials['AWS_ACCESS_KEY_ID'], aws_secret_access_key=self._credentials['AWS_SECRET_KEY'], ) filters = [] devicelist = client.search_devices(filters=filters) for result in devicelist['devices']: if result['deviceType'] not in ['QPU', 'SIMULATOR']: continue if result['deviceType'] == 'QPU': device_capabilities = json.loads( client.get_device(deviceArn=result['deviceArn'])['deviceCapabilities'] ) self.backends[result['deviceName']] = { 'nq': device_capabilities['paradigm']['qubitCount'], 'coupling_map': device_capabilities['paradigm']['connectivity']['connectivityGraph'], 'version': device_capabilities['braketSchemaHeader']['version'], 'location': region, # deviceCapabilities['service']['deviceLocation'], 'deviceArn': result['deviceArn'], 'deviceParameters': device_capabilities['deviceParameters']['properties']['braketSchemaHeader'][ 'const' ], 'deviceModelParameters': device_capabilities['deviceParameters']['definitions'][ 'GateModelParameters' ]['properties']['braketSchemaHeader']['const'], } # Unfortunately the Capabilities schemas are not homogeneus for real devices and simulators elif result['deviceType'] == 'SIMULATOR': device_capabilities = json.loads( client.get_device(deviceArn=result['deviceArn'])['deviceCapabilities'] ) self.backends[result['deviceName']] = { 'nq': device_capabilities['paradigm']['qubitCount'], 'coupling_map': {}, 'version': device_capabilities['braketSchemaHeader']['version'], 'location': 'us-east-1', 'deviceArn': result['deviceArn'], 'deviceParameters': device_capabilities['deviceParameters']['properties']['braketSchemaHeader'][ 'const' ], 'deviceModelParameters': device_capabilities['deviceParameters']['definitions'][ 'GateModelParameters' ]['properties']['braketSchemaHeader']['const'], } if verbose: print('- List of AWSBraket devices available:') print(list(self.backends)) return self.backends
Get the list of available devices with their basic properties. Args: verbose (bool): print the returned dictionary if True Returns: (dict) backends dictionary by deviceName, containing the qubit size 'nq', the coupling map 'coupling_map' if applicable (IonQ Device as an ion device is having full connectivity) and the Schema Header version 'version', because it seems that no device version is available by now
get_list_devices
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def is_online(self, device): """ Check if the device is in the list of available backends. Args: device (str): name of the device to check Returns: (bool) True if device is available, False otherwise """ # TODO: Add info for the device if it is actually ONLINE return device in self.backends
Check if the device is in the list of available backends. Args: device (str): name of the device to check Returns: (bool) True if device is available, False otherwise
is_online
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def can_run_experiment(self, info, device): """ Check if the device is big enough to run the code. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the device to use Returns: (tuple): (bool) True if device is big enough, False otherwise (int) maximum number of qubit available on the device (int) number of qubit needed for the circuit """ nb_qubit_max = self.backends[device]['nq'] nb_qubit_needed = info['nq'] return nb_qubit_needed <= nb_qubit_max, nb_qubit_max, nb_qubit_needed
Check if the device is big enough to run the code. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the device to use Returns: (tuple): (bool) True if device is big enough, False otherwise (int) maximum number of qubit available on the device (int) number of qubit needed for the circuit
can_run_experiment
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def run(self, info, device): """ Run the quantum code to the AWS Braket selected device. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the device to use Returns: task_arn (str): The Arn of the task """ argument = { 'circ': info['circuit'], 's3_folder': self._s3_folder, 'shots': info['shots'], } region_name = self.backends[device]['location'] device_parameters = { 'braketSchemaHeader': self.backends[device]['deviceParameters'], 'paradigmParameters': { 'braketSchemaHeader': self.backends[device]['deviceModelParameters'], 'qubitCount': info['nq'], 'disableQubitRewiring': False, }, } device_parameters = json.dumps(device_parameters) client_braket = boto3.client( 'braket', region_name=region_name, aws_access_key_id=self._credentials['AWS_ACCESS_KEY_ID'], aws_secret_access_key=self._credentials['AWS_SECRET_KEY'], ) response = client_braket.create_quantum_task( action=argument['circ'], deviceArn=self.backends[device]['deviceArn'], deviceParameters=device_parameters, outputS3Bucket=argument['s3_folder'][0], outputS3KeyPrefix=argument['s3_folder'][1], shots=argument['shots'], ) return response['quantumTaskArn']
Run the quantum code to the AWS Braket selected device. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the device to use Returns: task_arn (str): The Arn of the task
run
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def get_result(self, execution_id, num_retries=30, interval=1, verbose=False): # pylint: disable=too-many-locals """Get the result of an execution.""" if verbose: print(f"Waiting for results. [Job Arn: {execution_id}]") original_sigint_handler = signal.getsignal(signal.SIGINT) def _handle_sigint_during_get_result(*_): # pragma: no cover raise Exception(f"Interrupted. The Arn of your submitted job is {execution_id}.") def _calculate_measurement_probs(measurements): """ Calculate the measurement probabilities . Calculate the measurement probabilities based on the list of measurements for a job sent to a SV1 Braket simulator. Args: measurements (list): list of measurements Returns: measurementsProbabilities (dict): The measurements with their probabilities """ total_mes = len(measurements) unique_mes = [list(x) for x in {tuple(x) for x in measurements}] total_unique_mes = len(unique_mes) len_qubits = len(unique_mes[0]) measurements_probabilities = {} for i in range(total_unique_mes): strqubits = '' for qubit_idx in range(len_qubits): strqubits += str(unique_mes[i][qubit_idx]) prob = measurements.count(unique_mes[i]) / total_mes measurements_probabilities[strqubits] = prob return measurements_probabilities # The region_name is obtained from the task_arn itself region_name = re.split(':', execution_id)[3] client_braket = boto3.client( 'braket', region_name=region_name, aws_access_key_id=self._credentials['AWS_ACCESS_KEY_ID'], aws_secret_access_key=self._credentials['AWS_SECRET_KEY'], ) try: signal.signal(signal.SIGINT, _handle_sigint_during_get_result) for _ in range(num_retries): quantum_task = client_braket.get_quantum_task(quantumTaskArn=execution_id) status = quantum_task['status'] bucket = quantum_task['outputS3Bucket'] directory = quantum_task['outputS3Directory'] resultsojectname = f"{directory}/results.json" if status == 'COMPLETED': # Get the device type to obtian the correct measurement # structure devicetype_used = client_braket.get_device(deviceArn=quantum_task['deviceArn'])['deviceType'] # Get the results from S3 client_s3 = boto3.client( 's3', aws_access_key_id=self._credentials['AWS_ACCESS_KEY_ID'], aws_secret_access_key=self._credentials['AWS_SECRET_KEY'], ) s3result = client_s3.get_object(Bucket=bucket, Key=resultsojectname) if verbose: print(f"Results obtained. [Status: {status}]") result_content = json.loads(s3result['Body'].read()) if devicetype_used == 'QPU': return result_content['measurementProbabilities'] if devicetype_used == 'SIMULATOR': return _calculate_measurement_probs(result_content['measurements']) if status == 'FAILED': raise Exception( f'Error while running the code: {status}. ' f'The failure reason was: {quantum_task["failureReason"]}.' ) if status == 'CANCELLING': raise Exception(f"The job received a CANCEL operation: {status}.") time.sleep(interval) # NOTE: Be aware that AWS is billing if a lot of API calls are # executed, therefore the num_repetitions is set to a small # number by default. # For QPU devices the job is always queued and there are some # working hours available. # In addition the results and state is written in the # results.json file in the S3 Bucket and does not depend on the # status of the device finally: if original_sigint_handler is not None: signal.signal(signal.SIGINT, original_sigint_handler) raise RequestTimeoutError( f"Timeout. The Arn of your submitted job is {execution_id} and the status of the job is {status}." )
Get the result of an execution.
get_result
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def _calculate_measurement_probs(measurements): """ Calculate the measurement probabilities . Calculate the measurement probabilities based on the list of measurements for a job sent to a SV1 Braket simulator. Args: measurements (list): list of measurements Returns: measurementsProbabilities (dict): The measurements with their probabilities """ total_mes = len(measurements) unique_mes = [list(x) for x in {tuple(x) for x in measurements}] total_unique_mes = len(unique_mes) len_qubits = len(unique_mes[0]) measurements_probabilities = {} for i in range(total_unique_mes): strqubits = '' for qubit_idx in range(len_qubits): strqubits += str(unique_mes[i][qubit_idx]) prob = measurements.count(unique_mes[i]) / total_mes measurements_probabilities[strqubits] = prob return measurements_probabilities
Calculate the measurement probabilities . Calculate the measurement probabilities based on the list of measurements for a job sent to a SV1 Braket simulator. Args: measurements (list): list of measurements Returns: measurementsProbabilities (dict): The measurements with their probabilities
_calculate_measurement_probs
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def show_devices(credentials=None, verbose=False): """ Access the list of available devices and their properties (ex: for setup configuration). Args: credentials (dict): Dictionary storing the AWS credentials with keys AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. verbose (bool): If True, additional information is printed Returns: (list) list of available devices and their properties """ awsbraket_session = AWSBraket() awsbraket_session.authenticate(credentials=credentials) return awsbraket_session.get_list_devices(verbose=verbose)
Access the list of available devices and their properties (ex: for setup configuration). Args: credentials (dict): Dictionary storing the AWS credentials with keys AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. verbose (bool): If True, additional information is printed Returns: (list) list of available devices and their properties
show_devices
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def retrieve(credentials, task_arn, num_retries=30, interval=1, verbose=False): """ Retrieve a job/task by its Arn. Args: credentials (dict): Dictionary storing the AWS credentials with keys AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. task_arn (str): The Arn of the task to retrieve Returns: (dict) measurement probabilities from the result stored in the S3 folder """ try: awsbraket_session = AWSBraket() if verbose: print("- Authenticating...") if credentials is not None: print(f"AWS credentials: {credentials['AWS_ACCESS_KEY_ID']}, {credentials['AWS_SECRET_KEY']}") awsbraket_session.authenticate(credentials=credentials) res = awsbraket_session.get_result(task_arn, num_retries=num_retries, interval=interval, verbose=verbose) return res except botocore.exceptions.ClientError as error: error_code = error.response['Error']['Code'] if error_code == 'ResourceNotFoundException': print("- Unable to locate the job with Arn ", task_arn) print(error, error_code) raise
Retrieve a job/task by its Arn. Args: credentials (dict): Dictionary storing the AWS credentials with keys AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. task_arn (str): The Arn of the task to retrieve Returns: (dict) measurement probabilities from the result stored in the S3 folder
retrieve
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def send( # pylint: disable=too-many-branches,too-many-arguments,too-many-locals info, device, credentials, s3_folder, num_retries=30, interval=1, verbose=False ): """ Send circuit through the Boto3 SDK and runs the quantum circuit. Args: info(dict): Contains representation of the circuit to run. device (str): name of the AWS Braket device. credentials (dict): Dictionary storing the AWS credentials with keys AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. s3_folder (list): Contains the S3 bucket and directory to store the results. verbose (bool): If True, additional information is printed, such as measurement statistics. Otherwise, the backend simply registers one measurement result (same behavior as the projectq Simulator). Returns: (list) samples from the AWS Braket device """ try: awsbraket_session = AWSBraket() if verbose: print("- Authenticating...") if credentials is not None: print(f"AWS credentials: {credentials['AWS_ACCESS_KEY_ID']}, {credentials['AWS_SECRET_KEY']}") awsbraket_session.authenticate(credentials=credentials) awsbraket_session.get_s3_folder(s3_folder=s3_folder) # check if the device is online/is available awsbraket_session.get_list_devices(verbose) online = awsbraket_session.is_online(device) if online: print("The job will be queued in any case, please take this into account") else: print("The device is not available. Use the simulator instead or try another device.") raise DeviceOfflineError("Device is not available.") # check if the device has enough qubit to run the code runnable, qmax, qneeded = awsbraket_session.can_run_experiment(info, device) if not runnable: print( f"The device is too small ({qmax} qubits available) for the code", f"requested({qneeded} qubits needed). Try to look for another device with more qubits", ) raise DeviceTooSmall("Device is too small.") if verbose: print(f"- Running code: {info}") task_arn = awsbraket_session.run(info, device) print(f"Your task Arn is: {task_arn}. Make note of that for future reference") if verbose: print("- Waiting for results...") res = awsbraket_session.get_result(task_arn, num_retries=num_retries, interval=interval, verbose=verbose) if verbose: print("- Done.") return res except botocore.exceptions.ClientError as error: error_code = error.response['Error']['Code'] if error_code == 'AccessDeniedException': print("- There was an error: the access to Braket was denied") if error_code == 'DeviceOfflineException': print("- There was an error: the device is offline") if error_code == 'InternalServiceException': print("- There was an internal Bracket service error") if error_code == 'ServiceQuotaExceededException': print("- There was an error: the quota on Braket was exceed") if error_code == 'ValidationException': print("- There was a Validation error") print(error, error_code) raise
Send circuit through the Boto3 SDK and runs the quantum circuit. Args: info(dict): Contains representation of the circuit to run. device (str): name of the AWS Braket device. credentials (dict): Dictionary storing the AWS credentials with keys AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. s3_folder (list): Contains the S3 bucket and directory to store the results. verbose (bool): If True, additional information is printed, such as measurement statistics. Otherwise, the backend simply registers one measurement result (same behavior as the projectq Simulator). Returns: (list) samples from the AWS Braket device
send
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client.py
Apache-2.0
def retrieve_devicetypes_setup(request, arntask, creds, results_json, device_value_devicecapabilities): """Retrieve device types value test setup.""" if request.param == "qpu": body_qpu = StreamingBody(StringIO(results_json), len(results_json)) results_dict = { 'ResponseMetadata': { 'RequestId': 'CF4CAA48CC18836C', 'HTTPHeaders': {}, }, 'Body': body_qpu, } device_value = { "deviceName": "Aspen-8", "deviceType": "QPU", "providerName": "provider1", "deviceStatus": "OFFLINE", "deviceCapabilities": device_value_devicecapabilities, } res_completed = {"000": 0.1, "010": 0.4, "110": 0.1, "001": 0.1, "111": 0.3} else: results_json_simulator = json.dumps( { "braketSchemaHeader": { "name": "braket.task_result.gate_model_task_result", "version": "1", }, "measurements": [ [0, 0], [0, 1], [1, 1], [0, 1], [0, 1], [1, 1], [1, 1], [1, 1], [1, 1], [1, 1], ], "measuredQubits": [0, 1], } ) body_simulator = StreamingBody(StringIO(results_json_simulator), len(results_json_simulator)) results_dict = { 'ResponseMetadata': { 'RequestId': 'CF4CAA48CC18836C', 'HTTPHeaders': {}, }, 'Body': body_simulator, } device_value = { "deviceName": "SV1", "deviceType": "SIMULATOR", "providerName": "providerA", "deviceStatus": "ONLINE", "deviceCapabilities": device_value_devicecapabilities, } res_completed = {"00": 0.1, "01": 0.3, "11": 0.6} return arntask, creds, device_value, results_dict, res_completed
Retrieve device types value test setup.
retrieve_devicetypes_setup
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client_test_fixtures.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client_test_fixtures.py
Apache-2.0
def send_too_many_setup(creds, s3_folder, search_value, device_value): """Send too many value test setup.""" info_too_much = { 'circuit': '{"braketSchemaHeader":' '{"name": "braket.ir.jaqcd.program", "version": "1"}, ' '"results": [], "basis_rotation_instructions": [], ' '"instructions": [{"target": 0, "type": "h"}, {\ "target": 1, "type": "h"}, {\ "control": 1, "target": 2, "type": "cnot"}]}', 'nq': 100, 'shots': 1, 'backend': {'name': 'name2'}, } return creds, s3_folder, search_value, device_value, info_too_much
Send too many value test setup.
send_too_many_setup
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client_test_fixtures.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client_test_fixtures.py
Apache-2.0
def real_device_online_setup( arntask, creds, s3_folder, info, search_value, device_value, res_completed, results_json, ): """Real device online value test setup.""" qtarntask = {'quantumTaskArn': arntask} body = StreamingBody(StringIO(results_json), len(results_json)) results_dict = { 'ResponseMetadata': { 'RequestId': 'CF4CAA48CC18836C', 'HTTPHeaders': {}, }, 'Body': body, } return ( qtarntask, creds, s3_folder, info, search_value, device_value, res_completed, results_dict, )
Real device online value test setup.
real_device_online_setup
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_boto3_client_test_fixtures.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_boto3_client_test_fixtures.py
Apache-2.0
def mapper(request): """ Adds a mapper which changes qubit ids by adding 1 """ if request.param == "mapper": class TrivialMapper(BasicMapperEngine): def __init__(self): super().__init__() self.current_mapping = {} def receive(self, command_list): for cmd in command_list: for qureg in cmd.all_qubits: for qubit in qureg: if qubit.id == -1: continue elif qubit.id not in self.current_mapping: previous_map = self.current_mapping previous_map[qubit.id] = qubit.id self.current_mapping = previous_map self._send_cmd_with_mapped_ids(cmd) return TrivialMapper() if request.param == "no_mapper": return None
Adds a mapper which changes qubit ids by adding 1
mapper
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket_test.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket_test.py
Apache-2.0
def _reset(self): """ Reset this backend. Note: This sets ``_clear = True``, which will trigger state cleanup on the next call to ``_store``. """ # Lastly, reset internal state for measured IDs and circuit body. self._circuit = None self._clear = True
Reset this backend. Note: This sets ``_clear = True``, which will trigger state cleanup on the next call to ``_store``.
_reset
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_azure_quantum.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_azure_quantum.py
Apache-2.0
def _store(self, cmd): # pylint: disable=too-many-branches """ Temporarily store the command cmd. Translates the command and stores it in a local variable (self._cmds). Args: cmd (Command): Command to store """ if self._clear: self._probabilities = {} self._clear = False self._circuit = None gate = cmd.gate # No-op/Meta gates if isinstance(gate, (AllocateQubitGate, DeallocateQubitGate)): return # Measurement if isinstance(gate, MeasureGate): logical_id = None for tag in cmd.tags: if isinstance(tag, LogicalQubitIDTag): logical_id = tag.logical_qubit_id break if logical_id is None: raise RuntimeError('No LogicalQubitIDTag found in command!') self._measured_ids.append(logical_id) return if self._provider_id == IONQ_PROVIDER_ID: if not self._circuit: self._circuit = [] json_cmd = to_json(cmd) if json_cmd: self._circuit.append(json_cmd) elif self._provider_id == QUANTINUUM_PROVIDER_ID: if not self._circuit: self._circuit = '' qasm_cmd = to_qasm(cmd) if qasm_cmd: self._circuit += f'\n{qasm_cmd}' else: raise RuntimeError("Invalid Azure Quantum target.")
Temporarily store the command cmd. Translates the command and stores it in a local variable (self._cmds). Args: cmd (Command): Command to store
_store
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_azure_quantum.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_azure_quantum.py
Apache-2.0
def is_available(self, cmd): """ Test if this backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command. """ if self._provider_id == IONQ_PROVIDER_ID: return is_available_ionq(cmd) if self._provider_id == QUANTINUUM_PROVIDER_ID: return is_available_quantinuum(cmd) return False
Test if this backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command.
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_azure_quantum.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_azure_quantum.py
Apache-2.0
def get_probability(self, state, qureg): """Shortcut to get a specific state's probability. Args: state (str): A state in bit-string format. qureg (Qureg): A ProjectQ Qureg object. Returns: float: The probability for the provided state. """ if len(state) != len(qureg): raise ValueError('Desired state and register must be the same length!') probs = self.get_probabilities(qureg) return probs.get(state, 0.0)
Shortcut to get a specific state's probability. Args: state (str): A state in bit-string format. qureg (Qureg): A ProjectQ Qureg object. Returns: float: The probability for the provided state.
get_probability
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_azure_quantum.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_azure_quantum.py
Apache-2.0
def get_probabilities(self, qureg): """ Given the provided qubit register, determine the probability of each possible outcome. Note: This method should only be called *after* a circuit has been run and its results are available. Args: qureg (Qureg): A ProjectQ Qureg object. Returns: dict: A dict mapping of states -> probability. """ if len(self._probabilities) == 0: raise RuntimeError("Please, run the circuit first!") probability_dict = {} for state in self._probabilities: mapped_state = ['0'] * len(qureg) for i, qubit in enumerate(qureg): try: meas_idx = self._measured_ids.index(qubit.id) except ValueError: continue mapped_state[i] = state[meas_idx] probability = self._probabilities[state] mapped_state = "".join(mapped_state) probability_dict[mapped_state] = probability_dict.get(mapped_state, 0) + probability return probability_dict
Given the provided qubit register, determine the probability of each possible outcome. Note: This method should only be called *after* a circuit has been run and its results are available. Args: qureg (Qureg): A ProjectQ Qureg object. Returns: dict: A dict mapping of states -> probability.
get_probabilities
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_azure_quantum.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_azure_quantum.py
Apache-2.0
def _run(self): # pylint: disable=too-many-locals """Run the circuit this object has built during engine execution.""" # Nothing to do with an empty circuit. if not self._circuit: return if self._retrieve_execution is None: res = send( input_data=self._input_data, metadata=self._metadata, num_shots=self._num_runs, target=self._target, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) if res is None: # pragma: no cover raise RuntimeError('Failed to submit job to the Azure Quantum!') else: res = retrieve( job_id=self._retrieve_execution, target=self._target, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) if res is None: raise RuntimeError( f"Failed to retrieve job from Azure Quantum with job id: '{self._retrieve_execution}'!" ) if self._provider_id == IONQ_PROVIDER_ID: self._probabilities = { _rearrange_result(int(k), len(self._measured_ids)): v for k, v in res["histogram"].items() } elif self._provider_id == QUANTINUUM_PROVIDER_ID: histogram = Counter(res["c"]) self._probabilities = {k: v / self._num_runs for k, v in histogram.items()} else: # pragma: no cover raise RuntimeError("Invalid Azure Quantum target.") # Set a single measurement result bitstring = np.random.choice(list(self._probabilities.keys()), p=list(self._probabilities.values())) for qid in self._measured_ids: qubit_ref = WeakQubitRef(self.main_engine, qid) self.main_engine.set_measurement_result(qubit_ref, bitstring[qid])
Run the circuit this object has built during engine execution.
_run
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_azure_quantum.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_azure_quantum.py
Apache-2.0
def retrieve(job_id, target, num_retries=100, interval=1, verbose=False): """ Retrieve a job from Azure Quantum. Args: job_id (str), Azure Quantum job id. target (Target), The target job runs on. num_retries (int, optional): Number of times to retry while the job is not finished. Defaults to 100. interval (int, optional): Sleep interval between retries, in seconds. Defaults to 1. verbose (bool, optional): Whether to print verbose output. Defaults to False. Returns: dict: An intermediate dict representation of an Azure Quantum job result. """ job = target.workspace.get_job(job_id=job_id) res = _get_results(job=job, num_retries=num_retries, interval=interval, verbose=verbose) if verbose: print("- Done.") return res
Retrieve a job from Azure Quantum. Args: job_id (str), Azure Quantum job id. target (Target), The target job runs on. num_retries (int, optional): Number of times to retry while the job is not finished. Defaults to 100. interval (int, optional): Sleep interval between retries, in seconds. Defaults to 1. verbose (bool, optional): Whether to print verbose output. Defaults to False. Returns: dict: An intermediate dict representation of an Azure Quantum job result.
retrieve
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_azure_quantum_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_azure_quantum_client.py
Apache-2.0
def is_available_ionq(cmd): """ Test if IonQ backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command. """ gate = cmd.gate if has_negative_control(cmd): return False if isinstance(gate, ControlledGate): num_ctrl_qubits = gate._n # pylint: disable=protected-access else: num_ctrl_qubits = get_control_count(cmd) # Get base gate wrapped in ControlledGate class if isinstance(gate, ControlledGate): gate = gate._gate # pylint: disable=protected-access # NOTE: IonQ supports up to 7 control qubits if 0 < num_ctrl_qubits <= 7: return isinstance(gate, (XGate,)) # Gates without control bits if num_ctrl_qubits == 0: supported = isinstance(gate, IONQ_SUPPORTED_GATES) supported_meta = isinstance(gate, (MeasureGate, AllocateQubitGate, DeallocateQubitGate)) supported_transpose = gate in (Sdag, Tdag, Vdag) return supported or supported_meta or supported_transpose return False
Test if IonQ backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command.
is_available_ionq
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_utils.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_utils.py
Apache-2.0
def is_available_quantinuum(cmd): """ Test if Quantinuum backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command. """ gate = cmd.gate if has_negative_control(cmd): return False if isinstance(gate, ControlledGate): num_ctrl_qubits = gate._n # pylint: disable=protected-access else: num_ctrl_qubits = get_control_count(cmd) # Get base gate wrapped in ControlledGate class if isinstance(gate, ControlledGate): gate = gate._gate # pylint: disable=protected-access # TODO: NEEDED CONFIRMATION- Does Quantinuum support more than 2 control gates? if 0 < num_ctrl_qubits <= 2: return isinstance(gate, (XGate, ZGate)) # Gates without control bits. if num_ctrl_qubits == 0: supported = isinstance(gate, QUANTINUUM_SUPPORTED_GATES) supported_meta = isinstance(gate, (MeasureGate, AllocateQubitGate, DeallocateQubitGate, BarrierGate)) supported_transpose = gate in (Sdag, Tdag) return supported or supported_meta or supported_transpose return False
Test if Quantinuum backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command.
is_available_quantinuum
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_utils.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_utils.py
Apache-2.0
def to_json(cmd): """ Convert ProjectQ command to JSON format. Args: cmd (Command): A command to process. Returns: dict: JSON format of given command. """ # Invalid command, raise exception if not is_available_ionq(cmd): raise InvalidCommandError('Invalid command:', str(cmd)) gate = cmd.gate if isinstance(gate, ControlledGate): inner_gate = gate._gate # pylint: disable=protected-access gate_type = type(inner_gate) elif isinstance(gate, DaggeredGate): gate_type = type(gate.get_inverse()) else: gate_type = type(gate) gate_name = IONQ_GATE_MAP.get(gate_type) # Daggered gates get special treatment if isinstance(gate, DaggeredGate): gate_name = gate_name + 'i' # Controlled gates get special treatment too if isinstance(gate, ControlledGate): all_qubits = [qb.id for qureg in cmd.qubits for qb in qureg] controls = all_qubits[: gate._n] # pylint: disable=protected-access targets = all_qubits[gate._n :] # noqa: E203 # pylint: disable=protected-access else: controls = [qb.id for qb in cmd.control_qubits] targets = [qb.id for qureg in cmd.qubits for qb in qureg] # Initialize the gate dict gate_dict = {'gate': gate_name, 'targets': targets} # Check if we have a rotation if isinstance(gate, (R, Rx, Ry, Rz, Rxx, Ryy, Rzz)): gate_dict['rotation'] = gate.angle # Set controls if len(controls) > 0: gate_dict['controls'] = controls return gate_dict
Convert ProjectQ command to JSON format. Args: cmd (Command): A command to process. Returns: dict: JSON format of given command.
to_json
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_utils.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_utils.py
Apache-2.0
def to_qasm(cmd): # pylint: disable=too-many-return-statements,too-many-branches """ Convert ProjectQ command to QASM format. Args: cmd (Command): A command to process. Returns: dict: QASM format of given command. """ # Invalid command, raise exception if not is_available_quantinuum(cmd): raise InvalidCommandError('Invalid command:', str(cmd)) gate = cmd.gate if isinstance(gate, ControlledGate): inner_gate = gate._gate # pylint: disable=protected-access gate_type = type(inner_gate) elif isinstance(gate, DaggeredGate): gate_type = type(gate.get_inverse()) else: gate_type = type(gate) gate_name = QUANTINUUM_GATE_MAP.get(gate_type) # Daggered gates get special treatment if isinstance(gate, DaggeredGate): gate_name = gate_name + 'dg' # Controlled gates get special treatment too if isinstance(gate, ControlledGate): all_qubits = [qb.id for qureg in cmd.qubits for qb in qureg] controls = all_qubits[: gate._n] # pylint: disable=protected-access targets = all_qubits[gate._n :] # noqa: E203 # pylint: disable=protected-access else: controls = [qb.id for qb in cmd.control_qubits] targets = [qb.id for qureg in cmd.qubits for qb in qureg] # Barrier gate if isinstance(gate, BarrierGate): qb_str = "" for pos in targets: qb_str += f"q[{pos}], " return f"{gate_name} {qb_str[:-2]};" # Daggered gates if gate in (Sdag, Tdag): return f"{gate_name} q[{targets[0]}];" # Controlled gates if len(controls) > 0: # 1-Controlled gates if len(controls) == 1: gate_name = 'c' + gate_name return f"{gate_name} q[{controls[0]}], q[{targets[0]}];" # 2-Controlled gates if len(controls) == 2: gate_name = 'cc' + gate_name return f"{gate_name} q[{controls[0]}], q[{controls[1]}], q[{targets[0]}];" raise InvalidCommandError('Invalid command:', str(cmd)) # pragma: no cover # Single qubit gates if len(targets) == 1: # Standard gates if isinstance(gate, (HGate, XGate, YGate, ZGate, SGate, TGate)): return f"{gate_name} q[{targets[0]}];" # Rotational gates if isinstance(gate, (Rx, Ry, Rz)): return f"{gate_name}({gate.angle}) q[{targets[0]}];" raise InvalidCommandError('Invalid command:', str(cmd)) # pragma: no cover # Two qubit gates if len(targets) == 2: # Rotational gates if isinstance(gate, (Rxx, Ryy, Rzz)): return f"{gate_name}({gate.angle}) q[{targets[0]}], q[{targets[1]}];" raise InvalidCommandError('Invalid command:', str(cmd)) # Invalid command raise InvalidCommandError('Invalid command:', str(cmd)) # pragma: no cover
Convert ProjectQ command to QASM format. Args: cmd (Command): A command to process. Returns: dict: QASM format of given command.
to_qasm
python
ProjectQ-Framework/ProjectQ
projectq/backends/_azure/_utils.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_azure/_utils.py
Apache-2.0
def __init__(self, gate, lines, ctrl_lines): """ Initialize a circuit item. Args: gate: Gate object. lines (list<int>): Circuit lines the gate acts on. ctrl_lines (list<int>): Circuit lines which control the gate. """ self.gate = gate self.lines = lines self.ctrl_lines = ctrl_lines self.id = -1
Initialize a circuit item. Args: gate: Gate object. lines (list<int>): Circuit lines the gate acts on. ctrl_lines (list<int>): Circuit lines which control the gate.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer.py
Apache-2.0
def __init__(self, accept_input=False, default_measure=0): """ Initialize a circuit drawing engine. The TikZ code generator uses a settings file (settings.json), which can be altered by the user. It contains gate widths, heights, offsets, etc. Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CircuitDrawer is the last engine. Otherwise, all measurements yield the result default_measure (0 or 1). default_measure (bool): Default value to use as measurement results if accept_input is False and there is no underlying backend to register real measurement results. """ super().__init__() self._accept_input = accept_input self._default_measure = default_measure self._qubit_lines = {} self._free_lines = [] self._map = {} # Order in which qubit lines are drawn self._drawing_order = []
Initialize a circuit drawing engine. The TikZ code generator uses a settings file (settings.json), which can be altered by the user. It contains gate widths, heights, offsets, etc. Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CircuitDrawer is the last engine. Otherwise, all measurements yield the result default_measure (0 or 1). default_measure (bool): Default value to use as measurement results if accept_input is False and there is no underlying backend to register real measurement results.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer.py
Apache-2.0
def is_available(self, cmd): """ Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the CircuitDrawer is the last engine (since it can print any command). Args: cmd (Command): Command for which to check availability (all Commands can be printed). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine). """ try: return BasicEngine.is_available(self, cmd) except LastEngineException: return True
Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the CircuitDrawer is the last engine (since it can print any command). Args: cmd (Command): Command for which to check availability (all Commands can be printed). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine).
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer.py
Apache-2.0
def set_qubit_locations(self, id_to_loc): """ Set the qubit lines to use for the qubits explicitly. To figure out the qubit IDs, simply use the setting `draw_id` in the settings file. It is located in "gates":"AllocateQubitGate". If draw_id is True, the qubit IDs are drawn in red. Args: id_to_loc (dict): Dictionary mapping qubit ids to qubit line numbers. Raises: RuntimeError: If the mapping has already begun (this function needs be called before any gates have been received). """ if len(self._map) > 0: raise RuntimeError("set_qubit_locations() has to be called before applying gates!") for k in range(min(id_to_loc), max(id_to_loc) + 1): if k not in id_to_loc: raise RuntimeError( "set_qubit_locations(): Invalid id_to_loc " "mapping provided. All ids in the provided" " range of qubit ids have to be mapped " "somewhere." ) self._map = id_to_loc
Set the qubit lines to use for the qubits explicitly. To figure out the qubit IDs, simply use the setting `draw_id` in the settings file. It is located in "gates":"AllocateQubitGate". If draw_id is True, the qubit IDs are drawn in red. Args: id_to_loc (dict): Dictionary mapping qubit ids to qubit line numbers. Raises: RuntimeError: If the mapping has already begun (this function needs be called before any gates have been received).
set_qubit_locations
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer.py
Apache-2.0
def _print_cmd(self, cmd): """ Add a command to the list of commands to be printed. Add the command cmd to the circuit diagram, taking care of potential measurements as specified in the __init__ function. Queries the user for measurement input if a measurement command arrives if accept_input was set to True. Otherwise, it uses the default_measure parameter to register the measurement outcome. Args: cmd (Command): Command to add to the circuit diagram. """ # pylint: disable=R0801 if cmd.gate == Allocate: qubit_id = cmd.qubits[0][0].id if qubit_id not in self._map: self._map[qubit_id] = qubit_id self._qubit_lines[qubit_id] = [] if cmd.gate == Deallocate: qubit_id = cmd.qubits[0][0].id self._free_lines.append(qubit_id) if self.is_last_engine and cmd.gate == Measure: if get_control_count(cmd) != 0: raise ValueError('Cannot have control qubits with a measurement gate!') for qureg in cmd.qubits: for qubit in qureg: if self._accept_input: meas = None while meas not in ('0', '1', 1, 0): prompt = f"Input measurement result (0 or 1) for qubit {str(qubit)}: " meas = input(prompt) else: meas = self._default_measure meas = int(meas) self.main_engine.set_measurement_result(qubit, meas) all_lines = [qb.id for qr in cmd.all_qubits for qb in qr] gate = cmd.gate lines = [qb.id for qr in cmd.qubits for qb in qr] ctrl_lines = [qb.id for qb in cmd.control_qubits] item = CircuitItem(gate, lines, ctrl_lines) for line in all_lines: self._qubit_lines[line].append(item) self._drawing_order.append(all_lines[0])
Add a command to the list of commands to be printed. Add the command cmd to the circuit diagram, taking care of potential measurements as specified in the __init__ function. Queries the user for measurement input if a measurement command arrives if accept_input was set to True. Otherwise, it uses the default_measure parameter to register the measurement outcome. Args: cmd (Command): Command to add to the circuit diagram.
_print_cmd
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer.py
Apache-2.0
def get_latex(self, ordered=False, draw_gates_in_parallel=True): """ Return the latex document string representing the circuit. Simply write this string into a tex-file or, alternatively, pipe the output directly to, e.g., pdflatex: .. code-block:: bash python3 my_circuit.py | pdflatex where my_circuit.py calls this function and prints it to the terminal. Args: ordered(bool): flag if the gates should be drawn in the order they were added to the circuit draw_gates_in_parallel(bool): flag if parallel gates should be drawn parallel (True), or not (False) """ qubit_lines = {} for line, qubit_line in self._qubit_lines.items(): new_line = self._map[line] qubit_lines[new_line] = [] for cmd in qubit_line: lines = [self._map[qb_id] for qb_id in cmd.lines] ctrl_lines = [self._map[qb_id] for qb_id in cmd.ctrl_lines] gate = cmd.gate new_cmd = CircuitItem(gate, lines, ctrl_lines) if gate == Allocate: new_cmd.id = cmd.lines[0] qubit_lines[new_line].append(new_cmd) drawing_order = None if ordered: drawing_order = self._drawing_order return to_latex( qubit_lines, drawing_order=drawing_order, draw_gates_in_parallel=draw_gates_in_parallel, )
Return the latex document string representing the circuit. Simply write this string into a tex-file or, alternatively, pipe the output directly to, e.g., pdflatex: .. code-block:: bash python3 my_circuit.py | pdflatex where my_circuit.py calls this function and prints it to the terminal. Args: ordered(bool): flag if the gates should be drawn in the order they were added to the circuit draw_gates_in_parallel(bool): flag if parallel gates should be drawn parallel (True), or not (False)
get_latex
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine. Args: command_list (list<Command>): List of Commands to print (and potentially send on to the next engine). """ for cmd in command_list: if not cmd.gate == FlushGate(): self._print_cmd(cmd) # (try to) send on if not self.is_last_engine: self.send([cmd])
Receive a list of commands. Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine. Args: command_list (list<Command>): List of Commands to print (and potentially send on to the next engine).
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer.py
Apache-2.0
def __init__(self, accept_input=False, default_measure=0): """ Initialize a circuit drawing engine(mpl). Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CircuitDrawerMPL is the last engine. Otherwise, all measurements yield the result default_measure (0 or 1). default_measure (bool): Default value to use as measurement results if accept_input is False and there is no underlying backend to register real measurement results. """ super().__init__() self._accept_input = accept_input self._default_measure = default_measure self._map = {} self._qubit_lines = {}
Initialize a circuit drawing engine(mpl). Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CircuitDrawerMPL is the last engine. Otherwise, all measurements yield the result default_measure (0 or 1). default_measure (bool): Default value to use as measurement results if accept_input is False and there is no underlying backend to register real measurement results.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer_matplotlib.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer_matplotlib.py
Apache-2.0
def is_available(self, cmd): """ Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the CircuitDrawerMatplotlib is the last engine (since it can print any command). Args: cmd (Command): Command for which to check availability (all Commands can be printed). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine). """ try: # Multi-qubit gates may fail at drawing time if the target qubits # are not right next to each other on the output graphic. return BasicEngine.is_available(self, cmd) except LastEngineException: return True
Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the CircuitDrawerMatplotlib is the last engine (since it can print any command). Args: cmd (Command): Command for which to check availability (all Commands can be printed). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine).
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer_matplotlib.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer_matplotlib.py
Apache-2.0
def _process(self, cmd): # pylint: disable=too-many-branches """ Process the command cmd and stores it in the internal storage. Queries the user for measurement input if a measurement command arrives if accept_input was set to True. Otherwise, it uses the default_measure parameter to register the measurement outcome. Args: cmd (Command): Command to add to the circuit diagram. """ # pylint: disable=R0801 if cmd.gate == Allocate: qb_id = cmd.qubits[0][0].id if qb_id not in self._map: self._map[qb_id] = qb_id self._qubit_lines[qb_id] = [] return if cmd.gate == Deallocate: return if self.is_last_engine and cmd.gate == Measure: if get_control_count(cmd) != 0: raise ValueError('Cannot have control qubits with a measurement gate!') for qureg in cmd.qubits: for qubit in qureg: if self._accept_input: measurement = None while measurement not in ('0', '1', 1, 0): prompt = f"Input measurement result (0 or 1) for qubit {qubit}: " measurement = input(prompt) else: measurement = self._default_measure self.main_engine.set_measurement_result(qubit, int(measurement)) targets = [qubit.id for qureg in cmd.qubits for qubit in qureg] controls = [qubit.id for qubit in cmd.control_qubits] ref_qubit_id = targets[0] gate_str = _format_gate_str(cmd) # First find out what is the maximum index that this command might # have max_depth = max(len(self._qubit_lines[qubit_id]) for qubit_id in itertools.chain(targets, controls)) # If we have a multi-qubit gate, make sure that all the qubit axes # have the same depth. We do that by recalculating the maximum index # over all the known qubit axes. # This is to avoid the possibility of a multi-qubit gate overlapping # with some other gates. This could potentially be improved by only # considering the qubit axes that are between the topmost and # bottommost qubit axes of the current command. if len(targets) + len(controls) > 1: max_depth = max(len(line) for qubit_id, line in self._qubit_lines.items()) for qb_id in itertools.chain(targets, controls): depth = len(self._qubit_lines[qb_id]) self._qubit_lines[qb_id] += [None] * (max_depth - depth) if qb_id == ref_qubit_id: self._qubit_lines[qb_id].append((gate_str, targets, controls)) else: self._qubit_lines[qb_id].append(None)
Process the command cmd and stores it in the internal storage. Queries the user for measurement input if a measurement command arrives if accept_input was set to True. Otherwise, it uses the default_measure parameter to register the measurement outcome. Args: cmd (Command): Command to add to the circuit diagram.
_process
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer_matplotlib.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer_matplotlib.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine. Args: command_list (list<Command>): List of Commands to print (and potentially send on to the next engine). """ for cmd in command_list: if not isinstance(cmd.gate, FlushGate): self._process(cmd) if not self.is_last_engine: self.send([cmd])
Receive a list of commands. Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine. Args: command_list (list<Command>): List of Commands to print (and potentially send on to the next engine).
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer_matplotlib.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer_matplotlib.py
Apache-2.0
def draw(self, qubit_labels=None, drawing_order=None, **kwargs): """ Generate and returns the plot of the quantum circuit stored so far. Args: qubit_labels (dict): label for each wire in the output figure. Keys: qubit IDs, Values: string to print out as label for that particular qubit wire. drawing_order (dict): position of each qubit in the output graphic. Keys: qubit IDs, Values: position of qubit on the qubit line in the graphic. **kwargs (dict): additional parameters are used to update the default plot parameters Returns: A tuple containing the matplotlib figure and axes objects Note: Additional keyword arguments can be passed to this function in order to further customize the figure output by matplotlib (default value in parentheses): - fontsize (14): Font size in pt - column_spacing (.5): Vertical spacing between two neighbouring gates (roughly in inches) - control_radius (.015): Radius of the circle for controls - labels_margin (1): Margin between labels and begin of wire (roughly in inches) - linewidth (1): Width of line - not_radius (.03): Radius of the circle for X/NOT gates - gate_offset (.05): Inner margins for gates with a text representation - mgate_width (.1): Width of the measurement gate - swap_delta (.02): Half-size of the SWAP gate - x_offset (.05): Absolute X-offset for drawing within the axes - wire_height (1): Vertical spacing between two qubit wires (roughly in inches) """ max_depth = max(len(line) for qubit_id, line in self._qubit_lines.items()) for qubit_id, line in self._qubit_lines.items(): depth = len(line) if depth < max_depth: self._qubit_lines[qubit_id] += [None] * (max_depth - depth) return to_draw( self._qubit_lines, qubit_labels=qubit_labels, drawing_order=drawing_order, **kwargs, )
Generate and returns the plot of the quantum circuit stored so far. Args: qubit_labels (dict): label for each wire in the output figure. Keys: qubit IDs, Values: string to print out as label for that particular qubit wire. drawing_order (dict): position of each qubit in the output graphic. Keys: qubit IDs, Values: position of qubit on the qubit line in the graphic. **kwargs (dict): additional parameters are used to update the default plot parameters Returns: A tuple containing the matplotlib figure and axes objects Note: Additional keyword arguments can be passed to this function in order to further customize the figure output by matplotlib (default value in parentheses): - fontsize (14): Font size in pt - column_spacing (.5): Vertical spacing between two neighbouring gates (roughly in inches) - control_radius (.015): Radius of the circle for controls - labels_margin (1): Margin between labels and begin of wire (roughly in inches) - linewidth (1): Width of line - not_radius (.03): Radius of the circle for X/NOT gates - gate_offset (.05): Inner margins for gates with a text representation - mgate_width (.1): Width of the measurement gate - swap_delta (.02): Half-size of the SWAP gate - x_offset (.05): Absolute X-offset for drawing within the axes - wire_height (1): Vertical spacing between two qubit wires (roughly in inches)
draw
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_drawer_matplotlib.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_drawer_matplotlib.py
Apache-2.0
def to_draw(qubit_lines, qubit_labels=None, drawing_order=None, **kwargs): """ Translate a given circuit to a matplotlib figure. Args: qubit_lines (dict): list of gates for each qubit axis qubit_labels (dict): label to print in front of the qubit wire for each qubit ID drawing_order (dict): index of the wire for each qubit ID to be drawn. **kwargs (dict): additional parameters are used to update the default plot parameters Returns: A tuple with (figure, axes) Note: Numbering of qubit wires starts at 0 at the bottom and increases vertically. Note: Additional keyword arguments can be passed to this function in order to further customize the figure output by matplotlib (default value in parentheses): - fontsize (14): Font size in pt - column_spacing (.5): Vertical spacing between two neighbouring gates (roughly in inches) - control_radius (.015): Radius of the circle for controls - labels_margin (1): Margin between labels and begin of wire (roughly in inches) - linewidth (1): Width of line - not_radius (.03): Radius of the circle for X/NOT gates - gate_offset (.05): Inner margins for gates with a text representation - mgate_width (.1): Width of the measurement gate - swap_delta (.02): Half-size of the SWAP gate - x_offset (.05): Absolute X-offset for drawing within the axes - wire_height (1): Vertical spacing between two qubit wires (roughly in inches) """ if qubit_labels is None: qubit_labels = {qubit_id: r'$|0\rangle$' for qubit_id in qubit_lines} else: if list(qubit_labels) != list(qubit_lines): raise RuntimeError('Qubit IDs in qubit_labels do not match qubit IDs in qubit_lines!') if drawing_order is None: n_qubits = len(qubit_lines) drawing_order = {qubit_id: n_qubits - qubit_id - 1 for qubit_id in list(qubit_lines)} else: if set(drawing_order) != set(qubit_lines): raise RuntimeError("Qubit IDs in drawing_order do not match qubit IDs in qubit_lines!") if set(drawing_order.values()) != set(range(len(drawing_order))): raise RuntimeError(f'Indices of qubit wires in drawing_order must be between 0 and {len(drawing_order)}!') plot_params = deepcopy(_DEFAULT_PLOT_PARAMS) plot_params.update(kwargs) n_labels = len(list(qubit_lines)) wire_height = plot_params['wire_height'] # Grid in inches wire_grid = np.arange(wire_height, (n_labels + 1) * wire_height, wire_height, dtype=float) fig, axes = create_figure(plot_params) # Grid in inches gate_grid = calculate_gate_grid(axes, qubit_lines, plot_params) width = gate_grid[-1] + plot_params['column_spacing'] height = wire_grid[-1] + wire_height resize_figure(fig, axes, width, height, plot_params) # Convert grids into data coordinates units_per_inch = plot_params['units_per_inch'] gate_grid *= units_per_inch gate_grid = gate_grid + plot_params['x_offset'] wire_grid *= units_per_inch plot_params['column_spacing'] *= units_per_inch draw_wires(axes, n_labels, gate_grid, wire_grid, plot_params) draw_labels(axes, qubit_labels, drawing_order, wire_grid, plot_params) draw_gates(axes, qubit_lines, drawing_order, gate_grid, wire_grid, plot_params) return fig, axes
Translate a given circuit to a matplotlib figure. Args: qubit_lines (dict): list of gates for each qubit axis qubit_labels (dict): label to print in front of the qubit wire for each qubit ID drawing_order (dict): index of the wire for each qubit ID to be drawn. **kwargs (dict): additional parameters are used to update the default plot parameters Returns: A tuple with (figure, axes) Note: Numbering of qubit wires starts at 0 at the bottom and increases vertically. Note: Additional keyword arguments can be passed to this function in order to further customize the figure output by matplotlib (default value in parentheses): - fontsize (14): Font size in pt - column_spacing (.5): Vertical spacing between two neighbouring gates (roughly in inches) - control_radius (.015): Radius of the circle for controls - labels_margin (1): Margin between labels and begin of wire (roughly in inches) - linewidth (1): Width of line - not_radius (.03): Radius of the circle for X/NOT gates - gate_offset (.05): Inner margins for gates with a text representation - mgate_width (.1): Width of the measurement gate - swap_delta (.02): Half-size of the SWAP gate - x_offset (.05): Absolute X-offset for drawing within the axes - wire_height (1): Vertical spacing between two qubit wires (roughly in inches)
to_draw
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def gate_width(axes, gate_str, plot_params): """ Calculate the width of a gate based on its string representation. Args: axes (matplotlib.axes.Axes): axes object gate_str (str): string representation of a gate plot_params (dict): plot parameters Returns: The width of a gate on the figure (in inches) """ if gate_str == 'X': return 2 * plot_params['not_radius'] / plot_params['units_per_inch'] if gate_str == 'Swap': return 2 * plot_params['swap_delta'] / plot_params['units_per_inch'] if gate_str == 'Measure': return plot_params['mgate_width'] obj = axes.text( 0, 0, gate_str, visible=True, bbox={'edgecolor': 'k', 'facecolor': 'w', 'fill': True, 'lw': 1.0}, fontsize=14, ) obj.figure.canvas.draw() width = obj.get_window_extent(obj.figure.canvas.get_renderer()).width / axes.figure.dpi obj.remove() return width + 2 * plot_params['gate_offset']
Calculate the width of a gate based on its string representation. Args: axes (matplotlib.axes.Axes): axes object gate_str (str): string representation of a gate plot_params (dict): plot parameters Returns: The width of a gate on the figure (in inches)
gate_width
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def calculate_gate_grid(axes, qubit_lines, plot_params): """ Calculate an optimal grid spacing for a list of quantum gates. Args: axes (matplotlib.axes.Axes): axes object qubit_lines (dict): list of gates for each qubit axis plot_params (dict): plot parameters Returns: An array (np.ndarray) with the gate x positions. """ # NB: column_spacing is still in inch when this function is called column_spacing = plot_params['column_spacing'] data = list(qubit_lines.values()) depth = len(data[0]) width_list = [ max(gate_width(axes, line[idx][0], plot_params) if line[idx] else 0 for line in data) for idx in range(depth) ] gate_grid = np.array([0] * (depth + 1), dtype=float) gate_grid[0] = plot_params['labels_margin'] if depth > 0: gate_grid[0] += width_list[0] * 0.5 for idx in range(1, depth): gate_grid[idx] = gate_grid[idx - 1] + column_spacing + (width_list[idx] + width_list[idx - 1]) * 0.5 gate_grid[-1] = gate_grid[-2] + column_spacing + width_list[-1] * 0.5 return gate_grid
Calculate an optimal grid spacing for a list of quantum gates. Args: axes (matplotlib.axes.Axes): axes object qubit_lines (dict): list of gates for each qubit axis plot_params (dict): plot parameters Returns: An array (np.ndarray) with the gate x positions.
calculate_gate_grid
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def text(axes, gate_pos, wire_pos, textstr, plot_params): """ Draw a text box on the figure. Args: axes (matplotlib.axes.Axes): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire textstr (str): text of the gate and box plot_params (dict): plot parameters box (bool): draw the rectangle box if box is True """ return axes.text( gate_pos, wire_pos, textstr, color='k', ha='center', va='center', clip_on=True, size=plot_params['fontsize'], )
Draw a text box on the figure. Args: axes (matplotlib.axes.Axes): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire textstr (str): text of the gate and box plot_params (dict): plot parameters box (bool): draw the rectangle box if box is True
text
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def create_figure(plot_params): """ Create a new figure as well as a new axes instance. Args: plot_params (dict): plot parameters Returns: A tuple with (figure, axes) """ fig = plt.figure(facecolor='w', edgecolor='w') axes = plt.axes() axes.set_axis_off() axes.set_aspect('equal') plot_params['units_per_inch'] = fig.dpi / axes.get_window_extent().width return fig, axes
Create a new figure as well as a new axes instance. Args: plot_params (dict): plot parameters Returns: A tuple with (figure, axes)
create_figure
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_gates( # pylint: disable=too-many-arguments axes, qubit_lines, drawing_order, gate_grid, wire_grid, plot_params ): """ Draw the gates. Args: qubit_lines (dict): list of gates for each qubit axis drawing_order (dict): index of the wire for each qubit ID to be drawn gate_grid (np.ndarray): x positions of the gates wire_grid (np.ndarray): y positions of the qubit wires plot_params (dict): plot parameters Returns: A tuple with (figure, axes) """ for qubit_line in qubit_lines.values(): for idx, data in enumerate(qubit_line): if data is not None: (gate_str, targets, controls) = data targets_order = [drawing_order[tgt] for tgt in targets] draw_gate( axes, gate_str, gate_grid[idx], [wire_grid[tgt] for tgt in targets_order], targets_order, [wire_grid[drawing_order[ctrl]] for ctrl in controls], plot_params, )
Draw the gates. Args: qubit_lines (dict): list of gates for each qubit axis drawing_order (dict): index of the wire for each qubit ID to be drawn gate_grid (np.ndarray): x positions of the gates wire_grid (np.ndarray): y positions of the qubit wires plot_params (dict): plot parameters Returns: A tuple with (figure, axes)
draw_gates
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_gate( axes, gate_str, gate_pos, target_wires, targets_order, control_wires, plot_params ): # pylint: disable=too-many-arguments """ Draw a single gate at a given location. Args: axes (AxesSubplot): axes object gate_str (str): string representation of a gate gate_pos (float): x coordinate of the gate [data units] target_wires (list): y coordinates of the target qubits targets_order (list): index of the wires corresponding to the target qubit IDs control_wires (list): y coordinates of the control qubits plot_params (dict): plot parameters Returns: A tuple with (figure, axes) """ # Special cases if gate_str == 'Z' and len(control_wires) == 1: draw_control_z_gate(axes, gate_pos, target_wires[0], control_wires[0], plot_params) elif gate_str == 'X': draw_x_gate(axes, gate_pos, target_wires[0], plot_params) elif gate_str == 'Swap': draw_swap_gate(axes, gate_pos, target_wires[0], target_wires[1], plot_params) elif gate_str == 'Measure': draw_measure_gate(axes, gate_pos, target_wires[0], plot_params) else: if len(target_wires) == 1: draw_generic_gate(axes, gate_pos, target_wires[0], gate_str, plot_params) else: if sorted(targets_order) != list(range(min(targets_order), max(targets_order) + 1)): raise RuntimeError( f"Multi-qubit gate with non-neighbouring qubits!\nGate: {gate_str} on wires {targets_order}" ) multi_qubit_gate( axes, gate_str, gate_pos, min(target_wires), max(target_wires), plot_params, ) if not control_wires: return for control_wire in control_wires: axes.add_patch( Circle( (gate_pos, control_wire), plot_params['control_radius'], ec='k', fc='k', fill=True, lw=plot_params['linewidth'], ) ) all_wires = target_wires + control_wires axes.add_line( Line2D( (gate_pos, gate_pos), (min(all_wires), max(all_wires)), color='k', lw=plot_params['linewidth'], ) )
Draw a single gate at a given location. Args: axes (AxesSubplot): axes object gate_str (str): string representation of a gate gate_pos (float): x coordinate of the gate [data units] target_wires (list): y coordinates of the target qubits targets_order (list): index of the wires corresponding to the target qubit IDs control_wires (list): y coordinates of the control qubits plot_params (dict): plot parameters Returns: A tuple with (figure, axes)
draw_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_generic_gate(axes, gate_pos, wire_pos, gate_str, plot_params): """ Draw a measurement gate. Args: axes (AxesSubplot): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire gate_str (str) : string representation of a gate plot_params (dict): plot parameters """ obj = text(axes, gate_pos, wire_pos, gate_str, plot_params) obj.set_zorder(7) factor = plot_params['units_per_inch'] / obj.figure.dpi gate_offset = plot_params['gate_offset'] renderer = obj.figure.canvas.get_renderer() width = obj.get_window_extent(renderer).width * factor + 2 * gate_offset height = obj.get_window_extent(renderer).height * factor + 2 * gate_offset axes.add_patch( Rectangle( (gate_pos - width / 2, wire_pos - height / 2), width, height, ec='k', fc='w', fill=True, lw=plot_params['linewidth'], zorder=6, ) )
Draw a measurement gate. Args: axes (AxesSubplot): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire gate_str (str) : string representation of a gate plot_params (dict): plot parameters
draw_generic_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_measure_gate(axes, gate_pos, wire_pos, plot_params): """ Draw a measurement gate. Args: axes (AxesSubplot): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire plot_params (dict): plot parameters """ # pylint: disable=invalid-name width = plot_params['mgate_width'] height = 0.9 * width y_ref = wire_pos - 0.3 * height # Cannot use PatchCollection for the arc due to bug in matplotlib code... arc = Arc( (gate_pos, y_ref), width * 0.7, height * 0.8, theta1=0, theta2=180, ec='k', fc='w', zorder=5, ) axes.add_patch(arc) patches = [ Rectangle((gate_pos - width / 2, wire_pos - height / 2), width, height, fill=True), Line2D( (gate_pos, gate_pos + width * 0.35), (y_ref, wire_pos + height * 0.35), color='k', linewidth=1, ), ] gate = PatchCollection( patches, edgecolors='k', facecolors='w', linewidths=plot_params['linewidth'], zorder=5, ) gate.set_label('Measure') axes.add_collection(gate)
Draw a measurement gate. Args: axes (AxesSubplot): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire plot_params (dict): plot parameters
draw_measure_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def multi_qubit_gate( # pylint: disable=too-many-arguments axes, gate_str, gate_pos, wire_pos_min, wire_pos_max, plot_params ): """ Draw a multi-target qubit gate. Args: axes (matplotlib.axes.Axes): axes object gate_str (str): string representation of a gate gate_pos (float): x coordinate of the gate [data units] wire_pos_min (float): y coordinate of the lowest qubit wire wire_pos_max (float): y coordinate of the highest qubit wire plot_params (dict): plot parameters """ gate_offset = plot_params['gate_offset'] y_center = (wire_pos_max - wire_pos_min) / 2 + wire_pos_min obj = axes.text( gate_pos, y_center, gate_str, color='k', ha='center', va='center', size=plot_params['fontsize'], zorder=7, ) height = wire_pos_max - wire_pos_min + 2 * gate_offset inv = axes.transData.inverted() width = inv.transform_bbox(obj.get_window_extent(obj.figure.canvas.get_renderer())).width return axes.add_patch( Rectangle( (gate_pos - width / 2, wire_pos_min - gate_offset), width, height, edgecolor='k', facecolor='w', fill=True, lw=plot_params['linewidth'], zorder=6, ) )
Draw a multi-target qubit gate. Args: axes (matplotlib.axes.Axes): axes object gate_str (str): string representation of a gate gate_pos (float): x coordinate of the gate [data units] wire_pos_min (float): y coordinate of the lowest qubit wire wire_pos_max (float): y coordinate of the highest qubit wire plot_params (dict): plot parameters
multi_qubit_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_x_gate(axes, gate_pos, wire_pos, plot_params): """ Draw the symbol for a X/NOT gate. Args: axes (matplotlib.axes.Axes): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire [data units] plot_params (dict): plot parameters """ not_radius = plot_params['not_radius'] gate = PatchCollection( [ Circle((gate_pos, wire_pos), not_radius, fill=False), Line2D((gate_pos, gate_pos), (wire_pos - not_radius, wire_pos + not_radius)), ], edgecolors='k', facecolors='w', linewidths=plot_params['linewidth'], ) gate.set_label('NOT') axes.add_collection(gate)
Draw the symbol for a X/NOT gate. Args: axes (matplotlib.axes.Axes): axes object gate_pos (float): x coordinate of the gate [data units] wire_pos (float): y coordinate of the qubit wire [data units] plot_params (dict): plot parameters
draw_x_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_control_z_gate(axes, gate_pos, wire_pos1, wire_pos2, plot_params): """ Draw the symbol for a controlled-Z gate. Args: axes (matplotlib.axes.Axes): axes object wire_pos (float): x coordinate of the gate [data units] y1 (float): y coordinate of the 1st qubit wire y2 (float): y coordinate of the 2nd qubit wire plot_params (dict): plot parameters """ gate = PatchCollection( [ Circle((gate_pos, wire_pos1), plot_params['control_radius'], fill=True), Circle((gate_pos, wire_pos2), plot_params['control_radius'], fill=True), Line2D((gate_pos, gate_pos), (wire_pos1, wire_pos2)), ], edgecolors='k', facecolors='k', linewidths=plot_params['linewidth'], ) gate.set_label('CZ') axes.add_collection(gate)
Draw the symbol for a controlled-Z gate. Args: axes (matplotlib.axes.Axes): axes object wire_pos (float): x coordinate of the gate [data units] y1 (float): y coordinate of the 1st qubit wire y2 (float): y coordinate of the 2nd qubit wire plot_params (dict): plot parameters
draw_control_z_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_swap_gate(axes, gate_pos, wire_pos1, wire_pos2, plot_params): """ Draw the symbol for a SWAP gate. Args: axes (matplotlib.axes.Axes): axes object x (float): x coordinate [data units] y1 (float): y coordinate of the 1st qubit wire y2 (float): y coordinate of the 2nd qubit wire plot_params (dict): plot parameters """ delta = plot_params['swap_delta'] lines = [] for wire_pos in (wire_pos1, wire_pos2): lines.append([(gate_pos - delta, wire_pos - delta), (gate_pos + delta, wire_pos + delta)]) lines.append([(gate_pos - delta, wire_pos + delta), (gate_pos + delta, wire_pos - delta)]) lines.append([(gate_pos, wire_pos1), (gate_pos, wire_pos2)]) gate = LineCollection(lines, colors='k', linewidths=plot_params['linewidth']) gate.set_label('SWAP') axes.add_collection(gate)
Draw the symbol for a SWAP gate. Args: axes (matplotlib.axes.Axes): axes object x (float): x coordinate [data units] y1 (float): y coordinate of the 1st qubit wire y2 (float): y coordinate of the 2nd qubit wire plot_params (dict): plot parameters
draw_swap_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_wires(axes, n_labels, gate_grid, wire_grid, plot_params): """ Draw all the circuit qubit wires. Args: axes (matplotlib.axes.Axes): axes object n_labels (int): number of qubit gate_grid (ndarray): array with the ref. x positions of the gates wire_grid (ndarray): array with the ref. y positions of the qubit wires plot_params (dict): plot parameters """ # pylint: disable=invalid-name lines = [] for i in range(n_labels): lines.append( ( (gate_grid[0] - plot_params['column_spacing'], wire_grid[i]), (gate_grid[-1], wire_grid[i]), ) ) all_lines = LineCollection(lines, linewidths=plot_params['linewidth'], edgecolor='k') all_lines.set_label('qubit_wires') axes.add_collection(all_lines)
Draw all the circuit qubit wires. Args: axes (matplotlib.axes.Axes): axes object n_labels (int): number of qubit gate_grid (ndarray): array with the ref. x positions of the gates wire_grid (ndarray): array with the ref. y positions of the qubit wires plot_params (dict): plot parameters
draw_wires
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def draw_labels(axes, qubit_labels, drawing_order, wire_grid, plot_params): """ Draw the labels at the start of each qubit wire. Args: axes (matplotlib.axes.Axes): axes object qubit_labels (list): labels of the qubit to be drawn drawing_order (dict): Mapping between wire indices and qubit IDs gate_grid (ndarray): array with the ref. x positions of the gates wire_grid (ndarray): array with the ref. y positions of the qubit wires plot_params (dict): plot parameters """ for qubit_id in qubit_labels: wire_idx = drawing_order[qubit_id] text( axes, plot_params['x_offset'], wire_grid[wire_idx], qubit_labels[qubit_id], plot_params, )
Draw the labels at the start of each qubit wire. Args: axes (matplotlib.axes.Axes): axes object qubit_labels (list): labels of the qubit to be drawn drawing_order (dict): Mapping between wire indices and qubit IDs gate_grid (ndarray): array with the ref. x positions of the gates wire_grid (ndarray): array with the ref. y positions of the qubit wires plot_params (dict): plot parameters
draw_labels
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_plot.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_plot.py
Apache-2.0
def _gate_name(gate): """ Return the string representation of the gate. Tries to use gate.tex_str and, if that is not available, uses str(gate) instead. Args: gate: Gate object of which to get the name / latex representation. Returns: gate_name (string): Latex gate name. """ try: name = gate.tex_str() except AttributeError: name = str(gate) return name
Return the string representation of the gate. Tries to use gate.tex_str and, if that is not available, uses str(gate) instead. Args: gate: Gate object of which to get the name / latex representation. Returns: gate_name (string): Latex gate name.
_gate_name
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def to_latex(circuit, drawing_order=None, draw_gates_in_parallel=True): """ Translate a given circuit to a TikZ picture in a Latex document. It uses a json-configuration file which (if it does not exist) is created automatically upon running this function for the first time. The config file can be used to determine custom gate sizes, offsets, etc. New gate options can be added under settings['gates'], using the gate class name string as a key. Every gate can have its own width, height, pre offset and offset. Example: .. code-block:: python settings['gates']['HGate'] = {'width': 0.5, 'offset': 0.15} The default settings can be acquired using the get_default_settings() function, and written using write_settings(). Args: circuit (list): Each qubit line is a list of CircuitItem objects, i.e., in circuit[line]. drawing_order (list): A list of qubit lines from which the gates to be read from draw_gates_in_parallel (bool): If gates should (False) or not (True) be parallel in the circuit Returns: tex_doc_str (string): Latex document string which can be compiled using, e.g., pdflatex. """ try: with open('settings.json') as settings_file: settings = json.load(settings_file) except FileNotFoundError: settings = write_settings(get_default_settings()) text = _header(settings) text += _body(circuit, settings, drawing_order, draw_gates_in_parallel=draw_gates_in_parallel) text += _footer() return text
Translate a given circuit to a TikZ picture in a Latex document. It uses a json-configuration file which (if it does not exist) is created automatically upon running this function for the first time. The config file can be used to determine custom gate sizes, offsets, etc. New gate options can be added under settings['gates'], using the gate class name string as a key. Every gate can have its own width, height, pre offset and offset. Example: .. code-block:: python settings['gates']['HGate'] = {'width': 0.5, 'offset': 0.15} The default settings can be acquired using the get_default_settings() function, and written using write_settings(). Args: circuit (list): Each qubit line is a list of CircuitItem objects, i.e., in circuit[line]. drawing_order (list): A list of qubit lines from which the gates to be read from draw_gates_in_parallel (bool): If gates should (False) or not (True) be parallel in the circuit Returns: tex_doc_str (string): Latex document string which can be compiled using, e.g., pdflatex.
to_latex
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def write_settings(settings): """ Write all settings to a json-file. Args: settings (dict): Settings dict to write. """ with open('settings.json', 'w') as settings_file: json.dump(settings, settings_file, sort_keys=True, indent=4) return settings
Write all settings to a json-file. Args: settings (dict): Settings dict to write.
write_settings
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def get_default_settings(): """ Return the default settings for the circuit drawing function to_latex(). Returns: settings (dict): Default circuit settings """ settings = {} settings['gate_shadow'] = True settings['lines'] = { 'style': 'very thin', 'double_classical': True, 'init_quantum': True, 'double_lines_sep': 0.04, } settings['gates'] = { 'HGate': {'width': 0.5, 'offset': 0.3, 'pre_offset': 0.1}, 'XGate': {'width': 0.35, 'height': 0.35, 'offset': 0.1}, 'SqrtXGate': {'width': 0.7, 'offset': 0.3, 'pre_offset': 0.1}, 'SwapGate': {'width': 0.35, 'height': 0.35, 'offset': 0.1}, 'SqrtSwapGate': {'width': 0.35, 'height': 0.35, 'offset': 0.1}, 'Rx': {'width': 1.0, 'height': 0.8, 'pre_offset': 0.2, 'offset': 0.3}, 'Ry': {'width': 1.0, 'height': 0.8, 'pre_offset': 0.2, 'offset': 0.3}, 'Rz': {'width': 1.0, 'height': 0.8, 'pre_offset': 0.2, 'offset': 0.3}, 'Ph': {'width': 1.0, 'height': 0.8, 'pre_offset': 0.2, 'offset': 0.3}, 'EntangleGate': {'width': 1.8, 'offset': 0.2, 'pre_offset': 0.2}, 'DeallocateQubitGate': { 'height': 0.15, 'offset': 0.2, 'width': 0.2, 'pre_offset': 0.1, }, 'AllocateQubitGate': { 'height': 0.15, 'width': 0.2, 'offset': 0.1, 'pre_offset': 0.1, 'draw_id': False, 'allocate_at_zero': False, }, 'MeasureGate': {'width': 0.75, 'offset': 0.2, 'height': 0.5, 'pre_offset': 0.2}, } settings['control'] = {'size': 0.1, 'shadow': False} return settings
Return the default settings for the circuit drawing function to_latex(). Returns: settings (dict): Default circuit settings
get_default_settings
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _header(settings): """ Write the Latex header using the settings file. The header includes all packages and defines all tikz styles. Returns: header (string): Header of the Latex document. """ packages = ( "\\documentclass{standalone}\n\\usepackage[margin=1in]" "{geometry}\n\\usepackage[hang,small,bf]{caption}\n" "\\usepackage{tikz}\n" "\\usepackage{braket}\n\\usetikzlibrary{backgrounds,shadows." "blur,fit,decorations.pathreplacing,shapes}\n\n" ) init = "\\begin{document}\n\\begin{tikzpicture}[scale=0.8, transform shape]\n\n" gate_style = ( "\\tikzstyle{basicshadow}=[blur shadow={shadow blur steps=8," " shadow xshift=0.7pt, shadow yshift=-0.7pt, shadow scale=" "1.02}]" ) if not (settings['gate_shadow'] or settings['control']['shadow']): gate_style = "" gate_style += "\\tikzstyle{basic}=[draw,fill=white," if settings['gate_shadow']: gate_style += "basicshadow" gate_style += "]\n" gate_style += ( "\\tikzstyle{{operator}}=[basic,minimum size=1.5em]\n" f"\\tikzstyle{{phase}}=[fill=black,shape=circle,minimum size={settings['control']['size']}cm," "inner sep=0pt,outer sep=0pt,draw=black" ) if settings['control']['shadow']: gate_style += ",basicshadow" gate_style += ( "]\n\\tikzstyle{{none}}=[inner sep=0pt,outer sep=-.5pt,minimum height=0.5cm+1pt]\n" "\\tikzstyle{{measure}}=[operator,inner sep=0pt," f"minimum height={settings['gates']['MeasureGate']['height']}cm," f"minimum width={settings['gates']['MeasureGate']['width']}cm]\n" "\\tikzstyle{{xstyle}}=[circle,basic,minimum height=" ) x_gate_radius = min(settings['gates']['XGate']['height'], settings['gates']['XGate']['width']) gate_style += f"{x_gate_radius}cm,minimum width={x_gate_radius}cm,inner sep=-1pt,{settings['lines']['style']}]\n" if settings['gate_shadow']: gate_style += ( "\\tikzset{\nshadowed/.style={preaction={transform " "canvas={shift={(0.5pt,-0.5pt)}}, draw=gray, opacity=" "0.4}},\n}\n" ) gate_style += "\\tikzstyle{swapstyle}=[" gate_style += "inner sep=-1pt, outer sep=-1pt, minimum width=0pt]\n" edge_style = f"\\tikzstyle{{edgestyle}}=[{settings['lines']['style']}]\n" return packages + init + gate_style + edge_style
Write the Latex header using the settings file. The header includes all packages and defines all tikz styles. Returns: header (string): Header of the Latex document.
_header
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _body(circuit, settings, drawing_order=None, draw_gates_in_parallel=True): """ Return the body of the Latex document, including the entire circuit in TikZ format. Args: circuit (list<list<CircuitItem>>): Circuit to draw. settings: Dictionary of settings to use for the TikZ image. drawing_order: A list of circuit wires from where to read one gate command. draw_gates_in_parallel: Are the gate/commands occupying a single time step in the circuit diagram? For example, False means that gates can be parallel in the circuit. Returns: tex_str (string): Latex string to draw the entire circuit. """ code = [] conv = _Circ2Tikz(settings, len(circuit)) to_where = None if drawing_order is None: drawing_order = list(range(len(circuit))) else: to_where = 1 for line in drawing_order: code.append( conv.to_tikz( line, circuit, end=to_where, draw_gates_in_parallel=draw_gates_in_parallel, ) ) return "".join(code)
Return the body of the Latex document, including the entire circuit in TikZ format. Args: circuit (list<list<CircuitItem>>): Circuit to draw. settings: Dictionary of settings to use for the TikZ image. drawing_order: A list of circuit wires from where to read one gate command. draw_gates_in_parallel: Are the gate/commands occupying a single time step in the circuit diagram? For example, False means that gates can be parallel in the circuit. Returns: tex_str (string): Latex string to draw the entire circuit.
_body
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def __init__(self, settings, num_lines): """ Initialize a circuit to latex converter object. Args: settings (dict): Dictionary of settings to use for the TikZ image. num_lines (int): Number of qubit lines to use for the entire circuit. """ self.settings = settings self.pos = [0.0] * num_lines self.op_count = [0] * num_lines self.is_quantum = [settings['lines']['init_quantum']] * num_lines
Initialize a circuit to latex converter object. Args: settings (dict): Dictionary of settings to use for the TikZ image. num_lines (int): Number of qubit lines to use for the entire circuit.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def to_tikz( # pylint: disable=too-many-branches,too-many-locals,too-many-statements self, line, circuit, end=None, draw_gates_in_parallel=True ): """ Generate the TikZ code for one line of the circuit up to a certain gate. It modifies the circuit to include only the gates which have not been drawn. It automatically switches to other lines if the gates on those lines have to be drawn earlier. Args: line (int): Line to generate the TikZ code for. circuit (list<list<CircuitItem>>): The circuit to draw. end (int): Gate index to stop at (for recursion). draw_gates_in_parallel (bool): True or False for how to place gates Returns: tikz_code (string): TikZ code representing the current qubit line and, if it was necessary to draw other lines, those lines as well. """ if end is None: end = len(circuit[line]) tikz_code = [] cmds = circuit[line] for i in range(0, end): gate = cmds[i].gate lines = cmds[i].lines ctrl_lines = cmds[i].ctrl_lines all_lines = lines + ctrl_lines all_lines.remove(line) # remove current line for _line in all_lines: gate_idx = 0 while not circuit[_line][gate_idx] == cmds[i]: gate_idx += 1 tikz_code.append(self.to_tikz(_line, circuit, gate_idx)) # we are taking care of gate 0 (the current one) circuit[_line] = circuit[_line][1:] all_lines = lines + ctrl_lines pos = max(self.pos[ll] for ll in range(min(all_lines), max(all_lines) + 1)) for _line in range(min(all_lines), max(all_lines) + 1): self.pos[_line] = pos + self._gate_pre_offset(gate) connections = "" for _line in all_lines: connections += self._line(self.op_count[_line] - 1, self.op_count[_line], line=_line) add_str = "" if gate == X: # draw NOT-gate with controls add_str = self._x_gate(lines, ctrl_lines) # and make the target qubit quantum if one of the controls is if not self.is_quantum[lines[0]]: if sum(self.is_quantum[i] for i in ctrl_lines) > 0: self.is_quantum[lines[0]] = True elif gate == Z and len(ctrl_lines) > 0: add_str = self._cz_gate(lines + ctrl_lines) elif gate == Swap: add_str = self._swap_gate(lines, ctrl_lines) elif gate == SqrtSwap: add_str = self._sqrtswap_gate(lines, ctrl_lines, daggered=False) elif gate == get_inverse(SqrtSwap): add_str = self._sqrtswap_gate(lines, ctrl_lines, daggered=True) elif gate == Measure: # draw measurement gate for _line in lines: op = self._op(_line) width = self._gate_width(Measure) height = self._gate_height(Measure) shift0 = 0.07 * height shift1 = 0.36 * height shift2 = 0.1 * width add_str += ( f"\n\\node[measure,edgestyle] ({op}) at ({self.pos[_line]}" f",-{_line}) {{}};\n\\draw[edgestyle] ([yshift=" f"-{shift1}cm,xshift={shift2}cm]{op}.west) to " f"[out=60,in=180] ([yshift={shift0}cm]{op}." f"center) to [out=0, in=120] ([yshift=-{shift1}" f"cm,xshift=-{shift2}cm]{op}.east);\n" f"\\draw[edgestyle] ([yshift=-{shift1}cm]{op}." f"center) to ([yshift=-{shift2}cm,xshift=-" f"{shift1}cm]{op}.north east);" ) self.op_count[_line] += 1 self.pos[_line] += self._gate_width(gate) + self._gate_offset(gate) self.is_quantum[_line] = False elif gate == Allocate: # draw 'begin line' id_str = "" if self.settings['gates']['AllocateQubitGate']['draw_id']: id_str = f"^{{\\textcolor{{red}}{{{cmds[i].id}}}}}" xpos = self.pos[line] try: if self.settings['gates']['AllocateQubitGate']['allocate_at_zero']: self.pos[line] -= self._gate_pre_offset(gate) xpos = self._gate_pre_offset(gate) except KeyError: pass self.pos[line] = max( xpos + self._gate_offset(gate) + self._gate_width(gate), self.pos[line], ) add_str = f"\n\\node[none] ({self._op(line)}) at ({xpos},-{line}) {{$\\Ket{{0}}{id_str}$}};" self.op_count[line] += 1 self.is_quantum[line] = self.settings['lines']['init_quantum'] elif gate == Deallocate: # draw 'end of line' op = self._op(line) add_str = f"\n\\node[none] ({op}) at ({self.pos[line]},-{line}) {{}};" yshift = f"{str(self._gate_height(gate))}cm]" add_str += f"\n\\draw ([yshift={yshift}{op}.center) edge [edgestyle] ([yshift=-{yshift}{op}.center);" self.op_count[line] += 1 self.pos[line] += self._gate_width(gate) + self._gate_offset(gate) else: # regular gate must draw the lines it does not act upon # if it spans multiple qubits add_str = self._regular_gate(gate, lines, ctrl_lines) for _line in lines: self.is_quantum[_line] = True tikz_code.append(add_str) if not gate == Allocate: tikz_code.append(connections) if not draw_gates_in_parallel: for _line, _ in enumerate(self.pos): if _line != line: self.pos[_line] = self.pos[line] circuit[line] = circuit[line][end:] return "".join(tikz_code)
Generate the TikZ code for one line of the circuit up to a certain gate. It modifies the circuit to include only the gates which have not been drawn. It automatically switches to other lines if the gates on those lines have to be drawn earlier. Args: line (int): Line to generate the TikZ code for. circuit (list<list<CircuitItem>>): The circuit to draw. end (int): Gate index to stop at (for recursion). draw_gates_in_parallel (bool): True or False for how to place gates Returns: tikz_code (string): TikZ code representing the current qubit line and, if it was necessary to draw other lines, those lines as well.
to_tikz
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _sqrtswap_gate(self, lines, ctrl_lines, daggered): # pylint: disable=too-many-locals """ Return the TikZ code for a Square-root Swap-gate. Args: lines (list<int>): List of length 2 denoting the target qubit of the Swap gate. ctrl_lines (list<int>): List of qubit lines which act as controls. daggered (bool): Show the daggered one if True. """ if len(lines) != 2: raise RuntimeError('Sqrt SWAP gate acts on 2 qubits') delta_pos = self._gate_offset(SqrtSwap) gate_width = self._gate_width(SqrtSwap) lines.sort() gate_str = "" for line in lines: op = self._op(line) width = f"{0.5 * gate_width}cm" blc = f"[xshift=-{width},yshift=-{width}]{op}.center" trc = f"[xshift={width},yshift={width}]{op}.center" tlc = f"[xshift=-{width},yshift={width}]{op}.center" brc = f"[xshift={width},yshift=-{width}]{op}.center" swap_style = "swapstyle,edgestyle" if self.settings['gate_shadow']: swap_style += ",shadowed" gate_str += ( f"\n\\node[swapstyle] ({op}) at ({self.pos[line]},-{line}) {{}};" f"\n\\draw[{swap_style}] ({blc})--({trc});\n" f"\\draw[{swap_style}] ({tlc})--({brc});" ) # add a circled 1/2 midpoint = (lines[0] + lines[1]) / 2.0 pos = self.pos[lines[0]] # pylint: disable=consider-using-f-string op_mid = f"line{'{}-{}'.format(*lines)}_gate{self.op_count[lines[0]]}" dagger = '^{{\\dagger}}' if daggered else '' gate_str += f"\n\\node[xstyle] ({op}) at ({pos},-{midpoint}){{\\scriptsize $\\frac{{1}}{{2}}{dagger}$}};" # add two vertical lines to connect circled 1/2 gate_str += f"\n\\draw ({self._op(lines[0])}) edge[edgestyle] ({op_mid});" gate_str += f"\n\\draw ({op_mid}) edge[edgestyle] ({self._op(lines[1])});" if len(ctrl_lines) > 0: for ctrl in ctrl_lines: gate_str += self._phase(ctrl, self.pos[lines[0]]) if ctrl > lines[1] or ctrl < lines[0]: closer_line = lines[0] if ctrl > lines[1]: closer_line = lines[1] gate_str += self._line(ctrl, closer_line) all_lines = ctrl_lines + lines new_pos = self.pos[lines[0]] + delta_pos + gate_width for i in all_lines: self.op_count[i] += 1 for i in range(min(all_lines), max(all_lines) + 1): self.pos[i] = new_pos return gate_str
Return the TikZ code for a Square-root Swap-gate. Args: lines (list<int>): List of length 2 denoting the target qubit of the Swap gate. ctrl_lines (list<int>): List of qubit lines which act as controls. daggered (bool): Show the daggered one if True.
_sqrtswap_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _swap_gate(self, lines, ctrl_lines): # pylint: disable=too-many-locals """ Return the TikZ code for a Swap-gate. Args: lines (list<int>): List of length 2 denoting the target qubit of the Swap gate. ctrl_lines (list<int>): List of qubit lines which act as controls. """ if len(lines) != 2: raise RuntimeError('SWAP gate acts on 2 qubits') delta_pos = self._gate_offset(Swap) gate_width = self._gate_width(Swap) lines.sort() gate_str = "" for line in lines: op = self._op(line) width = f"{0.5 * gate_width}cm" blc = f"[xshift=-{width},yshift=-{width}]{op}.center" trc = f"[xshift={width},yshift={width}]{op}.center" tlc = f"[xshift=-{width},yshift={width}]{op}.center" brc = f"[xshift={width},yshift=-{width}]{op}.center" swap_style = "swapstyle,edgestyle" if self.settings['gate_shadow']: swap_style += ",shadowed" gate_str += ( f"\n\\node[swapstyle] ({op}) at ({self.pos[line]},-{line}) {{}};" f"\n\\draw[{swap_style}] ({blc})--({trc});\n" f"\\draw[{swap_style}] ({tlc})--({brc});" ) gate_str += self._line(lines[0], lines[1]) if len(ctrl_lines) > 0: for ctrl in ctrl_lines: gate_str += self._phase(ctrl, self.pos[lines[0]]) if ctrl > lines[1] or ctrl < lines[0]: closer_line = lines[0] if ctrl > lines[1]: closer_line = lines[1] gate_str += self._line(ctrl, closer_line) all_lines = ctrl_lines + lines new_pos = self.pos[lines[0]] + delta_pos + gate_width for i in all_lines: self.op_count[i] += 1 for i in range(min(all_lines), max(all_lines) + 1): self.pos[i] = new_pos return gate_str
Return the TikZ code for a Swap-gate. Args: lines (list<int>): List of length 2 denoting the target qubit of the Swap gate. ctrl_lines (list<int>): List of qubit lines which act as controls.
_swap_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _x_gate(self, lines, ctrl_lines): """ Return the TikZ code for a NOT-gate. Args: lines (list<int>): List of length 1 denoting the target qubit of the NOT / X gate. ctrl_lines (list<int>): List of qubit lines which act as controls. """ if len(lines) != 1: raise RuntimeError('X gate acts on 1 qubits') line = lines[0] delta_pos = self._gate_offset(X) gate_width = self._gate_width(X) op = self._op(line) gate_str = ( f"\n\\node[xstyle] ({op}) at ({self.pos[line]},-{line}) {{}};\n\\draw" f"[edgestyle] ({op}.north)--({op}.south);\n\\draw" f"[edgestyle] ({op}.west)--({op}.east);" ) if len(ctrl_lines) > 0: for ctrl in ctrl_lines: gate_str += self._phase(ctrl, self.pos[line]) gate_str += self._line(ctrl, line) all_lines = ctrl_lines + [line] new_pos = self.pos[line] + delta_pos + gate_width for i in all_lines: self.op_count[i] += 1 for i in range(min(all_lines), max(all_lines) + 1): self.pos[i] = new_pos return gate_str
Return the TikZ code for a NOT-gate. Args: lines (list<int>): List of length 1 denoting the target qubit of the NOT / X gate. ctrl_lines (list<int>): List of qubit lines which act as controls.
_x_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _cz_gate(self, lines): """ Return the TikZ code for an n-controlled Z-gate. Args: lines (list<int>): List of all qubits involved. """ line = lines[0] delta_pos = self._gate_offset(Z) gate_width = self._gate_width(Z) gate_str = self._phase(line, self.pos[line]) for ctrl in lines[1:]: gate_str += self._phase(ctrl, self.pos[line]) gate_str += self._line(ctrl, line) new_pos = self.pos[line] + delta_pos + gate_width for i in lines: self.op_count[i] += 1 for i in range(min(lines), max(lines) + 1): self.pos[i] = new_pos return gate_str
Return the TikZ code for an n-controlled Z-gate. Args: lines (list<int>): List of all qubits involved.
_cz_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _gate_width(self, gate): """ Return the gate width, using the settings (if available). Returns: gate_width (float): Width of the gate. (settings['gates'][gate_class_name]['width']) """ if isinstance(gate, DaggeredGate): gate = gate._gate # pylint: disable=protected-access try: gates = self.settings['gates'] gate_width = gates[gate.__class__.__name__]['width'] except KeyError: gate_width = 0.5 return gate_width
Return the gate width, using the settings (if available). Returns: gate_width (float): Width of the gate. (settings['gates'][gate_class_name]['width'])
_gate_width
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _gate_pre_offset(self, gate): """ Return the offset to use before placing this gate. Returns: gate_pre_offset (float): Offset to use before the gate. (settings['gates'][gate_class_name]['pre_offset']) """ if isinstance(gate, DaggeredGate): gate = gate._gate # pylint: disable=protected-access try: gates = self.settings['gates'] delta_pos = gates[gate.__class__.__name__]['pre_offset'] except KeyError: delta_pos = self._gate_offset(gate) return delta_pos
Return the offset to use before placing this gate. Returns: gate_pre_offset (float): Offset to use before the gate. (settings['gates'][gate_class_name]['pre_offset'])
_gate_pre_offset
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _gate_offset(self, gate): """ Return the offset to use after placing this gate. If no pre_offset is defined, the same offset is used in front of the gate. Returns: gate_offset (float): Offset. (settings['gates'][gate_class_name]['offset']) """ if isinstance(gate, DaggeredGate): gate = gate._gate # pylint: disable=protected-access try: gates = self.settings['gates'] delta_pos = gates[gate.__class__.__name__]['offset'] except KeyError: delta_pos = 0.2 return delta_pos
Return the offset to use after placing this gate. If no pre_offset is defined, the same offset is used in front of the gate. Returns: gate_offset (float): Offset. (settings['gates'][gate_class_name]['offset'])
_gate_offset
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _gate_height(self, gate): """ Return the height to use for this gate. Returns: gate_height (float): Height of the gate. (settings['gates'][gate_class_name]['height']) """ if isinstance(gate, DaggeredGate): gate = gate._gate # pylint: disable=protected-access try: height = self.settings['gates'][gate.__class__.__name__]['height'] except KeyError: height = 0.5 return height
Return the height to use for this gate. Returns: gate_height (float): Height of the gate. (settings['gates'][gate_class_name]['height'])
_gate_height
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _op(self, line, op=None, offset=0): """ Return the gate name for placing a gate on a line. Args: line (int): Line number. op (int): Operation number or, by default, uses the current op count. Returns: op_str (string): Gate name. """ if op is None: op = self.op_count[line] return f"line{line}_gate{op + offset}"
Return the gate name for placing a gate on a line. Args: line (int): Line number. op (int): Operation number or, by default, uses the current op count. Returns: op_str (string): Gate name.
_op
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _line(self, point1, point2, double=False, line=None): # pylint: disable=too-many-locals,unused-argument """ Create a line that connects two points. Connects point1 and point2, where point1 and point2 are either to qubit line indices, in which case the two most recent gates are connected, or two gate indices, in which case line denotes the line number and the two gates are connected on the given line. Args: p1 (int): Index of the first object to connect. p2 (int): Index of the second object to connect. double (bool): Draws double lines if True. line (int or None): Line index - if provided, p1 and p2 are gate indices. Returns: tex_str (string): Latex code to draw this / these line(s). """ dbl_classical = self.settings['lines']['double_classical'] if line is None: quantum = not dbl_classical or self.is_quantum[point1] op1, op2 = self._op(point1), self._op(point2) loc1, loc2 = 'north', 'south' shift = "xshift={}cm" else: quantum = not dbl_classical or self.is_quantum[line] op1, op2 = self._op(line, point1), self._op(line, point2) loc1, loc2 = 'west', 'east' shift = "yshift={}cm" if quantum: return f"\n\\draw ({op1}) edge[edgestyle] ({op2});" if point2 > point1: loc1, loc2 = loc2, loc1 edge_str = "\n\\draw ([{shift}]{op1}.{loc1}) edge[edgestyle] ([{shift}]{op2}.{loc2});" line_sep = self.settings['lines']['double_lines_sep'] shift1 = shift.format(line_sep / 2.0) shift2 = shift.format(-line_sep / 2.0) edges_str = edge_str.format(shift=shift1, op1=op1, op2=op2, loc1=loc1, loc2=loc2) edges_str += edge_str.format(shift=shift2, op1=op1, op2=op2, loc1=loc1, loc2=loc2) return edges_str
Create a line that connects two points. Connects point1 and point2, where point1 and point2 are either to qubit line indices, in which case the two most recent gates are connected, or two gate indices, in which case line denotes the line number and the two gates are connected on the given line. Args: p1 (int): Index of the first object to connect. p2 (int): Index of the second object to connect. double (bool): Draws double lines if True. line (int or None): Line index - if provided, p1 and p2 are gate indices. Returns: tex_str (string): Latex code to draw this / these line(s).
_line
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def _regular_gate(self, gate, lines, ctrl_lines): # pylint: disable=too-many-locals """ Draw a regular gate. Args: gate: Gate to draw. lines (list<int>): Lines the gate acts on. ctrl_lines (list<int>): Control lines. Returns: tex_str (string): Latex string drawing a regular gate at the given location """ imax = max(lines) imin = min(lines) gate_lines = lines + ctrl_lines delta_pos = self._gate_offset(gate) gate_width = self._gate_width(gate) gate_height = self._gate_height(gate) name = _gate_name(gate) lines = list(range(imin, imax + 1)) tex_str = "" pos = self.pos[lines[0]] node_str = "\n\\node[none] ({}) at ({},-{}) {{}};" for line in lines: node1 = node_str.format(self._op(line), pos, line) node2 = ( "\n\\node[none,minimum height={gate_height}cm,outer sep=0] ({self._op(line, offset=1)}) " f"at ({pos + gate_width / 2.0},-{line}) {{}};" ) node3 = node_str.format(self._op(line, offset=2), pos + gate_width, line) tex_str += node1 + node2 + node3 if line not in gate_lines: tex_str += self._line(self.op_count[line] - 1, self.op_count[line], line=line) tex_str += ( f"\n\\draw[operator,edgestyle,outer sep={gate_width}cm] ([" f"yshift={0.5 * gate_height}cm]{self._op(imin)}) rectangle ([yshift=-" f"{0.5 * gate_height}cm]{self._op(imax, offset=2)}) node[pos=.5] {{{name}}};" ) for line in lines: self.pos[line] = pos + gate_width / 2.0 self.op_count[line] += 1 for ctrl in ctrl_lines: if ctrl not in lines: tex_str += self._phase(ctrl, pos + gate_width / 2.0) connect_to = imax if abs(connect_to - ctrl) > abs(imin - ctrl): connect_to = imin tex_str += self._line(ctrl, connect_to) self.pos[ctrl] = pos + delta_pos + gate_width self.op_count[ctrl] += 1 for line in lines: self.op_count[line] += 2 for line in range(min(ctrl_lines + lines), max(ctrl_lines + lines) + 1): self.pos[line] = pos + delta_pos + gate_width return tex_str
Draw a regular gate. Args: gate: Gate to draw. lines (list<int>): Lines the gate acts on. ctrl_lines (list<int>): Control lines. Returns: tex_str (string): Latex string drawing a regular gate at the given location
_regular_gate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_circuits/_to_latex.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_circuits/_to_latex.py
Apache-2.0
def __init__( self, use_hardware=False, num_runs=1024, verbose=False, token='', device='ibmq_essex', num_retries=3000, interval=1, retrieve_execution=None, ): # pylint: disable=too-many-arguments """ Initialize the Backend object. Args: use_hardware (bool): If True, the code is run on the IBM quantum chip (instead of using the IBM simulator) num_runs (int): Number of runs to collect statistics. (default is 1024) verbose (bool): If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit). token (str): IBM quantum experience user password. device (str): name of the IBM device to use. ibmq_essex By default num_retries (int): Number of times to retry to obtain results from the IBM API. (default is 3000) interval (float, int): Number of seconds between successive attempts to obtain results from the IBM API. (default is 1) retrieve_execution (int): Job ID to retrieve instead of re- running the circuit (e.g., if previous run timed out). """ super().__init__() self._clear = False self._reset() if use_hardware: self.device = device else: self.device = 'ibmq_qasm_simulator' self._num_runs = num_runs self._verbose = verbose self._token = token self._num_retries = num_retries self._interval = interval self._probabilities = {} self.qasm = "" self._json = [] self._measured_ids = [] self._allocated_qubits = set() self._retrieve_execution = retrieve_execution
Initialize the Backend object. Args: use_hardware (bool): If True, the code is run on the IBM quantum chip (instead of using the IBM simulator) num_runs (int): Number of runs to collect statistics. (default is 1024) verbose (bool): If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit). token (str): IBM quantum experience user password. device (str): name of the IBM device to use. ibmq_essex By default num_retries (int): Number of times to retry to obtain results from the IBM API. (default is 3000) interval (float, int): Number of seconds between successive attempts to obtain results from the IBM API. (default is 1) retrieve_execution (int): Job ID to retrieve instead of re- running the circuit (e.g., if previous run timed out).
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def is_available(self, cmd): """ Return true if the command can be executed. The IBM quantum chip can only do U1,U2,U3,barriers, and CX / CNOT. Conversion implemented for Rotation gates and H gates. Args: cmd (Command): Command for which to check availability """ if has_negative_control(cmd): return False gate = cmd.gate if get_control_count(cmd) == 1: return gate == NOT if get_control_count(cmd) == 0: return gate == H or isinstance(gate, (Rx, Ry, Rz)) or gate in (Measure, Allocate, Deallocate, Barrier) return False
Return true if the command can be executed. The IBM quantum chip can only do U1,U2,U3,barriers, and CX / CNOT. Conversion implemented for Rotation gates and H gates. Args: cmd (Command): Command for which to check availability
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def _reset(self): """Reset all temporary variables (after flush gate).""" self._clear = True self._measured_ids = []
Reset all temporary variables (after flush gate).
_reset
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def _store(self, cmd): # pylint: disable=too-many-branches,too-many-statements """ Temporarily store the command cmd. Translates the command and stores it in a local variable (self._cmds). Args: cmd: Command to store """ if self.main_engine.mapper is None: raise RuntimeError('No mapper is present in the compiler engine list!') if self._clear: self._probabilities = {} self._clear = False self.qasm = "" self._json = [] self._allocated_qubits = set() gate = cmd.gate if gate == Allocate: self._allocated_qubits.add(cmd.qubits[0][0].id) return if gate == Deallocate: return if gate == Measure: logical_id = None for tag in cmd.tags: if isinstance(tag, LogicalQubitIDTag): logical_id = tag.logical_qubit_id break if logical_id is None: raise RuntimeError('No LogicalQubitIDTag found in command!') self._measured_ids += [logical_id] elif gate == NOT and get_control_count(cmd) == 1: ctrl_pos = cmd.control_qubits[0].id qb_pos = cmd.qubits[0][0].id self.qasm += f"\ncx q[{ctrl_pos}], q[{qb_pos}];" self._json.append({'qubits': [ctrl_pos, qb_pos], 'name': 'cx'}) elif gate == Barrier: qb_pos = [qb.id for qr in cmd.qubits for qb in qr] self.qasm += "\nbarrier " qb_str = "" for pos in qb_pos: qb_str += f"q[{pos}], " self.qasm += f"{qb_str[:-2]};" self._json.append({'qubits': qb_pos, 'name': 'barrier'}) elif isinstance(gate, (Rx, Ry, Rz)): qb_pos = cmd.qubits[0][0].id u_strs = {'Rx': 'u3({}, -pi/2, pi/2)', 'Ry': 'u3({}, 0, 0)', 'Rz': 'u1({})'} u_name = {'Rx': 'u3', 'Ry': 'u3', 'Rz': 'u1'} u_angle = { 'Rx': [gate.angle, -math.pi / 2, math.pi / 2], 'Ry': [gate.angle, 0, 0], 'Rz': [gate.angle], } gate_qasm = u_strs[str(gate)[0:2]].format(gate.angle) gate_name = u_name[str(gate)[0:2]] params = u_angle[str(gate)[0:2]] self.qasm += f"\n{gate_qasm} q[{qb_pos}];" self._json.append({'qubits': [qb_pos], 'name': gate_name, 'params': params}) elif gate == H: qb_pos = cmd.qubits[0][0].id self.qasm += f"\nu2(0,pi/2) q[{qb_pos}];" self._json.append({'qubits': [qb_pos], 'name': 'u2', 'params': [0, 3.141592653589793]}) else: raise InvalidCommandError( 'Command not authorized. You should run the circuit with the appropriate ibm setup.' )
Temporarily store the command cmd. Translates the command and stores it in a local variable (self._cmds). Args: cmd: Command to store
_store
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def _logical_to_physical(self, qb_id): """ Return the physical location of the qubit with the given logical id. Args: qb_id (int): ID of the logical qubit whose position should be returned. """ mapping = self.main_engine.mapper.current_mapping if qb_id not in mapping: raise RuntimeError( f"Unknown qubit id {qb_id}. " "Please make sure eng.flush() was called and that the qubit was eliminated during optimization." ) return mapping[qb_id]
Return the physical location of the qubit with the given logical id. Args: qb_id (int): ID of the logical qubit whose position should be returned.
_logical_to_physical
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def get_probabilities(self, qureg): """ Return the probability of the outcome `bit_string` when measuring the quantum register `qureg`. Return the list of basis states with corresponding probabilities. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states. The measured bits are ordered according to the supplied quantum register, i.e., the left-most bit in the state-string corresponds to the first qubit in the supplied quantum register. Warning: Only call this function after the circuit has been executed! Args: qureg (list<Qubit>): Quantum register determining the order of the qubits. Returns: probability_dict (dict): Dictionary mapping n-bit strings to probabilities. Raises: RuntimeError: If no data is available (i.e., if the circuit has not been executed). Or if a qubit was supplied which was not present in the circuit (might have gotten optimized away). """ if len(self._probabilities) == 0: raise RuntimeError("Please, run the circuit first!") probability_dict = {} for state, probability in self._probabilities.items(): mapped_state = ['0'] * len(qureg) for i, val in enumerate(qureg): mapped_state[i] = state[self._logical_to_physical(val.id)] mapped_state = "".join(mapped_state) if mapped_state not in probability_dict: probability_dict[mapped_state] = probability else: probability_dict[mapped_state] += probability return probability_dict
Return the probability of the outcome `bit_string` when measuring the quantum register `qureg`. Return the list of basis states with corresponding probabilities. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states. The measured bits are ordered according to the supplied quantum register, i.e., the left-most bit in the state-string corresponds to the first qubit in the supplied quantum register. Warning: Only call this function after the circuit has been executed! Args: qureg (list<Qubit>): Quantum register determining the order of the qubits. Returns: probability_dict (dict): Dictionary mapping n-bit strings to probabilities. Raises: RuntimeError: If no data is available (i.e., if the circuit has not been executed). Or if a qubit was supplied which was not present in the circuit (might have gotten optimized away).
get_probabilities
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def _run(self): # pylint: disable=too-many-locals """ Run the circuit. Send the circuit via a non documented IBM API (using JSON written circuits) using the provided user data / ask for the user token. """ # finally: add measurements (no intermediate measurements are allowed) for measured_id in self._measured_ids: qb_loc = self.main_engine.mapper.current_mapping[measured_id] self.qasm += f"\nmeasure q[{qb_loc}] -> c[{qb_loc}];" self._json.append({'qubits': [qb_loc], 'name': 'measure', 'memory': [qb_loc]}) # return if no operations / measurements have been performed. if self.qasm == "": return max_qubit_id = max(self._allocated_qubits) + 1 info = {} info['json'] = self._json info['nq'] = max_qubit_id info['shots'] = self._num_runs info['maxCredits'] = 10 info['backend'] = {'name': self.device} try: if self._retrieve_execution is None: res = send( info, device=self.device, token=self._token, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) else: res = retrieve( device=self.device, token=self._token, jobid=self._retrieve_execution, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) counts = res['data']['counts'] # Determine random outcome random_outcome = random.random() p_sum = 0.0 measured = "" for state in counts: probability = counts[state] * 1.0 / self._num_runs state = f"{int(state, 0):b}" state = state.zfill(max_qubit_id) # states in ibmq are right-ordered, so need to reverse state string state = state[::-1] p_sum += probability star = "" if p_sum >= random_outcome and measured == "": measured = state star = "*" self._probabilities[state] = probability if self._verbose and probability > 0: print(f"{str(state)} with p = {probability}{star}") # register measurement result from IBM for qubit_id in self._measured_ids: location = self._logical_to_physical(qubit_id) result = int(measured[location]) self.main_engine.set_measurement_result(WeakQubitRef(self, qubit_id), result) self._reset() except TypeError as err: raise Exception("Failed to run the circuit. Aborting.") from err
Run the circuit. Send the circuit via a non documented IBM API (using JSON written circuits) using the provided user data / ask for the user token.
_run
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the IBM QE API. Args: command_list: List of commands to execute """ for cmd in command_list: if not cmd.gate == FlushGate(): self._store(cmd) else: self._run() self._reset()
Receive a list of commands. Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the IBM QE API. Args: command_list: List of commands to execute
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py
Apache-2.0
def __init__(self, **kwargs): """Initialize a session with the IBM QE's APIs.""" super().__init__(**kwargs) self.backends = {} self.timeout = 5.0
Initialize a session with the IBM QE's APIs.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def get_list_devices(self, verbose=False): """ Get the list of available IBM backends with their properties. Args: verbose (bool): print the returned dictionary if True Returns: (dict) backends dictionary by name device, containing the qubit size 'nq', the coupling map 'coupling_map' as well as the device version 'version' """ list_device_url = 'Network/ibm-q/Groups/open/Projects/main/devices/v/1' argument = {'allow_redirects': True, 'timeout': (self.timeout, None)} request = super().get(urljoin(_API_URL, list_device_url), **argument) request.raise_for_status() r_json = request.json() self.backends = {} for obj in r_json: self.backends[obj['backend_name']] = { 'nq': obj['n_qubits'], 'coupling_map': obj['coupling_map'], 'version': obj['backend_version'], } if verbose: print('- List of IBMQ devices available:') print(self.backends) return self.backends
Get the list of available IBM backends with their properties. Args: verbose (bool): print the returned dictionary if True Returns: (dict) backends dictionary by name device, containing the qubit size 'nq', the coupling map 'coupling_map' as well as the device version 'version'
get_list_devices
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def can_run_experiment(self, info, device): """ Check if the device is big enough to run the code. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the ibm device to use Returns: (tuple): (bool) True if device is big enough, False otherwise (int) maximum number of qubit available on the device (int) number of qubit needed for the circuit """ nb_qubit_max = self.backends[device]['nq'] nb_qubit_needed = info['nq'] return nb_qubit_needed <= nb_qubit_max, nb_qubit_max, nb_qubit_needed
Check if the device is big enough to run the code. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the ibm device to use Returns: (tuple): (bool) True if device is big enough, False otherwise (int) maximum number of qubit available on the device (int) number of qubit needed for the circuit
can_run_experiment
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def authenticate(self, token=None): """ Authenticate with IBM's Web API. Args: token (str): IBM quantum experience user API token. """ if token is None: token = getpass.getpass(prompt="IBM QE token > ") if len(token) == 0: raise Exception('Error with the IBM QE token') self.headers.update({'X-Qx-Client-Application': CLIENT_APPLICATION}) args = { 'data': None, 'json': {'apiToken': token}, 'timeout': (self.timeout, None), } request = super().post(_AUTH_API_URL, **args) request.raise_for_status() r_json = request.json() self.params.update({'access_token': r_json['id']})
Authenticate with IBM's Web API. Args: token (str): IBM quantum experience user API token.
authenticate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def run(self, info, device): # pylint: disable=too-many-locals """ Run the quantum code to the IBMQ machine. Update since September 2020: only protocol available is what they call 'object storage' where a job request via the POST method gets in return a url link to which send the json data. A final http validates the data communication. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the ibm device to use Returns: (tuple): (str) Execution Id """ # STEP1: Obtain most of the URLs for handling communication with # quantum device json_step1 = { 'data': None, 'json': { 'backend': {'name': device}, 'allowObjectStorage': True, 'shareLevel': 'none', }, 'timeout': (self.timeout, None), } request = super().post( urljoin(_API_URL, 'Network/ibm-q/Groups/open/Projects/main/Jobs'), **json_step1, ) request.raise_for_status() r_json = request.json() upload_url = r_json['objectStorageInfo']['uploadUrl'] execution_id = r_json['id'] # STEP2: WE UPLOAD THE CIRCUIT DATA n_classical_reg = info['nq'] # hack: easier to restrict labels to measured qubits n_qubits = n_classical_reg # self.backends[device]['nq'] instructions = info['json'] maxcredit = info['maxCredits'] c_label = [["c", i] for i in range(n_classical_reg)] q_label = [["q", i] for i in range(n_qubits)] # hack: the data value in the json quantum code is a string instruction_str = str(instructions).replace('\'', '\"') data = '{"qobj_id": "' + str(uuid.uuid4()) + '", ' data += '"header": {"backend_name": "' + device + '", ' data += '"backend_version": "' + self.backends[device]['version'] + '"}, ' data += '"config": {"shots": ' + str(info['shots']) + ', ' data += '"max_credits": ' + str(maxcredit) + ', "memory": false, ' data += '"parameter_binds": [], "memory_slots": ' + str(n_classical_reg) data += ', "n_qubits": ' + str(n_qubits) + '}, "schema_version": "1.2.0", ' data += '"type": "QASM", "experiments": [{"config": ' data += '{"n_qubits": ' + str(n_qubits) + ', ' data += '"memory_slots": ' + str(n_classical_reg) + '}, ' data += '"header": {"qubit_labels": ' + str(q_label).replace('\'', '\"') + ', ' data += '"n_qubits": ' + str(n_classical_reg) + ', ' data += '"qreg_sizes": [["q", ' + str(n_qubits) + ']], ' data += '"clbit_labels": ' + str(c_label).replace('\'', '\"') + ', ' data += '"memory_slots": ' + str(n_classical_reg) + ', ' data += '"creg_sizes": [["c", ' + str(n_classical_reg) + ']], ' data += '"name": "circuit0", "global_phase": 0}, "instructions": ' + instruction_str + '}]}' json_step2 = { 'data': data, 'params': {'access_token': None}, 'timeout': (5.0, None), } request = super().put(upload_url, **json_step2) request.raise_for_status() # STEP3: CONFIRM UPLOAD json_step3 = {'data': None, 'json': None, 'timeout': (self.timeout, None)} upload_data_url = urljoin( _API_URL, 'Network/ibm-q/Groups/open/Projects/main/Jobs/' + str(execution_id) + '/jobDataUploaded', ) request = super().post(upload_data_url, **json_step3) request.raise_for_status() return execution_id
Run the quantum code to the IBMQ machine. Update since September 2020: only protocol available is what they call 'object storage' where a job request via the POST method gets in return a url link to which send the json data. A final http validates the data communication. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the ibm device to use Returns: (tuple): (str) Execution Id
run
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def get_result( self, device, execution_id, num_retries=3000, interval=1, verbose=False ): # pylint: disable=too-many-arguments,too-many-locals """Get the result of an execution.""" job_status_url = 'Network/ibm-q/Groups/open/Projects/main/Jobs/' + execution_id if verbose: print(f"Waiting for results. [Job ID: {execution_id}]") original_sigint_handler = signal.getsignal(signal.SIGINT) def _handle_sigint_during_get_result(*_): # pragma: no cover raise Exception(f"Interrupted. The ID of your submitted job is {execution_id}.") try: signal.signal(signal.SIGINT, _handle_sigint_during_get_result) for retries in range(num_retries): # STEP5: WAIT FOR THE JOB TO BE RUN json_step5 = {'allow_redirects': True, 'timeout': (self.timeout, None)} request = super().get(urljoin(_API_URL, job_status_url), **json_step5) request.raise_for_status() r_json = request.json() acceptable_status = ['VALIDATING', 'VALIDATED', 'RUNNING'] if r_json['status'] == 'COMPLETED': # STEP6: Get the endpoint to get the result json_step6 = { 'allow_redirects': True, 'timeout': (self.timeout, None), } request = super().get( urljoin(_API_URL, job_status_url + '/resultDownloadUrl'), **json_step6, ) request.raise_for_status() r_json = request.json() # STEP7: Get the result json_step7 = { 'allow_redirects': True, 'params': {'access_token': None}, 'timeout': (self.timeout, None), } request = super().get(r_json['url'], **json_step7) r_json = request.json() result = r_json['results'][0] # STEP8: Confirm the data was downloaded json_step8 = {'data': None, 'json': None, 'timeout': (5.0, None)} request = super().post( urljoin(_API_URL, job_status_url + '/resultDownloaded'), **json_step8, ) r_json = request.json() return result # Note: if stays stuck if 'Validating' mode, then sthg went # wrong in step 3 if r_json['status'] not in acceptable_status: raise Exception(f"Error while running the code. Last status: {r_json['status']}.") time.sleep(interval) if self.is_online(device) and retries % 60 == 0: self.get_list_devices() if not self.is_online(device): raise DeviceOfflineError( f"Device went offline. The ID of your submitted job is {execution_id}." ) finally: if original_sigint_handler is not None: signal.signal(signal.SIGINT, original_sigint_handler) raise Exception(f"Timeout. The ID of your submitted job is {execution_id}.")
Get the result of an execution.
get_result
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def show_devices(token=None, verbose=False): """ Access the list of available devices and their properties (ex: for setup configuration). Args: token (str): IBM quantum experience user API token. verbose (bool): If True, additional information is printed Returns: (list) list of available devices and their properties """ ibmq_session = IBMQ() ibmq_session.authenticate(token=token) return ibmq_session.get_list_devices(verbose=verbose)
Access the list of available devices and their properties (ex: for setup configuration). Args: token (str): IBM quantum experience user API token. verbose (bool): If True, additional information is printed Returns: (list) list of available devices and their properties
show_devices
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def retrieve(device, token, jobid, num_retries=3000, interval=1, verbose=False): # pylint: disable=too-many-arguments """ Retrieve a previously run job by its ID. Args: device (str): Device on which the code was run / is running. token (str): IBM quantum experience user API token. jobid (str): Id of the job to retrieve Returns: (dict) result form the IBMQ server """ ibmq_session = IBMQ() ibmq_session.authenticate(token) ibmq_session.get_list_devices(verbose) res = ibmq_session.get_result(device, jobid, num_retries=num_retries, interval=interval, verbose=verbose) return res
Retrieve a previously run job by its ID. Args: device (str): Device on which the code was run / is running. token (str): IBM quantum experience user API token. jobid (str): Id of the job to retrieve Returns: (dict) result form the IBMQ server
retrieve
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def send( info, device='ibmq_qasm_simulator', token=None, shots=None, num_retries=3000, interval=1, verbose=False, ): # pylint: disable=too-many-arguments """ Send QASM through the IBM API and runs the quantum circuit. Args: info(dict): Contains representation of the circuit to run. device (str): name of the ibm device. Simulator chosen by default token (str): IBM quantum experience user API token. shots (int): Number of runs of the same circuit to collect statistics. verbose (bool): If True, additional information is printed, such as measurement statistics. Otherwise, the backend simply registers one measurement result (same behavior as the projectq Simulator). Returns: (dict) result form the IBMQ server """ try: ibmq_session = IBMQ() # Shots argument deprecated, as already if shots is not None: info['shots'] = shots if verbose: print("- Authenticating...") if token is not None: print('user API token: ' + token) ibmq_session.authenticate(token) # check if the device is online ibmq_session.get_list_devices(verbose) online = ibmq_session.is_online(device) if not online: print("The device is offline (for maintenance?). Use the simulator instead or try again later.") raise DeviceOfflineError("Device is offline.") # check if the device has enough qubit to run the code runnable, qmax, qneeded = ibmq_session.can_run_experiment(info, device) if not runnable: print( f"The device is too small ({qmax} qubits available) for the code " f"requested({qneeded} qubits needed) Try to look for another device with more qubits" ) raise DeviceTooSmall("Device is too small.") if verbose: print(f"- Running code: {info}") execution_id = ibmq_session.run(info, device) if verbose: print("- Waiting for results...") res = ibmq_session.get_result( device, execution_id, num_retries=num_retries, interval=interval, verbose=verbose, ) if verbose: print("- Done.") return res except requests.exceptions.HTTPError as err: print("- There was an error running your code:") print(err) except requests.exceptions.RequestException as err: print("- Looks like something is wrong with server:") print(err) except KeyError as err: print("- Failed to parse response:") print(err) return None
Send QASM through the IBM API and runs the quantum circuit. Args: info(dict): Contains representation of the circuit to run. device (str): name of the ibm device. Simulator chosen by default token (str): IBM quantum experience user API token. shots (int): Number of runs of the same circuit to collect statistics. verbose (bool): If True, additional information is printed, such as measurement statistics. Otherwise, the backend simply registers one measurement result (same behavior as the projectq Simulator). Returns: (dict) result form the IBMQ server
send
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ibm/_ibm_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py
Apache-2.0
def is_available(self, cmd): """ Test if this backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command. """ gate = cmd.gate # Metagates. if gate in (Measure, Allocate, Deallocate, Barrier): return True if has_negative_control(cmd): return False # CNOT gates. # NOTE: IonQ supports up to 7 control qubits num_ctrl_qubits = get_control_count(cmd) if 0 < num_ctrl_qubits <= 7: return isinstance(gate, (XGate,)) # Gates without control bits. if num_ctrl_qubits == 0: supported = isinstance(gate, SUPPORTED_GATES) supported_transpose = gate in (Sdag, Tdag) return supported or supported_transpose return False
Test if this backend is available to process the provided command. Args: cmd (Command): A command to process. Returns: bool: If this backend can process the command.
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ionq/_ionq.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq.py
Apache-2.0
def _reset(self): """ Reset this backend. Note: This sets ``_clear = True``, which will trigger state cleanup on the next call to ``_store``. """ # Lastly, reset internal state for measured IDs and circuit body. self._circuit = [] self._clear = True
Reset this backend. Note: This sets ``_clear = True``, which will trigger state cleanup on the next call to ``_store``.
_reset
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ionq/_ionq.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq.py
Apache-2.0
def _store(self, cmd): """Interpret the ProjectQ command as a circuit instruction and store it. Args: cmd (Command): A command to process. Raises: InvalidCommandError: If the command can not be interpreted. MidCircuitMeasurementError: If this command would result in a mid-circuit qubit measurement. """ if self._clear: self._measured_ids = [] self._probabilities = {} self._clear = False # No-op/Meta gates. # NOTE: self.main_engine.mapper takes care qubit allocation/mapping. gate = cmd.gate if gate in (Allocate, Deallocate, Barrier): return # Create a measurement. if gate == Measure: logical_id = cmd.qubits[0][0].id for tag in cmd.tags: if isinstance(tag, LogicalQubitIDTag): logical_id = tag.logical_qubit_id break # Add the qubit id self._measured_ids.append(logical_id) return # Process the Command's gate type: gate_type = type(gate) gate_name = GATE_MAP.get(gate_type) # Daggered gates get special treatment. if isinstance(gate, DaggeredGate): gate_name = f"{GATE_MAP[type(gate._gate)]}i" # pylint: disable=protected-access # Unable to determine a gate mapping here, so raise out. if gate_name is None: raise InvalidCommandError(f"Invalid command: {str(cmd)}") # Now make sure there are no existing measurements on qubits involved # in this operation. targets = [qb.id for qureg in cmd.qubits for qb in qureg] controls = [qb.id for qb in cmd.control_qubits] if len(self._measured_ids) > 0: # Check any qubits we are trying to operate on. gate_qubits = set(targets) | set(controls) # If any of them have already been measured... already_measured = gate_qubits & set(self._measured_ids) # Boom! if len(already_measured) > 0: err = ( 'Mid-circuit measurement is not supported. ' f'The following qubits have already been measured: {list(already_measured)}.' ) raise MidCircuitMeasurementError(err) # Initialize the gate dict: gate_dict = { 'gate': gate_name, 'targets': targets, } # Check if we have a rotation if isinstance(gate, (R, Rx, Ry, Rz, Rxx, Ryy, Rzz)): gate_dict['rotation'] = gate.angle # Set controls if len(controls) > 0: gate_dict['controls'] = controls self._circuit.append(gate_dict)
Interpret the ProjectQ command as a circuit instruction and store it. Args: cmd (Command): A command to process. Raises: InvalidCommandError: If the command can not be interpreted. MidCircuitMeasurementError: If this command would result in a mid-circuit qubit measurement.
_store
python
ProjectQ-Framework/ProjectQ
projectq/backends/_ionq/_ionq.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq.py
Apache-2.0