<jupyter_start><jupyter_text>Histogram<jupyter_code>from quchem_ibm.exp_analysis import *
def dict_of_M_to_list(M_dict, PauliOP):
    
    P_Qubit_list, _ = zip(*(list(*PauliOP.terms.keys())))
    
    list_of_M_bitstrings=None
    for bit_string, N_obtained in M_dict.items():
        
        M_string = np.take(list(bit_string[::-1]), P_Qubit_list) # only take terms measured! Note bitstring reversed!
        
        array_meas = np.repeat(''.join(M_string), N_obtained)
        if list_of_M_bitstrings is None:
            list_of_M_bitstrings=array_meas
        else:
            list_of_M_bitstrings=np.hstack((list_of_M_bitstrings,array_meas))
    
    # randomly shuffle (seed means outcome will always be the SAME!)
    np.random.seed(42) 
    np.random.shuffle(list_of_M_bitstrings) 
    
    return list_of_M_bitstrings
list(LiH_data.keys())
# LCU_Hist_data_sim={}
    
# for exp_instance in LiH_data['experiment_data'][101852100]['LCU']: #each exp repeated 10 times!
#     for exp_dict_key in exp_instance:

#         exp_dict= exp_instance[exp_dict_key]

#         if 'Pn' in exp_dict.keys():
#             P=exp_dict['Pn']
#             coeff = exp_dict['gamma_l']

#             measured_dict_sim = exp_dict['measurement_dict'] # post selection already done!

#         else:
#             P=exp_dict['qubitOp']
#             coeff = exp_dict['coeff']
#             measured_dict_sim = exp_dict['measurement_dict']

#         M_list_sim = dict_of_M_to_list(measured_dict_sim, P)

#         if exp_dict_key in LCU_Hist_data_sim.keys():
#             LCU_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': np.hstack((LCU_Hist_data_sim[exp_dict_key]['Measurements'],M_list_sim))}
#         else:
#             LCU_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': M_list_sim}

                
# # as probablistic need to all be same shape (cannot have more measurements of one term)
# fewest_succ_shots_sim = min([LCU_Hist_data_sim[key]['Measurements'].shape[0] for key in LCU_Hist_data_sim])
# # for exp_dict_key in exp_instance:
# #     exp_dict= exp_instance[exp_dict_key]
# #     if 'Pn' in exp_dict.keys():
# #         LCU_Hist_data_sim[exp_dict_key]['Measurements']= LCU_Hist_data_sim[exp_dict_key]['Measurements'][:fewest_succ_shots_sim]
# for key in LCU_Hist_data_sim.keys():
#     LCU_Hist_data_sim[key]['Measurements']= LCU_Hist_data_sim[key]['Measurements'][:fewest_succ_shots_sim]
    
# LCU_Hist_data_sim[0]['Measurements'].shape
LCU_Hist_data_sim={}
for shot_key in list(LiH_data['experiment_data'].keys())[:3]: # <-- currently limiting
    
    for exp_instance in LiH_data['experiment_data'][shot_key]['LCU']: #each exp repeated 10 times!
        for exp_dict_key in exp_instance:

            exp_dict= exp_instance[exp_dict_key]

            if 'Pn' in exp_dict.keys():
                P=exp_dict['Pn']
                coeff = exp_dict['gamma_l']

                measured_dict_sim = exp_dict['measurement_dict'] # post selection already done!

            else:
                P=exp_dict['qubitOp']
                coeff = exp_dict['coeff']
                measured_dict_sim = exp_dict['measurement_dict']

            M_list_sim = dict_of_M_to_list(measured_dict_sim, P)

            if exp_dict_key in LCU_Hist_data_sim.keys():
                LCU_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': np.hstack((LCU_Hist_data_sim[exp_dict_key]['Measurements'],M_list_sim))}
            else:
                LCU_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': M_list_sim}

                
# as probablistic need to all be same shape (cannot have more measurements of one term)
fewest_succ_shots_sim = min([LCU_Hist_data_sim[key]['Measurements'].shape[0] for key in LCU_Hist_data_sim])
# for exp_dict_key in exp_instance:
#     exp_dict= exp_instance[exp_dict_key]
#     if 'Pn' in exp_dict.keys():
#         LCU_Hist_data_sim[exp_dict_key]['Measurements']= LCU_Hist_data_sim[exp_dict_key]['Measurements'][:fewest_succ_shots_sim]
for key in LCU_Hist_data_sim.keys():
    LCU_Hist_data_sim[key]['Measurements']= LCU_Hist_data_sim[key]['Measurements'][:fewest_succ_shots_sim]
    
