#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Baidu, Inc. 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.

"""
This example demonstrates how to use the Gate Error Mitigation method to
improve the accuracy of the outcomes generated by a noisy quantum computer.
"""
import numpy as np
import functools
import copy
from qiskit.providers.fake_provider import FakeSantiago

from QCompute import *
from qcompute_qep.mitigation import ZNEMitigator
from qcompute_qep.utils import expval_from_counts
from qcompute_qep.utils.types import QProgram, QComputer
from qcompute_qep.utils.circuit import execute

# Set the default number of shots
NUMBER_OF_SHOTS = 4096


def calculator(qp: QProgram = None, qc: QComputer = None) -> float:
    """
    Run the quantum program on the quantum computer and estimate the expectation value.
    This function must be specified by the user.

    :param qp: QProgram, describes the quantum program
    :param qc: QComputer, specifies the quantum computer
    :return: the evaluated expectation value
    """
    # Run the quantum program on the quantum computer and obtain the measurement outcomes
    counts = execute(qp, qc, shots=NUMBER_OF_SHOTS)
    # Compute the expectation value from counts w.r.t. to the observable
    # :math:`|0\cdots 0><0\cdots 0| + |1\cdots 1><1\cdots 1|`
    proj0 = np.array([[1, 0], [0, 0]]).astype(complex)
    proj1 = np.array([[0, 0], [0, 1]]).astype(complex)
    A = functools.reduce(np.kron, [proj0] * n) + functools.reduce(np.kron, [proj1] * n)

    return expval_from_counts(A, counts)


##########################################################################################
# Setup the quantum program for estimating the expectation value of GHZ state
##########################################################################################
qp = QEnv()
n = 4
qp.Q.createList(n)
H(qp.Q[0])
for i in range(1, n):
    CX(qp.Q[0], qp.Q[i])
MeasureZ(*qp.Q.toListPair())

##########################################################################################
# Set the quantum hardware for estimating the expectation value of GHZ state
##########################################################################################
# For numeric test on the ideal simulator, change qc to BackendName.LocalBaiduSim2
qc_ideal = BackendName.LocalBaiduSim2

# For experiment on the real quantum device, change qc to BackendName.CloudBaiduQPUQian
# You must set your VIP token first in order to access the Baidu hardware.
# Define.hubToken = "Token"
# qc_noisy = BackendName.CloudBaiduQPUQian

# For numeric test on the noisy simulator, change qc to Qiskit's FakeSantiago simulator
qc_noisy = FakeSantiago()

##########################################################################################
# Compute the ideal and noisy expectation values.
##########################################################################################
val_ideal = calculator(copy.deepcopy(qp), qc=qc_ideal)
val_noisy = calculator(copy.deepcopy(qp), qc=qc_noisy)

# Initialize a ZNEMitigator instance to mitigate the expectation values
# You can change the `folder` and `extrapolator` parameters to obtain better results.
zne = ZNEMitigator(folder='circuit', extrapolator='richardson')
val_miti = zne.mitigate(copy.deepcopy(qp), qc_noisy, calculator, scale_factors=[1, 3, 5, 7, 9])

print("The ideal expectation value is: {}".format(val_ideal))
print("The noisy expectation value is: {}".format(val_noisy))
print("The mitigated expectation value is: {}".format(val_miti))
