1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright © 2021 HQS Quantum Simulations GmbH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;

use crate::backends::{EvaluatingBackend, RegisterResult};
use crate::measurements;
use crate::measurements::Measure;
use crate::RoqoqoBackendError;
use std::fmt::{Display, Formatter};
/// Represents a quantum program evaluating measurements based on a one or more free float parameters.
///
/// The main use of QuantumProgram is to contain a Measurements implementing [crate::measurements::Measure]
/// that measures expectation values or output registers of [crate::Circuit] quantum circuits that contain
/// symbolic parameters. Circuit with symbolic parameters can not be simulated or executed on real hardware.
/// The symbolic parameters need to be replaced with real floating point numbers first.
/// A QuantumProgram contains a list of the free parameters (`input_parameter_names`) and can automatically
/// replace the parameters with its `run` methods and return the result.
///
/// The QuantumProgram should correspond as closely as possible to a normal mulit-parameter function
/// in classical computing that can be called with a set of parameters and returns a result.
/// It is the intended way to interface between normal program code and roqoqo based quantum programs.
///
#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub enum QuantumProgram {
    /// Variant for basis rotation measurement based quantum programs
    BasisRotation {
        /// The measurement that is performed
        measurement: measurements::BasisRotation,
        /// List of free input parameters that can be set when the QuantumProgram is executed
        input_parameter_names: Vec<String>,
    },
    /// Variant for cheated basis rotation measurement based quantum programs
    CheatedBasisRotation {
        /// The measurement that is performed
        measurement: measurements::CheatedBasisRotation,
        /// List of free input parameters that can be set when the QuantumProgram is executed
        input_parameter_names: Vec<String>,
    },
    /// Variant for statevector/density matrix based measurements
    Cheated {
        /// The measurement that is performed
        measurement: measurements::Cheated,
        /// List of free input parameters that can be set when the QuantumProgram is executed
        input_parameter_names: Vec<String>,
    },
    /// Variant quantum programs returning full classical registers
    ClassicalRegister {
        /// The measurement that is performed
        measurement: measurements::ClassicalRegister,
        /// List of free input parameters that can be set when the QuantumProgram is executed
        input_parameter_names: Vec<String>,
    },
}

impl QuantumProgram {
    /// Runs the QuantumProgram and returns expectation values.
    ///
    /// Runs the quantum programm for a given set of parameters passed in the same order as the parameters
    /// listed in `input_parameter_names` and returns expectation values.
    ///
    /// Arguments:
    ///
    /// * `backend` - The backend the program is executed on.
    /// * `parameters` - List of float ([f64]) parameters of the function call in order of `input_parameter_names`
    pub fn run<T>(
        &self,
        backend: T,
        parameters: &[f64],
    ) -> Result<Option<HashMap<String, f64>>, RoqoqoBackendError>
    where
        T: EvaluatingBackend,
    {
        match self{
            QuantumProgram::BasisRotation{measurement, input_parameter_names } => {
                if parameters.len() != input_parameter_names.len() { return Err(RoqoqoBackendError::GenericError{msg: format!("Wrong number of parameters {} parameters expected {} parameters given", input_parameter_names.len(), parameters.len())})};
                let substituted_parameters: HashMap<String, f64> = input_parameter_names.iter().zip(parameters.iter()).map(|(key, value)| (key.clone(), *value)).collect();
                let substituted_measurement = measurement.substitute_parameters(
                    substituted_parameters
                )?;
                backend.run_measurement(&substituted_measurement)
            }
            QuantumProgram::CheatedBasisRotation{measurement, input_parameter_names } => {
                if parameters.len() != input_parameter_names.len() { return Err(RoqoqoBackendError::GenericError{msg: format!("Wrong number of parameters {} parameters expected {} parameters given", input_parameter_names.len(), parameters.len())})};
                let substituted_parameters: HashMap<String, f64> = input_parameter_names.iter().zip(parameters.iter()).map(|(key, value)| (key.clone(), *value)).collect();
                let substituted_measurement = measurement.substitute_parameters(
                    substituted_parameters
                )?;
                backend.run_measurement(&substituted_measurement)
            }
            QuantumProgram::Cheated{measurement, input_parameter_names } => {
                if parameters.len() != input_parameter_names.len() { return Err(RoqoqoBackendError::GenericError{msg: format!("Wrong number of parameters {} parameters expected {} parameters given", input_parameter_names.len(), parameters.len())})};
                let substituted_parameters: HashMap<String, f64> = input_parameter_names.iter().zip(parameters.iter()).map(|(key, value)| (key.clone(), *value)).collect();
                let substituted_measurement = measurement.substitute_parameters(
                    substituted_parameters
                )?;
                backend.run_measurement(&substituted_measurement)
            }
            _ => Err(RoqoqoBackendError::GenericError{msg: "A quantum programm returning classical registeres cannot be executed by `run` use `run_registers` instead".to_string()})
        }
    }

    /// Runs the QuantumProgram and returns the classical registers of the quantum program.
    ///
    /// Runs the quantum programm for a given set of parameters passed in the same order as the parameters
    /// listed in `input_parameter_names` and returns the classical register output.  
    /// The classical registers usually contain a record of measurement values for the repeated execution
    /// of a [crate::Circuit] quantum circuit for real quantum hardware
    /// or the readout of the statevector or the density matrix for simulators.
    ///
    /// Arguments:
    ///
    /// * `backend` - The backend the program is executed on.
    /// * `parameters` - List of float ([f64]) parameters of the function call in order of `input_parameter_names`
    pub fn run_registers<T>(&self, backend: T, parameters: &[f64]) -> RegisterResult
    where
        T: EvaluatingBackend,
    {
        match self{
            QuantumProgram::ClassicalRegister{measurement, input_parameter_names } => {
                if parameters.len() != input_parameter_names.len() { return Err(RoqoqoBackendError::GenericError{msg: format!("Wrong number of parameters {} parameters expected {} parameters given", input_parameter_names.len(), parameters.len())})};
                let substituted_parameters: HashMap<String, f64> = input_parameter_names.iter().zip(parameters.iter()).map(|(key, value)| (key.clone(), *value)).collect();
                let substituted_measurement = measurement.substitute_parameters(
                    substituted_parameters
                )?;
                backend.run_measurement_registers(&substituted_measurement)
            }
            _ => Err(RoqoqoBackendError::GenericError{msg: "A quantum programm returning expectation values cannot be executed by `run_registers` use `run` instead".to_string()})
        }
    }
}

/// Implements the Display trait for QuantumProgram.
impl Display for QuantumProgram {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut s: String = String::new();

        match self {
            QuantumProgram::BasisRotation { .. } => {
                s.push_str(&"QuantumProgram::BasisRotation".to_string());
            }
            QuantumProgram::CheatedBasisRotation { .. } => {
                s.push_str(&"QuantumProgram::CheatedBasisRotation".to_string());
            }
            QuantumProgram::Cheated { .. } => {
                s.push_str(&"QuantumProgram::Cheated".to_string());
            }
            QuantumProgram::ClassicalRegister { .. } => {
                s.push_str(&"QuantumProgram::ClassicalRegister".to_string());
            }
        }

        write!(f, "{}", s)
    }
}