def _cpmg_sweep(num_pulses: List[int]): """Returns a sweep for a circuit created by _cpmg_circuit. The circuit in _cpmg_circuit parameterizes the pulses, so this function fills in the parameters for each pulse. For instance, if we want 3 pulses, pulse_0, pulse_1, and pulse_2 should be 1 and the rest of the pulses should be 0. """ pulse_points = [] for n in range(max(num_pulses)): pulse_points.append(study.Points(f'pulse_{n}', [1 if p > n else 0 for p in num_pulses])) return study.Zip(*pulse_points)
def t2_decay( sampler: 'cirq.Sampler', *, qubit: 'cirq.Qid', experiment_type: 'ExperimentType' = ExperimentType.RAMSEY, num_points: int, max_delay: 'cirq.DURATION_LIKE', min_delay: 'cirq.DURATION_LIKE' = None, repetitions: int = 1000, delay_sweep: Optional[study.Sweep] = None, num_pulses: List[int] = None ) -> Union['cirq.experiments.T2DecayResult', List['cirq.experiments.T2DecayResult']]: """Runs a t2 transverse relaxation experiment. Initializes a qubit into a superposition state, evolves the system using rules determined by the experiment type and by the delay parameters, then rotates back for measurement. This will measure the phase decoherence decay. This experiment has three types of T2 metrics, each which measure a different slice of the noise spectrum. For the Ramsey experiment type (often denoted T2*), the state will be prepared with a square root Y gate (`cirq.Y ** 0.5`) and then waits for a variable amount of time. After this time, it will do basic state tomography to measure the expectation of the Pauli-X and Pauli-Y operators by performing either a `cirq.Y ** -0.5` or `cirq.X ** 0.5`. The square of these two measurements is summed to determine the length of the Bloch vector. This experiment measures the phase decoherence of the system under free evolution. For the Hahn echo experiment (often denoted T2 or spin echo), the state will also be prepared with a square root Y gate (`cirq.Y ** 0.5`). However, during the mid-point of the delay time being measured, a pi-pulse (`cirq.X`) gate will be applied to cancel out inhomogeneous dephasing. The same method of measuring the final state as Ramsey experiment is applied after the second half of the delay period. See the animation on the wiki page https://en.wikipedia.org/wiki/Spin_echo for a visual illustration of this experiment. CPMG, or the Carr-Purcell-Meiboom-Gill sequence, involves using a sqrt(Y) followed by a sequence of pi pulses (X gates) in a specific timing pattern: π/2, t, π, 2t, π, ... 2t, π, t The first pulse, a sqrt(Y) gate, will put the qubit's state on the Bloch equator. After a delay, successive X gates will refocus dehomogenous phase effects by causing them to precess in opposite directions and averaging their effects across the entire pulse train. This pulse pattern has two variables that can be adjusted. The first, denoted as 't' in the above sequence, is delay, which can be specified with `delay_min` and `delay_max` or by using a `delay_sweep`, similar to the other experiments. The second variable is the number of pi pulses (X gates). This can be specified as a list of integers using the `num_pulses` parameter. If multiple different pulses are specified, the data will be presented in a data frame with two indices (delay_ns and num_pulses). See the following reference for more information about CPMG pulse trains: Meiboom, S., and D. Gill, “Modified spin-echo method for measuring nuclear relaxation times”, Rev. Sci. Inst., 29, 688–691 (1958). https://doi.org/10.1063/1.1716296 Note that interpreting T2 data is fairly tricky and subtle, as it can include other effects that need to be accounted for. For instance, amplitude damping (T1) will present as T2 noise and needs to be appropriately compensated for to find a true measure of T2. Due to this subtlety and lack of standard way to interpret the data, the fitting of the data to an exponential curve and the extrapolation of an actual T2 time value is left as an exercise to the reader. Args: sampler: The quantum engine or simulator to run the circuits. qubit: The qubit under test. experiment_type: The type of T2 test to run. num_points: The number of evenly spaced delays to test. max_delay: The largest delay to test. min_delay: The smallest delay to test. Defaults to no delay. repetitions: The number of repetitions of the circuit for each delay and for each tomography result. delay_sweep: Optional range of time delays to sweep across. This should be a SingleSweep using the 'delay_ns' with values in integer number of nanoseconds. If specified, this will override the max_delay and min_delay parameters. If not specified, the experiment will sweep from min_delay to max_delay with linear steps. num_pulses: For CPMG, a list of the number of pulses to use. If multiple pulses are specified, each will be swept on. Returns: A T2DecayResult object that stores and can plot the data. """ min_delay_dur = value.Duration(min_delay) max_delay_dur = value.Duration(max_delay) # Input validation if repetitions <= 0: raise ValueError('repetitions <= 0') if max_delay_dur < min_delay_dur: raise ValueError('max_delay < min_delay') if min_delay_dur < 0: raise ValueError('min_delay < 0') if num_pulses and experiment_type != ExperimentType.CPMG: raise ValueError('num_pulses is only valid for CPMG experiments.') # Initialize values used in sweeps delay_var = sympy.Symbol('delay_ns') inv_x_var = sympy.Symbol('inv_x') inv_y_var = sympy.Symbol('inv_y') max_pulses = max(num_pulses) if num_pulses else 0 if not delay_sweep: delay_sweep = study.Linspace(delay_var, start=min_delay_dur.total_nanos(), stop=max_delay_dur.total_nanos(), length=num_points) if delay_sweep.keys != ['delay_ns']: raise ValueError('delay_sweep must be a SingleSweep ' 'with delay_ns parameter') if experiment_type == ExperimentType.RAMSEY: # Ramsey T2* experiment # Use sqrt(Y) to flip to the equator. # Evolve the state for a given amount of delay time # Then measure the state in both X and Y bases. circuit = circuits.Circuit( ops.Y(qubit)**0.5, ops.wait(qubit, nanos=delay_var), ) else: if experiment_type == ExperimentType.HAHN_ECHO: # Hahn / Spin Echo T2 experiment # Use sqrt(Y) to flip to the equator. # Evolve the state for the given amount of delay time # Flip the state using an X gate # Evolve the state for the given amount of delay time # Then measure the state in both X and Y bases. num_pulses = [0] # This is equivalent to a CPMG experiment with zero pulses # and will follow the same code path. # Carr-Purcell-Meiboom-Gill sequence. # Performs the following sequence # π/2 - wait(t) - π - wait(2t) - ... - π - wait(t) # There will be N π pulses (X gates) # where N sweeps over the values of num_pulses # if not num_pulses: raise ValueError('At least one value must be given ' 'for num_pulses in a CPMG experiment') circuit = _cpmg_circuit(qubit, delay_var, max_pulses) # Add simple state tomography circuit.append(ops.X(qubit)**inv_x_var) circuit.append(ops.Y(qubit)**inv_y_var) circuit.append(ops.measure(qubit, key='output')) tomography_sweep = study.Zip( study.Points('inv_x', [0.0, 0.5]), study.Points('inv_y', [-0.5, 0.0]), ) if num_pulses and max_pulses > 0: pulse_sweep = _cpmg_sweep(num_pulses) sweep = study.Product(delay_sweep, pulse_sweep, tomography_sweep) else: sweep = study.Product(delay_sweep, tomography_sweep) # Tabulate measurements into a histogram results = sampler.sample(circuit, params=sweep, repetitions=repetitions) y_basis_measurements = results[abs(results.inv_y) > 0].copy() x_basis_measurements = results[abs(results.inv_x) > 0].copy() if num_pulses and len(num_pulses) > 1: cols = tuple(f'pulse_{t}' for t in range(max_pulses)) x_basis_measurements[ 'num_pulses'] = x_basis_measurements.loc[:, cols].sum(axis=1) y_basis_measurements[ 'num_pulses'] = y_basis_measurements.loc[:, cols].sum(axis=1) x_basis_tabulation = _create_tabulation(x_basis_measurements) y_basis_tabulation = _create_tabulation(y_basis_measurements) # Return the results in a container object return T2DecayResult(x_basis_tabulation, y_basis_tabulation)
def estimate_parallel_single_qubit_readout_errors( sampler: 'cirq.Sampler', *, qubits: Iterable['cirq.Qid'], trials: int = 20, repetitions: int = 1000, trials_per_batch: Optional[int] = None, bit_strings: np.ndarray = None, ) -> SingleQubitReadoutCalibrationResult: """Estimate single qubit readout error using parallel operations. For each trial, prepare and then measure a random computational basis bitstring on qubits using gates in parallel. Returns a SingleQubitReadoutCalibrationResult which can be used to compute readout errors for each qubit. Args: sampler: The `cirq.Sampler` used to run the circuits. qubits: The qubits being tested. repetitions: The number of measurement repetitions to perform for each trial. trials: The number of bitstrings to prepare. trials_per_batch: If provided, split the experiment into batches with this number of trials in each batch. bit_strings: Optional numpy array of shape (trials, qubits) where the first dimension is the number of the trial and the second dimension is the qubit (ordered by the qubit order from the qubits parameter). Each value should be a 0 or 1 which specifies which state the qubit should be prepared into during that trial. If not provided, the function will generate random bit strings for you. Returns: A SingleQubitReadoutCalibrationResult storing the readout error probabilities as well as the number of repetitions used to estimate the probabilities. Also stores a timestamp indicating the time when data was finished being collected from the sampler. Note that, if there did not exist a trial where a given qubit was set to |0〉, the zero-state error will be set to `nan` (not a number). Likewise for qubits with no |1〉trial and one-state error. """ qubits = list(qubits) if trials <= 0: raise ValueError("Must provide non-zero trials for readout calibration.") if repetitions <= 0: raise ValueError("Must provide non-zero repetition for readout calibration.") if bit_strings is None: bit_strings = np.random.randint(0, 2, size=(trials, len(qubits))) else: if not hasattr(bit_strings, 'shape') or bit_strings.shape != (trials, len(qubits)): raise ValueError( 'bit_strings must be numpy array ' f'of shape (trials, qubits) ({trials}, {len(qubits)}) ' f"but was {bit_strings.shape if hasattr(bit_strings, 'shape') else None}" ) if not np.all((bit_strings == 0) | (bit_strings == 1)): raise ValueError('bit_strings values must be all 0 or 1') if trials_per_batch is None: trials_per_batch = trials if trials_per_batch <= 0: raise ValueError("Must provide non-zero trials_per_batch for readout calibration.") all_sweeps: List[study.Sweepable] = [] num_batches = (trials + trials_per_batch - 1) // trials_per_batch # Initialize circuits flip_symbols = sympy.symbols(f'flip_0:{len(qubits)}') flip_circuit = circuits.Circuit( [ops.X(q) ** s for q, s in zip(qubits, flip_symbols)], [ops.measure_each(*qubits, key_func=repr)], ) all_circuits = [flip_circuit] * num_batches # Initialize sweeps for batch in range(num_batches): single_sweeps = [] for qubit_idx in range(len(qubits)): trial_range = range( batch * trials_per_batch, min((batch + 1) * trials_per_batch, trials) ) single_sweeps.append( study.Points( key=f'flip_{qubit_idx}', points=[bit_strings[bit][qubit_idx] for bit in trial_range], ) ) total_sweeps = study.Zip(*single_sweeps) all_sweeps.append(total_sweeps) # Execute circuits results = sampler.run_batch(all_circuits, all_sweeps, repetitions=repetitions) timestamp = time.time() # Analyze results zero_state_trials = np.zeros((1, len(qubits))) one_state_trials = np.zeros((1, len(qubits))) zero_state_totals = np.zeros((1, len(qubits))) one_state_totals = np.zeros((1, len(qubits))) trial_idx = 0 for batch_result in results: for trial_result in batch_result: all_measurements = trial_result.data[[repr(x) for x in qubits]].to_numpy() sample_counts = np.einsum('ij->j', all_measurements) zero_state_trials += sample_counts * (1 - bit_strings[trial_idx]) zero_state_totals += repetitions * (1 - bit_strings[trial_idx]) one_state_trials += (repetitions - sample_counts) * bit_strings[trial_idx] one_state_totals += repetitions * bit_strings[trial_idx] trial_idx += 1 zero_state_errors = { q: zero_state_trials[0][qubit_idx] / zero_state_totals[0][qubit_idx] if zero_state_totals[0][qubit_idx] > 0 else np.nan for qubit_idx, q in enumerate(qubits) } one_state_errors = { q: one_state_trials[0][qubit_idx] / one_state_totals[0][qubit_idx] if one_state_totals[0][qubit_idx] > 0 else np.nan for qubit_idx, q in enumerate(qubits) } return SingleQubitReadoutCalibrationResult( zero_state_errors=zero_state_errors, one_state_errors=one_state_errors, repetitions=repetitions, timestamp=timestamp, )
def t2_decay( sampler: work.Sampler, *, qubit: devices.GridQubit, experiment_type: 'ExperimentType' = ExperimentType.RAMSEY, num_points: int, max_delay: 'cirq.DURATION_LIKE', min_delay: 'cirq.DURATION_LIKE' = None, repetitions: int = 1000, delay_sweep: Optional[study.Sweep] = None, ) -> 'cirq.experiments.T2DecayResult': """Runs a t2 transverse relaxation experiment. Initializes a qubit into a superposition state, evolves the system using rules determined by the experiment type and by the delay parameters, then rotates back for measurement. This will measure the phase decoherence decay. This experiment has three types of T2 metrics, each which measure a different slice of the noise spectrum. For the Ramsey experiment type (often denoted T2*), the state will be prepared with a square root Y gate (`cirq.Y ** 0.5`) and then waits for a variable amount of time. After this time, it will do basic state tomography to measure the expectation of the Pauli-X and Pauli-Y operators by performing either a `cirq.Y ** -0.5` or `cirq.X ** -0.5`. The square of these two measurements is summed to determine the length of the Bloch vector. This experiment measures the phase decoherence of the system under free evolution. For the Hahn echo experiment (often denoted T2 or spin echo), the state will also be prepared with a square root Y gate (`cirq.Y ** 0.5`). However, during the mid-point of the delay time being measured, a pi-pulse (`cirq.X`) gate will be applied to cancel out inhomogeneous dephasing. The same method of measuring the final state as Ramsey experiment is applied after the second half of the delay period. CPMG, or the Carr-Purcell-Meiboom-Gill sequence, is currently not implemented. Args: sampler: The quantum engine or simulator to run the circuits. qubit: The qubit under test. experiment_type: The type of T2 test to run. num_points: The number of evenly spaced delays to test. max_delay: The largest delay to test. min_delay: The smallest delay to test. Defaults to no delay. repetitions: The number of repetitions of the circuit for each delay and for each tomography result. delay_sweep: Optional range of time delays to sweep across. This should be a SingleSweep using the 'delay_ns' with values in integer number of nanoseconds. If specified, this will override the max_delay and min_delay parameters. If not specified, the experiment will sweep from min_delay to max_delay with linear steps. Returns: A T2DecayResult object that stores and can plot the data. """ min_delay_dur = value.Duration(min_delay) max_delay_dur = value.Duration(max_delay) # Input validation if repetitions <= 0: raise ValueError('repetitions <= 0') if max_delay_dur < min_delay_dur: raise ValueError('max_delay < min_delay') if min_delay_dur < 0: raise ValueError('min_delay < 0') # Initialize values used in sweeps delay_var = sympy.Symbol('delay_ns') inv_x_var = sympy.Symbol('inv_x') inv_y_var = sympy.Symbol('inv_y') if not delay_sweep: delay_sweep = study.Linspace(delay_var, start=min_delay_dur.total_nanos(), stop=max_delay_dur.total_nanos(), length=num_points) if delay_sweep.keys != ['delay_ns']: raise ValueError('delay_sweep must be a SingleSweep ' 'with delay_ns parameter') if experiment_type == ExperimentType.RAMSEY: # Ramsey T2* experiment # Use sqrt(Y) to flip to the equator. # Evolve the state for a given amount of delay time # Then measure the state in both X and Y bases. circuit = circuits.Circuit( ops.Y(qubit)**0.5, ops.WaitGate(value.Duration(nanos=delay_var))(qubit), ops.X(qubit)**inv_x_var, ops.Y(qubit)**inv_y_var, ops.measure(qubit, key='output'), ) tomography_sweep = study.Zip( study.Points('inv_x', [0.0, -0.5]), study.Points('inv_y', [-0.5, 0.0]), ) sweep = study.Product(delay_sweep, tomography_sweep) elif experiment_type == ExperimentType.HAHN_ECHO: # Hahn / Spin Echo T2 experiment # Use sqrt(Y) to flip to the equator. # Evolve the state for half the given amount of delay time # Flip the state using an X gate # Evolve the state for half the given amount of delay time # Then measure the state in both X and Y bases. circuit = circuits.Circuit( ops.Y(qubit)**0.5, ops.WaitGate(value.Duration(nanos=0.5 * delay_var))(qubit), ops.X(qubit), ops.WaitGate(value.Duration(nanos=0.5 * delay_var))(qubit), ops.X(qubit)**inv_x_var, ops.Y(qubit)**inv_y_var, ops.measure(qubit, key='output'), ) tomography_sweep = study.Zip( study.Points('inv_x', [0.0, 0.5]), study.Points('inv_y', [-0.5, 0.0]), ) sweep = study.Product(delay_sweep, tomography_sweep) else: raise ValueError(f'Experiment type {experiment_type} not supported') # Tabulate measurements into a histogram results = sampler.sample(circuit, params=sweep, repetitions=repetitions) y_basis_measurements = results[abs(results.inv_y) > 0] x_basis_measurements = results[abs(results.inv_x) > 0] x_basis_tabulation = pd.crosstab( x_basis_measurements.delay_ns, x_basis_measurements.output).reset_index() y_basis_tabulation = pd.crosstab( y_basis_measurements.delay_ns, y_basis_measurements.output).reset_index() # If all measurements are 1 or 0, fill in the missing column with all zeros. for tab in [x_basis_tabulation, y_basis_tabulation]: for col_index, name in [(1, 0), (2, 1)]: if name not in tab: tab.insert(col_index, name, [0] * tab.shape[0]) # Return the results in a container object return T2DecayResult(x_basis_tabulation, y_basis_tabulation)