<jupyter_start><jupyter_text>HoloPy demo: spin-chainXXZ: $$H_\text{XXZ}=\sum_{i=1}^{L-1} \sigma^x_{i}\sigma^x_{i+1}+\sigma^y_{i}\sigma^y_{i+1} + \Delta \sigma^z_i\sigma^z_{i+1}$$Ising: $$H_\text{TFIM}=\sum_i -J\sigma^x_i\sigma^x_{i+1}-h\sigma^x_{i}$$<jupyter_code># ansatz parameters
nb = 2 # number of bond-qubits 
L = 1 # number of unit cells
l_uc = 1 # number of sites in unit cell
## Setup IsoMPS ##
# initialize registers
preg = qk.QuantumRegister(1,'p') # physical qubits
breg = qk.QuantumRegister(nb,'b') # bond qubits
creg = qk.ClassicalRegister(L*l_uc+nb,'m') # classical register to hold measurement outcomes

## Initialize parameterized circuits
# bond-prep circuit (sets left-boundary vector of MPS)
bond_prep_circ = QKParamCircuit(qk.QuantumCircuit(breg),[])
pcircs = [bond_prep_circ]

# circuits that generate tensors
param_names= [] # list of circuit parameters
for j in range(l_uc):
    circ_tmp,params_tmp = circuits.star_circ(preg,
                                             breg,
                                             label='[c{}]'.format(j),
                                             circ_type='xxz') 
    pcircs+=[circ_tmp]
    param_names+=params_tmp

# setup circuit-generated isoMPS
psi = IsoMPS(preg,breg,pcircs,L=L)
## Example (resolve parameters => random values and print circuit)
# pick some random parameter values
param_vals = [4*np.pi*np.random.rand() for j in range(len(param_names))]
param_dict = dict(zip(param_names,param_vals))
psi.construct_circuit(param_dict,include_measurements=False)
psi.circ.draw('mpl')<jupyter_output><empty_output><jupyter_text>1. Compute energy by exporting to tenpy<jupyter_code>## Functions to create tenpy models
def ising_impo(J, h):
    site = tp.networks.site.SpinHalfSite(conserve=None)
    #Id, Sp, Sm, Sz = site.Id, site.Sp, site.Sm, 2*site.Sz
    #Sx = Sp + Sm
    Id, Sx, Sz = site.Id, site.Sigmax, site.Sigmaz
    W = [[Id,Sx,-h*Sz], 
         [None,None,-J*Sx], 
         [None,None,Id]]
    H = tp.networks.mpo.MPO.from_grids([site], [W], bc='infinite', IdL=0, IdR=-1)
    return H

def xxz_impo(Delta):
    """
    Doesn't work! (leg-charge error?)
    """
    site = tp.networks.site.SpinHalfSite(conserve=None)
    Id, Sp, Sm, Sz = site.Id, site.Sp, site.Sm, site.Sigmaz
    Sx = Sp + Sm
    W = [[Id,Sp,Sm,Sz], 
         [None,None,None,1/2*Sm],
         [None,None,None,1/2*Sp],
         [None,None,None,Delta*Sz],
         [None,None,None,Id]]
    H = tp.networks.mpo.MPO.from_grids([site], [W], bc='infinite', IdL=0, IdR=-1)
    return H

# energy calculator
def energy_tp(param_vals,*args):
    """
    function to calculate energy using MPO/MPS contraction in tenpy
    inputs:
        - param_vals = dict {parameter:value}
        - *args, 
            args[0] should be psi: state as IsoMPS
            args[1] should be H_mpo: Hamiltonian as MPO
        (input made this way to be compatible w/ scipy.optimize)
    outputs:
        - float, <psi|H|psi> computed w/ tenpy
    """
    # parse inputs
    psi=args[0] # state as isoMPS    
    H_mpo = args[1] # Hamiltonian as tenpy MPO
    param_dict = dict(zip(param_names,param_vals))
    
    # convert state from holoPy isoMPS to tenpy MPS
    psi_tp = psi.to_tenpy(param_dict,L=np.inf)
    
    # compute energy
    E = (H_mpo.expectation_value(psi_tp)).real
    return E
## define model ##
J_xx = 1
h_z = 1
H_mpo = ising_impo(J=1,h=1) # Hamiltonian as tenpy MPO

# optimize ansatz using tenpy
x0 = 0.03*np.random.randn(len(param_names)) # starting point for parameters
t0 = time.time()
opt_result = minimize(energy_tp, # function to minimize
                      x0, # starting point for parameters 
                      args=(psi,H_mpo), # must take form (isoMPS,tenpy MPO)
                      method='BFGS'
                     )
tf = time.time()
# set parameters to previously optimized values
opt_vals = opt_result.x
opt_params = dict(zip(param_names,opt_vals))

print('Optimization done, elapsed time: {}'.format(tf-t0))
print('Optimized energy = {}'.format(opt_result.fun))<jupyter_output>Optimization done, elapsed time: 44.94563698768616
Optimized energy = -1.2699400603424678<jupyter_text>2. Qiskit simulationsNow, compute the energy for the optimized parameter values in qiskit<jupyter_code>## Specify hyperparameters ##
L=10 # length of chain to simulate
measurement_strings = [['z']*L,['x']*L] # list of Pauli strings to measure
shots = 100

# file saving info
subdir = 'test_data' # subfolder to hold data
filename = 'tfimjobs_hz{}.dat'.format(h_z) # file name for saved data

# Create meta-data
model_data = {'model':'tfim',
             'model_params':{'J_xx':J_xx,'h_z':h_z},
             'L':L,
             'shots':shots,
             }
vqe_data = {'architecture':'su4_star',
                'nb':nb,
                'params':opt_params}
## Create jobs ##
# loop through measurement strings, and create list of jobs to run
jobs = []
for m in measurement_strings:
    psi_curr = IsoMPS(preg,breg,pcircs,bases=m,L=L)
    circ_curr = psi_curr.construct_circuit(opt_params)
    jobs += [{'name':'tfim_su4star_hz{}'.format(h_z)+'_basis_'+m[0],
              'isoMPS':psi_curr,
              'vqe_data':vqe_data,
              'qiskit_circuit':circ_curr,
              'qasm':circ_curr.qasm(),
              'model':model_data,
              'basis':m,
              'job_id':None, # job-id when submitted to honeywell
              'results':None
              }]

# save jobs dict to pickle file
file = open(subdir+'/' + filename, 'ab') 
pickle.dump(jobs, file)                      
file.close() 
## Run Jobs (qiskit version) ##
# load job files
file = open(subdir+'/' + filename, 'rb') 
jobs = pickle.load(file)
file.close() 

# setup qiskit simulator
simulator = qk.providers.aer.QasmSimulator()
for job in jobs:
    job['result'] = execute(job['circuit'], simulator, shots=shots, memory=True).result()
    
## Retrieve Results ##
## Post-process results ##
## Plot results ##
['z']*8<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1377525463349474, 'fraction_numerical': 0.01319084989146769, 'mean_word_length': 3.0887372013651877, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '465451', 'license': 'MIT', 'n_tokens_mistral': 2194, 'n_tokens_neox': 2087, 'n_words': 477, 'path': '.ipynb_checkpoints/holoVQE_demo_XXZ-checkpoint.ipynb', 'repo_name': 'andrewcpotter/holopy', 'size': '5989'}