예제 #1
0
    def compute_displays_sweep(
        self,
        program: Union[circuits.Circuit, schedules.Schedule],
        params: Optional[study.Sweepable] = None,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Union[int, np.ndarray] = 0,
    ) -> List[study.ComputeDisplaysResult]:
        """Computes displays in the supplied Circuit or Schedule.

        In contrast to `compute_displays`, this allows for sweeping
        over different parameter values.

        Args:
            program: The circuit or schedule to simulate.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits used to
                define the order of amplitudes in the wave function.
            initial_state: If an int, the state is set to the computational
                basis state corresponding to this state. Otherwise if it is a
                np.ndarray it is the full initial state, either a pure state
                or the full density matrix. If it is the pure state it must be
                the correct size, be normalized (an L2 norm of 1), and be
                safely castable to an appropriate dtype for the simulator.
                If it is a mixed state it must be correctly sized and
                positive semidefinite with trace one.

        Returns:
            List of ComputeDisplaysResults for this run, one for each
            possible parameter resolver.
        """
        circuit = (program.to_circuit()
                   if isinstance(program, schedules.Schedule) else program)
        qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
        qubits = qubit_order.order_for(circuit.all_qubits())

        compute_displays_results: List[study.ComputeDisplaysResult] = []
        for param_resolver in study.to_resolvers(params):
            display_values: Dict[Hashable, Any] = {}

            # Compute the displays in the first Moment
            moment = circuit[0]
            matrix = density_matrix_utils.to_valid_density_matrix(
                initial_state, num_qubits=len(qubits), dtype=self._dtype)
            qubit_map = {q: i for i, q in enumerate(qubits)}
            _enter_moment_display_values_into_dictionary(
                display_values, moment, matrix, qubits, qubit_map)

            # Compute the displays in the rest of the Moments
            all_step_results = self.simulate_moment_steps(
                circuit, param_resolver, qubits, initial_state)
            for step_result, moment in zip(all_step_results, circuit[1:]):
                _enter_moment_display_values_into_dictionary(
                    display_values, moment, step_result.density_matrix(),
                    qubits, step_result._qubit_map)

            compute_displays_results.append(
                study.ComputeDisplaysResult(params=param_resolver,
                                            display_values=display_values))

        return compute_displays_results
 def simulate_expectation_values_sweep(
     self,
     program: 'cirq.Circuit',
     observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
     params: 'study.Sweepable',
     qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
     initial_state: Any = None,
     permit_terminal_measurements: bool = False,
 ) -> List[List[float]]:
     if not permit_terminal_measurements and program.are_any_measurements_terminal():
         raise ValueError(
             'Provided circuit has terminal measurements, which may '
             'skew expectation values. If this is intentional, set '
             'permit_terminal_measurements=True.'
         )
     swept_evs = []
     qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
     qmap = {q: i for i, q in enumerate(qubit_order.order_for(program.all_qubits()))}
     if not isinstance(observables, List):
         observables = [observables]
     pslist = [ops.PauliSum.wrap(pslike) for pslike in observables]
     for param_resolver in study.to_resolvers(params):
         result = cast(
             state_vector_simulator.StateVectorTrialResult,
             self.simulate(
                 program, param_resolver, qubit_order=qubit_order, initial_state=initial_state
             ),
         )
         swept_evs.append(
             [
                 obs.expectation_from_state_vector(result.final_state_vector, qmap)
                 for obs in pslist
             ]
         )
     return swept_evs
예제 #3
0
 def simulate_expectation_values_sweep_iter(
     self,
     program: 'cirq.AbstractCircuit',
     observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
     params: 'cirq.Sweepable',
     qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
     initial_state: Any = None,
     permit_terminal_measurements: bool = False,
 ) -> Iterator[List[float]]:
     if not permit_terminal_measurements and program.are_any_measurements_terminal():
         raise ValueError(
             'Provided circuit has terminal measurements, which may '
             'skew expectation values. If this is intentional, set '
             'permit_terminal_measurements=True.'
         )
     qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
     qmap = {q: i for i, q in enumerate(qubit_order.order_for(program.all_qubits()))}
     if not isinstance(observables, List):
         observables = [observables]
     pslist = [ops.PauliSum.wrap(pslike) for pslike in observables]
     yield from (
         [obs.expectation_from_state_vector(result.final_state_vector, qmap) for obs in pslist]
         for result in self.simulate_sweep_iter(
             program, params, qubit_order=qubit_order, initial_state=initial_state
         )
     )
