<jupyter_start><jupyter_text>Protein Folding Problem  content[i.ProteinFoldingProblem function](i.ProteinFoldingProblemfunction)&nbsp; [1.ProteinDefining](1.ProteinDefining)&nbsp; [2.InteractionMethod](2.InteractionMethod)&nbsp; [3.PenaltyTerms](3.PenaltyTerms)[ii.ConvertToQubits](ii.ConvertToQubits)[iii.VQE](iii.VQE)&nbsp; [1.ansatz](1.ansatz)&nbsp; [2.optimizer](2.optimizer)&nbsp; [3.backend](3.backend)&nbsp; [4.expectation](4.expectation)[iv.AnalysingTheResults](iv.AnalysingTheResults)   i.ProteinFoldingProblemfunction  1.ProteinDefining<jupyter_code># To simplify the problem, we only consider the main chain and omit the side chain 
main_chain = "APRLRFY" # 7 amino acids
def validate_main_chain(main_chain: str):
    for amino_acid in main_chain:
        if validate_amino_acid(amino_acid) == False:
            return False
    return True

def validate_amino_acid(amino_acid: str) -> bool:
    valid_amino_acids = [
        "A",  # Alanine
        "C",  # Cysteine
        "D",  # Aspartic acid
        "E",  # Glutamic acid
        "F",  # Phenylalanine
        "G",  # Glycine
        "H",  # Histidine
        "I",  # Isoleucine
        "K",  # Lysine
        "L",  # Leucine
        "M",  # Methionine
        "N",  # Asparagine
        "P",  # Proline
        "Q",  # Glutamine
        "R",  # Arginine
        "S",  # Serine
        "T",  # Threonine
        "V",  # Valine
        "W",  # Tryptophan
        "Y",  # Tyrosine
    ]
    if amino_acid != "" and amino_acid not in valid_amino_acids:
        return False
    return True
validate_main_chain(main_chain)<jupyter_output><empty_output><jupyter_text>2.InteractionMethod<jupyter_code>from pathlib import Path
import os
import numpy as np
from typing import Tuple, List

def path_of_mj():
    path1 = Path().parent.absolute()
    path2 = Path("resources")
    path1 = os.path.join(path1, path2)
    filename = "mj_matrix.txt"
    path = os.path.normpath(os.path.join(path1, filename))
    return path

def load_mj_matrix() -> Tuple[np.ndarray, List[str]]:
    path = path_of_mj()
    matrix = np.loadtxt(fname=path, dtype=str)
    mj_matrix = np.zeros((np.shape(matrix)[0], np.shape(matrix)[1]))
    for row in range(1, np.shape(matrix)[0]):
        for col in range(row - 1, np.shape(matrix)[1]):
            mj_matrix[row, col] = float(matrix[row, col])
    mj_matrix = mj_matrix[1:,]
    amino_acids = list(matrix[0, :])
    return mj_matrix, amino_acids

def calculate_energy_matrix(main_chain: str) -> np.ndarray:
        chain_len = len(main_chain)
        if(validate_main_chain(main_chain) == False):
            print("The wrong string of amino acids.")
            return
        mj_matrix, list_amino_acids = load_mj_matrix() 
        energy_matrix = np.zeros((chain_len, chain_len)) 
        for i in range(chain_len):
            for j in range(i + 1, chain_len):
                aa_i = list_amino_acids.index(main_chain[i])
                aa_j = list_amino_acids.index(main_chain[j])
                energy_matrix[i, j] = mj_matrix[min(aa_i, aa_j), max(aa_i, aa_j)] 
        return energy_matrix
### MJ interaction table
mj, amino_acids = load_mj_matrix()
print(amino_acids)
print(mj)
### Calculating energy for the special peptide
miyazawa_jernigan=calculate_energy_matrix(main_chain)
print(miyazawa_jernigan)<jupyter_output>[[ 0.   -2.03 -1.83 -4.91 -1.83 -4.81 -3.36]
 [ 0.    0.   -1.7  -4.2  -1.7  -4.25 -3.19]
 [ 0.    0.    0.   -4.03 -1.55 -3.98 -3.16]
 [ 0.    0.    0.    0.   -4.03 -7.28 -5.67]
 [ 0.    0.    0.    0.    0.   -3.98 -3.16]
 [ 0.    0.    0.    0.    0.    0.   -5.66]
 [ 0.    0.    0.    0.    0.    0.    0.  ]]<jupyter_text>3.PenaltyTerms<jupyter_code>penalty_chiral = 10.0 #float