LCU_Hist_data_sim[0]['Measurements'].shape
SEQ_ROT_Hist_data_sim={}
for shot_key in list(LiH_data['experiment_data'].keys())[:3]: # <-- currently limiting
    
    for exp_instance in LiH_data['experiment_data'][shot_key]['seq_rot']: #each exp repeated 10 times!
        for exp_dict_key in exp_instance:

            exp_dict= exp_instance[exp_dict_key]

            if 'Ps' in exp_dict.keys():
                P=exp_dict['Ps']
                coeff = exp_dict['gamma_l']

                measured_dict_sim = exp_dict['measurement_dict']

            else:
                P=exp_dict['qubitOp']
                coeff = exp_dict['coeff']
                measured_dict_sim = exp_dict['measurement_dict']

            M_list_sim = dict_of_M_to_list(measured_dict_sim, P)

            if exp_dict_key in SEQ_ROT_Hist_data_sim.keys():
                SEQ_ROT_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': np.hstack((SEQ_ROT_Hist_data_sim[exp_dict_key]['Measurements'],M_list_sim))}
            else:
                SEQ_ROT_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': M_list_sim}

SEQ_ROT_Hist_data_sim[0]['Measurements'].shape
STANDARD_Hist_data_sim={}
for shot_key in list(LiH_data['experiment_data'].keys())[:3]: # <-- currently limiting
    
    for exp_instance in LiH_data['experiment_data'][shot_key]['standard']: #each exp repeated 10 times!
        for exp_dict_key in exp_instance:

            P=exp_dict['qubitOp']
            coeff = exp_dict['coeff']
            measured_dict_sim = exp_dict['measurement_dict']

            M_list_sim = dict_of_M_to_list(measured_dict_sim, P)

            if exp_dict_key in STANDARD_Hist_data_sim.keys():
                STANDARD_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': np.hstack((STANDARD_Hist_data_sim[exp_dict_key]['Measurements'],M_list_sim))}
            else:
                STANDARD_Hist_data_sim[exp_dict_key]={'P':P ,'coeff': coeff, 'Measurements': M_list_sim}

STANDARD_Hist_data_sim[0]['Measurements'].shape[0]
from tqdm.notebook import tqdm
def Get_Hist_data(Histogram_data, I_term):
    E_list=[]
    for m_index in tqdm(range(Histogram_data[0]['Measurements'].shape[0])):
        E=I_term
        for M_dict_key in Histogram_data:
            coeff = Histogram_data[M_dict_key]['coeff']
            parity =  1 if sum(map(int, Histogram_data[M_dict_key]['Measurements'][m_index])) % 2 == 0 else -1
            E+=coeff*parity
        E_list.append(E)
    return E_list
    
I_term = -4.142299396835105

E_LCU_list_sim=Get_Hist_data(LCU_Hist_data_sim, I_term)
E_list_SEQ_ROT_sim=Get_Hist_data(SEQ_ROT_Hist_data_sim, I_term)
E_list_STANDARD_sim=Get_Hist_data(STANDARD_Hist_data_sim, I_term)
del LiH_data
E_LCU_list_sim=np.array(E_LCU_list_sim)
E_list_SEQ_ROT_sim=np.array(E_list_SEQ_ROT_sim)
E_list_STANDARD_sim=np.array(E_list_STANDARD_sim)
def gaussian(x, mean, amplitude, standard_deviation):
    return amplitude * np.exp( - ((x - mean) / standard_deviation) ** 2)
from scipy.optimize import curve_fit
from matplotlib import pyplot
%matplotlib inline


# bins = len(set(E_list_SEQ_ROT_sim))
# bins_standard = len(set(E_list_STANDARD_sim))

bins = 100
bins_standard = 100

bin_heights_STANDARD, bin_borders_STANDARD, _=pyplot.hist(E_list_STANDARD_sim,
                                                          bins_standard, alpha=0.7,
                                                          label='$E$ standard VQE - sim',
                                                          color='g',
                                                          density=False)

# bin_centers_STANDARD = bin_borders_STANDARD[:-1] + np.diff(bin_borders_STANDARD) / 2
# popt, _ = curve_fit(gaussian, bin_centers_STANDARD, bin_heights_STANDARD, p0=[1., 0., 1.], **{'maxfev':10000})
# mean_STANDARD, amplitude_STANDARD, standard_deviation_STANDARD= popt
# x_interval_for_fit = np.linspace(bin_borders_STANDARD[0], bin_borders_STANDARD[-1], 10000)
# pyplot.plot(x_interval_for_fit, gaussian(x_interval_for_fit, *popt), label='Gaussian fit', color='g')


# # pyplot.axvline(mean_STANDARD, color='g', linestyle='dashed', linewidth=1, 
# #             label='$E_{average}$ standard VQE - sim') # mean of GAUSSIAN FIT

# pyplot.axvline(E_list_STANDARD_sim.mean(), color='g', linestyle='dashed', linewidth=1, 
#             label='$E_{average}$ standard VQE - sim') # mean of DATA