예제 #4
0
파일: simulator.py 프로젝트: sgangoly/Cirq
    def simulate_sweep(
        self,
        program: Union[circuits.Circuit, schedules.Schedule],
        params: study.Sweepable = study.ParamResolver({}),
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Union[int, np.ndarray] = 0,
    ) -> List['SimulationTrialResult']:
        """Simulates the entire supplied Circuit.

        This method returns a result which allows access to the entire
        wave function. In contrast to simulate, this allows for sweeping
        over different parameter values.

        Args:
            program: The circuit or schedule to simulate.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits used to
                define the order of amplitudes in the wave function.
            initial_state: If an int, the state is set to the computational
                basis state corresponding to this state.
                Otherwise if this is a np.ndarray it is the full initial state.
                In this case it must be the correct size, be normalized (an L2
                norm of 1), and  be safely castable to an appropriate
                dtype for the simulator.

        Returns:
            List of SimulatorTrialResults for this run, one for each
            possible parameter resolver.
        """
        circuit = (program if isinstance(program, circuits.Circuit)
                   else program.to_circuit())
        param_resolvers = study.to_resolvers(params or study.ParamResolver({}))

        trial_results = []  # type: List[SimulationTrialResult]
        qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
        for param_resolver in param_resolvers:
            step_result = None
            all_step_results = self.simulate_moment_steps(circuit,
                                                          param_resolver,
                                                          qubit_order,
                                                          initial_state)
            measurements = {}  # type: Dict[str, np.ndarray]
            for step_result in all_step_results:
                for k, v in step_result.measurements.items():
                    measurements[k] = np.array(v, dtype=bool)
            if step_result:
                final_state = step_result.state()
            else:
                # Empty circuit, so final state should be initial state.
                num_qubits = len(qubit_order.order_for(circuit.all_qubits()))
                final_state = wave_function.to_valid_state_vector(initial_state,
                                                                  num_qubits)
            trial_results.append(SimulationTrialResult(
                params=param_resolver,
                measurements=measurements,
                final_state=final_state))

        return trial_results
예제 #5
0
    def simulate_sweep(
            self,
            program: Union[Circuit, Schedule],
            params: Sweepable = ParamResolver({}),
            qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
            initial_state: Union[int, np.ndarray] = 0,
            extensions: Extensions = None) -> List[XmonSimulateTrialResult]:
        """Simulates the entire supplied Circuit.

        Args:
            program: The circuit or schedule to simulate.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits used to
                define the order of amplitudes in the wave function.
            initial_state: If an int, the state is set to the computational
                basis state corresponding to this state.
                Otherwise if this is a np.ndarray it is the full initial state.
                In this case it must be the correct size, be normalized (an L2
                norm of 1), and be safely castable to a np.complex64.
            extensions: Extensions that will be applied while trying to
                decompose the circuit's gates into XmonGates. If None, this
                uses the default of xmon_gate_ext.

        Returns:
            List of XmonSimulatorTrialResults for this run, one for each
            possible parameter resolver.
        """
        circuit = (program
                   if isinstance(program, Circuit) else program.to_circuit())
        param_resolvers = self._to_resolvers(params or ParamResolver({}))

        trial_results = []  # type: List[XmonSimulateTrialResult]
        qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
        for param_resolver in param_resolvers:
            xmon_circuit, _ = self._to_xmon_circuit(
                circuit, param_resolver, extensions or xmon_gate_ext)
            measurements = {}  # type: Dict[str, np.ndarray]
            all_step_results = _simulator_iterator(xmon_circuit, self.options,
                                                   qubit_order, initial_state)
            step_result = None
            for step_result in all_step_results:
                for k, v in step_result.measurements.items():
                    measurements[k] = np.array(v, dtype=bool)
            if step_result:
                final_state = step_result.state()
            else:
                # Empty circuit, so final state should be initial state.
                num_qubits = len(qubit_order.order_for(circuit.all_qubits()))
                final_state = xmon_stepper.decode_initial_state(
                    initial_state, num_qubits)
            trial_results.append(
                XmonSimulateTrialResult(params=param_resolver,
                                        measurements=measurements,
                                        final_state=final_state))
        return trial_results
예제 #6
0
    def simulate_sweep(
        self,
        program: Union[Circuit, Schedule],
        params: Sweepable = ParamResolver({}),
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Union[int, np.ndarray] = 0,
        extensions: Extensions = None
    ) -> List[XmonSimulateTrialResult]:
        """Simulates the entire supplied Circuit.

        Args:
            program: The circuit or schedule to simulate.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits used to
                define the order of amplitudes in the wave function.
            initial_state: If an int, the state is set to the computational
                basis state corresponding to this state.
                Otherwise if this is a np.ndarray it is the full initial state.
                In this case it must be the correct size, be normalized (an L2
                norm of 1), and be safely castable to a np.complex64.
            extensions: Extensions that will be applied while trying to
                decompose the circuit's gates into XmonGates. If None, this
                uses the default of xmon_gate_ext.

        Returns:
            List of XmonSimulatorTrialResults for this run, one for each
            possible parameter resolver.
        """
        circuit = (
            program if isinstance(program, Circuit) else program.to_circuit())
        param_resolvers = self._to_resolvers(params or ParamResolver({}))

        trial_results = []  # type: List[XmonSimulateTrialResult]
        qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
        for param_resolver in param_resolvers:
            xmon_circuit, _ = self._to_xmon_circuit(
                circuit,
                param_resolver,
                extensions or xmon_gate_ext)
            measurements = {}  # type: Dict[str, np.ndarray]
            all_step_results = _simulator_iterator(
                xmon_circuit,
                self.options,
                qubit_order,
                initial_state)
            step_result = None
            for step_result in all_step_results:
                for k, v in step_result.measurements.items():
                    measurements[k] = np.array(v, dtype=bool)
            if step_result:
                final_state = step_result.state()
            else:
                # Empty circuit, so final state should be initial state.
                num_qubits = len(qubit_order.order_for(circuit.all_qubits()))
                final_state = xmon_stepper.decode_initial_state(initial_state,
                                                                num_qubits)
            trial_results.append(XmonSimulateTrialResult(
                params=param_resolver,
                measurements=measurements,
                final_state=final_state))
        return trial_results