penalty_back   = 10.0 #float
penalty_1      = 10.0 #float

penalty_terms = (penalty_chiral, penalty_back, penalty_1) # tuple<jupyter_output><empty_output><jupyter_text>ii.ConvertToQubits<jupyter_code>from qiskit_nature.problems.sampling.protein_folding.protein_folding_problem import ProteinFoldingProblem

### using ProteinFoldingProblem Function
protein_folding_1 = ProteinFoldingProblem(main_chain, miyazawa_jernigan, penalty_terms)
qubit_operations_1 = protein_folding_1.qubit_op()

###
#print(qubit_operations_1)
print(qubit_operations_1[0:5])<jupyter_output><empty_output><jupyter_text>iii.VQE  1.ansatz<jupyter_code>from qiskit.circuit import Parameter, ParameterVector, QuantumCircuit, QuantumRegister, ClassicalRegister

def RealAmplitudes_m(
    num_qubits=1,
    entanglement='full',
    reps=3,
    #skip_unentangled_qubits=False,
    skip_final_rotation_layer=False,
    #parameter_prefix='θ',
    insert_barriers=False,
    initial_state=None,
    name='RealAmplitudes'
) -> QuantumCircuit:
    
    parameters = ParameterVector('θ', 2*num_qubits)
    q =  QuantumRegister(num_qubits)
    qc = QuantumCircuit(q)
    angle=0
    for k in range(reps):
        for i in range(num_qubits):
            qc.ry(parameters[angle],q[i])
            angle =angle+1
        if(insert_barriers):
            qc.barrier()
        if(entanglement=='linear'):
            for i in range(num_qubits-1):
                qc.cx(q[i],q[i+1])
        elif(entanglement=='full'):
            for i in range(num_qubits-1):
                for j in range(i+1,num_qubits):
                    qc.cx(q[i],q[j])
        if(insert_barriers):
            qc.barrier()
    if(skip_final_rotation_layer==False):
        for i in range(num_qubits):
            qc.ry(parameters[angle],q[i])
            angle =angle+1
    return qc
circuit = RealAmplitudes_m(9, reps=1, insert_barriers=True)
circuit.draw(output='mpl')<jupyter_output><empty_output><jupyter_text>2.optimizer<jupyter_code>### ???
from qiskit.algorithms.optimizers import COBYLA
### 2. optimizer
optimizer = COBYLA(maxiter=50)<jupyter_output><empty_output><jupyter_text>3.backend<jupyter_code>from qiskit.utils import QuantumInstance
from qiskit import execute, Aer
### 3. backend
backend = "aer_simulator"
backend = QuantumInstance(
    Aer.get_backend(backend),
    shots=1000,
)

### callback function
counts = []
values = []

def callback_function(eval_count, parameters, mean, std):
    counts.append(eval_count)
    values.append(mean)<jupyter_output><empty_output><jupyter_text>4.expectation<jupyter_code>from qiskit.opflow import PauliExpectation, CVaRExpectation
### expectation
cvar_exp = CVaRExpectation(0.1, PauliExpectation())

### ???
from qiskit.algorithms import VQE
### VQE using CVaR
vqe = VQE(
    expectation=cvar_exp,
    optimizer=optimizer,
    ansatz=ansatz,
    quantum_instance=backend,
    callback=callback_function,
)
### ???<jupyter_output><empty_output><jupyter_text>iv.AnalysingTheResults<jupyter_code>result = vqe.compute_minimum_eigenvalue(qubit_operations_1)
print(result)<jupyter_output><empty_output><jupyter_text>Plot the results<jupyter_code>import matplotlib.pyplot as plt

figure = plt.figure()

plt.plot(counts, values)
plt.ylabel("Conformation Energy")
plt.xlabel("VQE Iterations")

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12642531356898518, 'fraction_numerical': 0.023660205245153935, 'mean_word_length': 3.4665817950350095, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 44, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '325791', 'license': 'MIT', 'n_tokens_mistral': 2735, 'n_tokens_neox': 2544, 'n_words': 455, 'path': 'ProteinFolding_3.ipynb', 'repo_name': 'yadavar-m/Protein_Folding', 'size': '7016'}