# pyplot.errorbar(mean_STANDARD,500_000,
#              xerr=standard_deviation_STANDARD, linestyle="None", color='g',
#              uplims=True, lolims=True, label='$\sigma_{E_{av}}$standard VQE - sim')




bin_heights_SEQ_ROT_sim, bin_borders_SEQ_ROT_sim, _=pyplot.hist(E_list_SEQ_ROT_sim, 
                                                                bins, alpha=0.7, 
                                                                label='$E_{average}$ seq rot VQE - sim', 
                                                                color='b',
                                                              density=False)

# bin_centers_SEQ_ROT_sim = bin_borders_SEQ_ROT_sim[:-1] + np.diff(bin_borders_SEQ_ROT_sim) / 2
# popt, _ = curve_fit(gaussian, bin_centers_SEQ_ROT_sim, bin_heights_SEQ_ROT_sim, p0=[1., 0, 1], **{'maxfev':10000})
# mean_SEQ_ROT_sim, amplitude_SEQ_ROT_sim, standard_deviation_SEQ_ROT_sim= popt
# # x_interval_for_fit = np.linspace(bin_borders_SEQ_ROT_sim[0], bin_borders_SEQ_ROT_sim[-1], 10000)
# pyplot.plot(x_interval_for_fit, gaussian(x_interval_for_fit, *popt), label='Gaussian fit', color='b')


# # pyplot.axvline(mean_SEQ_ROT_sim, color='b', linestyle='dashdot', linewidth=1, 
# #             label='$E_{average}$ seq rot VQE - sim') # mean of GAUSSIAN FIT

# pyplot.axvline(E_list_SEQ_ROT_sim.mean(), color='b', linestyle='dashdot', linewidth=1, 
#             label='$E_{average}$ seq rot VQE - sim') # mean of DATA

# pyplot.errorbar(mean_SEQ_ROT_sim,510_000,
#              xerr=standard_deviation_SEQ_ROT_sim, linestyle="None", color='b',
#              uplims=True, lolims=True, label='$\sigma_{E_{av}}$ seq rot - sim')



bin_heights_LCU_sim, bin_borders_LCU_sim, _=pyplot.hist(E_LCU_list_sim, bins, alpha=0.7, 
                                                                label='$E$ LCU - sim', 
                                                                color='r',
                                                              density=False)

# bin_centers_LCU_sim = bin_borders_LCU_sim[:-1] + np.diff(bin_borders_LCU_sim) / 2
# popt, _ = curve_fit(gaussian, bin_centers_LCU_sim, bin_heights_LCU_sim, p0=[1., 0., 1.], **{'maxfev':10000})
# mean_LCU_sim, amplitude_LCU_sim, standard_deviation_LCU_sim= popt
# # x_interval_for_fit = np.linspace(bin_borders_LCU_sim[0], bin_borders_LCU_sim[-1], 10000)
# pyplot.plot(x_interval_for_fit, gaussian(x_interval_for_fit, *popt), label='Gaussian fit', color='r')

# # pyplot.axvline(mean_LCU_sim, alpha=0.5, color='r', linestyle='dashed', linewidth=1, 
# #             label='$E_{average}$ LCU - sim') # mean of GAUSSIAN FIT
# pyplot.axvline(E_LCU_list_sim.mean(), alpha=0.5, color='r', linestyle='dashed', linewidth=1, 
#             label='$E_{average}$ LCU - sim') # mean of DATA

# pyplot.errorbar(mean_LCU_sim,520_000,
#              xerr=standard_deviation_LCU_sim, linestyle="None", color='r',
#              uplims=True, lolims=True, label='$\sigma_{E_{av}}$ LCU - sim')

pyplot.axvline(fci_energy, color='k', linestyle='solid', linewidth=2, 
            label='$E_{FCI}$', alpha=0.4)

pyplot.legend(loc='upper right')
# pyplot.legend(bbox_to_anchor=(0.865,1.9), loc="upper left")
pyplot.ylabel('Frequency')
pyplot.xlabel('Energy')

pyplot.tight_layout()

file_name = 'LiH_Histogram_sim_Gaussian.jpeg'
pyplot.savefig(file_name, dpi=300,transparent=True,) # edgecolor='black', facecolor='white')
pyplot.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12396075823079482, 'fraction_numerical': 0.01321915530428999, 'mean_word_length': 3.2221832221832223, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '631588', 'license': 'MIT', 'n_tokens_mistral': 4480, 'n_tokens_neox': 4258, 'n_words': 649, 'path': 'old_projects/quchem_ibm/Experiments/LiH_Simulation_result/LiH_Analysis.ipynb', 'repo_name': 'AlexisRalli/VQE-code', 'size': '12028'}