<jupyter_start><jupyter_text>Prepare Qiskit Challenge 2021 --reference:* [qiskit introduction](https://qiskit.org/textbook/ch-states/atoms-computation.html)  Install qiskit, qiskit visualisation, qiskit textbook**Qiskit**:```pip install qiskit```**Visualisation**:```pip install qiskit[visualization]```**textbook**:```pip install git+https://github.com/qiskit-community/qiskit-textbook.gitsubdirectory=qiskit-textbook-src```  Create Qiskit Circuit and draw<jupyter_code># Create simple circuit and simple draw
from qiskit import QuantumCircuit, assemble, Aer
from qiskit.visualization import plot_histogram
qc_output = QuantumCircuit(8)
qc_output.measure_all()
qc_output.draw(initial_state=True)
sim = Aer.get_backend("aer_simulator")
result = sim.run(qc_output).result()
counts = result.get_counts()
plot_histogram(counts)
# create Circuit with classical bits
n_qbits = 2
n_cbits = 2
fst_qubit, fst_cbit = 0, 0
sec_qubit, sec_cbit  = 1, 1

qc = QuantumCircuit(n_qbits, n_cbits)
qc.x(fst_qubit)
qc.cx(fst_qubit, sec_qubit)
qc.measure(fst_qubit, fst_cbit)
qc.measure(sec_qubit, sec_cbit)
qc.draw()<jupyter_output><empty_output><jupyter_text>Qiskit Gates<jupyter_code># NOT gate
qc_mnot = QuantumCircuit(4, 2)
qc_mnot.x(0)
qc_mnot.barrier()
# CNOT gate
qc_mnot.cx(0, 1) # (control qubit, target qubit)
# CCNOT gate
qc_mnot.ccx(0, 1, 2) # (control qubit, control qubit, target qubit)
qc_mnot.barrier()
# measure
qc_mnot.measure(2, 0)
qc_mnot.measure(3, 1)
qc_mnot.draw()
# Pauli Gates Y, Z
from qiskit_textbook.widgets import gate_demo
gate_demo(gates='pauli')

# x-measurement
# Create the X-measurement function:
def x_measurement(qc, qubit, cbit):
    """Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
    qc.h(qubit)
    qc.measure(qubit, cbit)
    return qc

initial_state = [1/sqrt(2), -1/sqrt(2)]
# Initialize our qubit and measure it
qc_xm = QuantumCircuit(1,1)
qc_xm.initialize(initial_state, 0)
x_measurement(qc_xm, 0, 0)  # measure qubit 0 to classical bit 0
qc_xm.draw()
counts = sim.run(qc_xm).result().get_counts()
plot_histogram(counts)
# P-gate(Phase gate)
qc_g = QuantumCircuit(1)
qc_g.p(pi/4, 0)
qc_g.draw()
# I, S and T-gates
qc_g.s(0)
qc_g.sdg(0)
qc_g.t(0)
qc_g.tdg(0)
qc_g.draw()
# u gate
from qiskit.visualization import plot_bloch_multivector, plot_histogram

qc_u = QuantumCircuit(1)
qc_u.u(pi/2, 0, pi, 0)
qc_u.draw()
qc_u.save_statevector()
state = sim.run(qc_u).result().get_statevector()
plot_bloch_multivector(state)
# hadamard gate#
qc_h = QuantumCircuit(1)
qc_h.x(0)
qc_h.h(0)
qc_h.save_statevector()
state = sim.run(qc_h).result().get_statevector()
plot_bloch_multivector(state)

# sx gate (sqrt x gate: x = sx * sx)
qc_sx = QuantumCircuit(1)
qc_sx.sx(0)
qc_sx.save_statevector()
# show
state = sim.run(qc_sx).result().get_statevector()
plot_bloch_multivector(state)<jupyter_output>E:\anaconda\lib\site-packages\qiskit\visualization\bloch.py:69: MatplotlibDeprecationWarning: 
The M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.
  x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)<jupyter_text>[State Vector](https://qiskit.org/textbook/ch-states/representing-qubit-states.html)<jupyter_code>from qiskit import QuantumCircuit, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi

coeff1, coeff2 = 0, 1 # or
i_qubit = 0
# coeff1, coeff2 = 0 + 0j, 1 + 0j # j stands for indeterminate
qc_stv = QuantumCircuit(1)
initial_state = [coeff1, coeff2]
qc_stv.initialize(initial_state, i_qubit)
# save state vector for result
qc_stv.save_statevector()
rlt = sim.run(qc_stv).result()
# output state vector
out_state = rlt.get_statevector()
print("output state vector: ", out_state)
#output histogram
counts = rlt.get_counts()
print("output histogram:")
plot_histogram(counts)

# other initial state
initial_state = [1/sqrt(2), 1j/sqrt(2)]
qc_stv1 = QuantumCircuit(1)
qc_stv1.initialize(initial_state, 0)
qc_stv1.save_statevector()
# show
rlt = sim.run(qc_stv1).result()
print(rlt.get_statevector())
plot_histogram(rlt.get_counts())<jupyter_output>[0.5+0.5j 0.5-0.5j]<jupyter_text>Bloch vector<jupyter_code>from qiskit_textbook.widgets import plot_bloch_vector_spherical
coords = [pi/2, 0, 1] # [theta, phi, radius]
plot_bloch_vector_spherical(coords)
from qiskit_textbook.widgets import bloch_calc
bloch_calc()<jupyter_output>E:\anaconda\lib\site-packages\qiskit\visualization\bloch.py:397: MatplotlibDeprecationWarning: Axes3D(fig) adding itself to the figure is deprecated since 3.4. Pass the keyword argument auto_add_to_figure=False and use fig.add_axes(ax) to suppress this warning. The default value of auto_add_to_figure will change to False in mpl3.5 and True values will no longer work in 3.6.  This is consistent with other Axes classes.
  self.axes = Axes3D(self.fig, azim=self.view[0], elev=self.view[1])
E:\anaconda\lib\site-packages\qiskit\visualization\bloch.py:69: MatplotlibDeprecationWarning: 
The M attribute was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use self.axes.M instead.
  x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)<jupyter_text>[Finance + Quantum Computing](https://qiskit.org/documentation/tutorials/finance/index.html)  [Porfolio Optimization](https://qiskit.org/documentation/tutorials/finance/01_portfolio_optimization.html)<jupyter_code>from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.finance.applications.ising import portfolio
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.finance.data_providers import RandomDataProvider
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
import numpy as np
import matplotlib.pyplot as plt
import datetime
# The idea of hamiltonian is minimize the difference between risk and return values
num_assets = 4

# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(tickers=stocks,
                 start=datetime.datetime(2016,1,1),
                 end=datetime.datetime(2016,1,30))
data.run()
mu = data.get_period_return_mean_vector()
print(mu)
sigma = data.get_period_return_covariance_matrix()
print(sigma)
# plot sigma
plt.imshow(sigma, interpolation='nearest')
plt.show()
q = 0.5                   # set risk factor
budget = num_assets // 2  # set budget
penalty = num_assets      # set parameter to scale the budget penalty term

qubitOp, offset = portfolio.get_operator(mu, sigma, q, budget, penalty)
def index_to_selection(i, num_assets):
    s = "{0:b}".format(i).rjust(num_assets)
    x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
    return x

def print_result(result):
    selection = sample_most_likely(result.eigenstate)
    value = portfolio.portfolio_value(selection, mu, sigma, q, budget, penalty)
    print('Optimal: selection {}, value {:.4f}'.format(selection, value))

    eigenvector = result.eigenstate if isinstance(result.eigenstate, np.ndarray) else result.eigenstate.to_matrix()
    probabilities = np.abs(eigenvector)**2
    i_sorted = reversed(np.argsort(probabilities))
    print('\n----------------- Full result ---------------------')
    print('selection\tvalue\t\tprobability')
    print('---------------------------------------------------')
    for i in i_sorted:
        x = index_to_selection(i, num_assets)
        value = portfolio.portfolio_value(x, mu, sigma, q, budget, penalty)
        probability = probabilities[i]
        print('%10s\t%.4f\t\t%.4f' %(x, value, probability))<jupyter_output><empty_output><jupyter_text>Classical eigensolver<jupyter_code>exact_eigensolver = NumPyMinimumEigensolver(qubitOp)
result = exact_eigensolver.run()

print_result(result)<jupyter_output>E:\anaconda\lib\site-packages\qiskit\aqua\algorithms\minimum_eigen_solvers\minimum_eigen_solver.py:36: DeprecationWarning: The package qiskit.aqua.algorithms.minimum_eigen_solvers is deprecated. It was moved/refactored to qiskit.algorithms.minimum_eigen_solvers (pip install qiskit-terra). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>
  warn_package('aqua.algorithms.minimum_eigen_solvers',
E:\anaconda\lib\site-packages\qiskit\aqua\algorithms\eigen_solvers\eigen_solver.py:36: DeprecationWarning: The package qiskit.aqua.algorithms.eigen_solvers is deprecated. It was moved/refactored to qiskit.algorithms.eigen_solvers (pip install qiskit-terra). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>
  warn_package('aqua.algorithms.eigen_solvers',
E:\anaconda\lib\site-packages\qiskit\aqua\operators\state_fns\vector_state_fn.py:215: DeprecationWarning: The variable qiskit.aqua.aqua_global[...]<jupyter_text>[VQE Eigensolver](https://qiskit.org/documentation/tutorials/algorithms/04_vqe_advanced.html)<jupyter_code>backend = Aer.get_backend('statevector_simulator')
seed = 50

cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=3, entanglement='full')
vqe = VQE(qubitOp, ry, cobyla)
vqe.random_seed = seed

quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)

result = vqe.run(quantum_instance)

print_result(result)<jupyter_output>E:\anaconda\lib\site-packages\qiskit\aqua\components\optimizers\optimizer.py:49: DeprecationWarning: The package qiskit.aqua.components.optimizers is deprecated. It was moved/refactored to qiskit.algorithms.optimizers (pip install qiskit-terra). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>
  warn_package('aqua.components.optimizers',
E:\anaconda\lib\site-packages\qiskit\aqua\algorithms\vq_algorithm.py:70: DeprecationWarning: The class qiskit.aqua.algorithms.VQAlgorithm is deprecated. It was moved/refactored to qiskit.algorithms.VariationalAlgorithm (pip install qiskit-terra). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>
  warn_class('aqua.algorithms.VQAlgorithm',
E:\anaconda\lib\site-packages\qiskit\aqua\quantum_instance.py:135: DeprecationWarning: The class qiskit.aqua.QuantumInstance is deprecated. It was moved/refactored to qiskit.utils.QuantumInstance (pip install qis[...]<jupyter_text>[QAOA](https://qiskit.org/documentation/stubs/qiskit.algorithms.QAOA.html) Eigensolver<jupyter_code># by using QAOA
backend = Aer.get_backend('statevector_simulator')
seed = 50

cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa = QAOA(qubitOp, cobyla, 3)

qaoa.random_seed = seed

quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)

result = qaoa.run(quantum_instance)

print_result(result)<jupyter_output>E:\anaconda\lib\site-packages\qiskit\aqua\components\variational_forms\variational_form.py:48: DeprecationWarning: The package qiskit.aqua.components.variational_forms is deprecated. For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>
  warn_package('aqua.components.variational_forms')
{'fraction_non_alphanumeric': 0.12441293752769163, 'fraction_numerical': 0.015330084182543198, 'mean_word_length': 5.823458282950424, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 12, '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': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '195634', 'license': 'MIT', 'n_tokens_mistral': 4391, 'n_tokens_neox': 4080, 'n_words': 798, 'path': 'prepareQC2021.ipynb', 'repo_name': 'YizeSun/qiskit-challenge-2021-prepare', 'size': '11285'}