

!pip install numpy

import numpy as np
print(np.round(np.pi,4))

lista = [0,1,2,3,4,5]
print(lista[1])
print(lista[0:-1])

for i in range(5):
  print("Hola mundo i=%d" %i)

lista = [i for i in range(10)]
lista

import matplotlib.pyplot as plt
plt.plot(lista)
plt.draw()

i = 10
while (i < 15):
  print(i,end=",")
  i = i + 1

def f(x):
  return 2*x
f(3)

a = np.array([1,3,5.31,2,-10.3])
print("El mínimo es %2.3f y el mínimo %2.3e" %(a.min(),a.max()))

b=np.where(a<3) # da los índices donde se cumple la condición
print(b)

a = [1,3,5,2,0]
for i in a:
  if i < 3 :
    print(i, " es < que 3")
  else:
    print(i, " es >= que 3")

!pip install qiskit[machine-learning]
!pip install pylatexenc # instalamos la librería *pylatexenc* para dibujar circuitos con matplotlib

import qiskit
qiskit.__qiskit_version__

from qiskit import QuantumCircuit, Aer
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.h(0)
qc.y(1)
qc.z(2)
qc.h(3)
stv = qi.Statevector.from_instruction(qc)
# Ahora hacemos mediciones de cada qubit
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
qc.draw(output='mpl')

from qiskit import QuantumCircuit, Aer
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.h(0)
qc.y(1)
qc.z(2)
qc.h(3)
stv = qi.Statevector.from_instruction(qc)
# Ahora hacemos mediciones de cada qubit
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style=style)

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3)
for qubit in range(3):
  qc.h(qubit)
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
  qc.measure(qubit,qubit)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit, Aer
import qiskit.quantum_info as qi
qc = QuantumCircuit(1,1)
qc.measure(0,0)
qc.draw("mpl")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(1,1)
qc.ry(-np.pi/2,0)
stv = qi.Statevector.from_instruction(qc)

qc.measure(0,0)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
qc = QuantumCircuit(1,1)
qc.ry(np.pi/2,0)
stv = qi.Statevector.from_instruction(qc)

qc.measure(0,0)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv)

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=471)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import IBMQ
#IBMQ.save_account('CLAVE', overwrite=True)

from qiskit import IBMQ
IBMQ.load_account() # Load account from disk
print(IBMQ.providers())    # List all available providers
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
qc=QuantumCircuit(3)
qc.x(0)
qc.x(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
op = X^X^X
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
display(Latex(f'$<\psi|Op|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))


from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = Zero
from IPython.display import display, Latex,Math
display(Math('|\psi> = |0>'))
display(Latex(f'$<\psi|XX|\psi>$'))
print("=",np.round(psi.adjoint().compose(X).compose(X).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Y).compose(Y).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Z).compose(Z).compose(psi).eval().real,1))


from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = One
from IPython.display import display, Latex,Math
display(Math('|\psi> = |1>'))
display(Latex(f'$<\psi|XX|\psi>$'))
print("=",np.round(psi.adjoint().compose(X).compose(X).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Y).compose(Y).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Z).compose(Z).compose(psi).eval().real,1))


from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^One ^ Zero^ Zero) - (Zero ^Zero ^ One^ One))
op1 = -0.8105479805373275 * I^I^I^I + 0.1721839326191556 * I^I^I^Z - 0.2257534922240239 * I^I^Z^I \
+ 0.17218393261915554 * I^Z^I^I - 0.2257534922240239 * Z^I^I^I
# Step 1: Define operator
op = SparsePauliOp.from_list(
    [
        ("IIII", -0.8105479805373275),
        ("IIIZ", + 0.1721839326191556),
        ("IIZI", - 0.2257534922240239),
        ("IZII", + 0.17218393261915554),
        ("ZIII", - 0.2257534922240239),
        ("IIZZ", + 0.12091263261776629),
        ("IZIZ", + 0.16892753870087907),
        ("YYYY", + 0.04523279994605784),
        ("XXYY", + 0.04523279994605784),
        ("YYXX", + 0.04523279994605784),
        ("XXXX", + 0.04523279994605784),
        ("ZIIZ", + 0.16614543256382414),
        ("IZZI", +0.16614543256382414),
        ("ZIZI", + 0.17464343068300445),
        ("ZIZI", + 0.12091263261776629),

    ]
)
# Step 2: Define quantum state
state = QuantumCircuit(4)
state.h(0)
state.h(1)
state.x(2)
from qiskit.primitives import Estimator

estimator = Estimator()

expectation_value = estimator.run(state, op).result().values

# for shot-based simulation:
expectation_value = estimator.run(state, op, shots=1000).result().values
print("expectation: ", expectation_value)

print("=",np.round(psi.adjoint().compose(op1).compose(psi).eval().real,16))

from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
  qc.measure(qubit,qubit)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.z(1) # NOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
  qc.measure(qubit,qubit)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.x(1) # NOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
  qc.measure(qubit,qubit)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.x(1) # NOT gate
qc.z(1) # Z gate
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
  qc.measure(qubit,qubit)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
from IPython.display import display, Latex,Math
Op1 = X^X
Op2 = Y^Y
Op3 = Z^Z
for j in range(4):
  if j == 0:
    psi = 1 / np.sqrt(2) * ((Zero^ Zero) + (One^ One))
    display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>+|1>|1>)'))
  if j == 1:
    psi = 1 / np.sqrt(2) * ((Zero^ Zero) - (One^ One))
    display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>-|1>|1>)'))
  if j == 2:
    psi = 1 / np.sqrt(2) * ((Zero^ One) + (One^ Zero))
    display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|1>+|1>|0>)'))
  if j == 3:
    psi = 1 / np.sqrt(2) * ((Zero^ One) - (One^ Zero))
    display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|1>-|1>|0>)'))
  display(Latex(f'$<\psi|2(X\otimes X+Y\otimes Y+Z\otimes Z)|\psi>$'))

  print("=",2*(np.round(psi.adjoint().compose(Op1).compose(psi).eval().real,1)
  +np.round(psi.adjoint().compose(Op2).compose(psi).eval().real,1)+
  np.round(psi.adjoint().compose(Op3).compose(psi).eval().real,1)),"\n")


from qiskit import QuantumCircuit, Aer,transpile
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.cx(1,2) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
  qc.measure(qubit,qubit)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())

from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy


from qiskit import IBMQ, Aer
from qiskit_aer.noise import NoiseModel
#IBMQ.save_account('CLAVE', overwrite=True)

provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_manila')
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)

backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
      and not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)

sim_backend = AerSimulator.from_backend(backend)
print("least busy backend: ", sim_backend)

# Transpile the circuit for the noisy basis gates
tqc = transpile(qc, sim_backend,optimization_level=3)

# Execute noisy simulation and get counts
job = sim_backend.run(tqc,shots=1000)
print("Counts for 3-qubit GHZ state with simulated noise model for", backend)
plot_histogram(job.result().get_counts())

tqc.draw("mpl")

from qiskit import QuantumCircuit, Aer,transpile
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.cx(1,2) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
  qc.measure(qubit,qubit)
qc.draw("mpl")

from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
# Load local account information
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
                                       and not x.configuration().simulator
                                       and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit
tqc = transpile(qc, backend, optimization_level=3)
job = backend.run(tqc,shots = 100)

from qiskit.providers.jobstatus import JobStatus
print(job.status(),job.queue_position())

print("Counts for 3-qubit GHZ state with real computer", backend)
plot_histogram(job.result().get_counts())

import numpy as np
from qiskit.visualization import array_to_latex
from qiskit.quantum_info import random_statevector
psi = random_statevector(2)
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))

from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(psi)

from qiskit import QuantumCircuit, assemble, Aer
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,2)
qc.initialize(psi, 0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.measure(0,0)
qc.measure(1,1)
qc.draw("mpl")


from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv0)

stv.draw('latex', prefix='Estado \quad del \quad sistema \quad de \quad 3 \quad qubits \quad = \quad')

from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1)
print(job.result().get_counts(qc))
plot_histogram(job.result().get_counts())

import qiskit.quantum_info as qi
import numpy as np
qc1 = QuantumCircuit(3,2)
print(job.result().get_counts())
for key in job.result().data()["counts"]:
  if int(key,0) == 0 :
    print("El resultado es 00")
    q2_state = [np.round(stv[0],3),np.round(stv[4],3)]
    qc1.initialize(0, 0)
    qc1.initialize(0, 1)
  elif int(key,0) == 1 :
    print("El resultado es 01")
    q2_state = [np.round(stv[1],3),np.round(stv[5],3)]
    qc1.initialize(1, 0)
    qc1.initialize(0, 1)
  elif int(key,0) == 2 :
    print("El resultado es 10")
    q2_state = [np.round(stv[2],3),np.round(stv[6],3)]
    qc1.initialize(0, 0)
    qc1.initialize(1, 1)
  elif int(key,0) == 3 :
    print("El resultado es 11")
    q2_state = [np.round(stv[3],3),np.round(stv[7],3)]
    qc1.initialize(1, 0)
    qc1.initialize(1, 1)
q2_normalizado = q2_state/np.linalg.norm(q2_state)
qc1.barrier()
qc1.initialize(q2_normalizado, 2)
for key in job.result().data()["counts"]:
  if int(key,0) == 1 :
    qc1.z(2)
  if int(key,0) == 2 :
    qc1.x(2)
  if int(key,0) == 3 :
    qc1.x(2)
    qc1.z(2)

stv1 = qi.Statevector.from_instruction(qc1)
stv1.draw('latex', prefix='Estado \quad del \quad qubit \quad 2 = ')

from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv1)

import qiskit.quantum_info as qi
import numpy as np
qc2 = QuantumCircuit(3,2)
for key in job.result().data(qc)["counts"]:
  if int(key,0) != 0 :
    qc2.initialize(psi, 2)
qcc = qc.compose(qc1)
qc3 = qcc.compose(qc2)
qc3.draw("mpl")

from qiskit import QuantumCircuit, assemble, Aer
from qiskit import IBMQ, transpile
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram

import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
theta=np.pi*np.random.rand()
phi = 2*np.pi*np.random.rand()
print("theta =",np.round(theta,2),"rad,   theta =",np.round(180*theta/np.pi,2),"grados")
print("phi=",np.round(phi,2),"rad,   phi =",np.round(180*phi/np.pi,2),"grados")
qc = QuantumCircuit(3,3)
qc.ry(theta,0)
qc.rz(phi,0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()

qc.rz(-phi,2)
qc.ry(-theta,2)
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style=style)


from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv0)

backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
#print(job.result().get_counts(qc))
try :
  n_error = job.result().get_counts(qc)['100']
except:
  n_error = 0
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,6))

states = ['000', '100']
counts = [job.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
    plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()

#plot_histogram(job.result().get_counts())

from qiskit_aer import AerSimulator

IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
                                       and not x.configuration().simulator
                                       and x.status().operational==True))
sim_backend = AerSimulator.from_backend(backend)
print("least busy backend: ", sim_backend,"\n\n")

# Transpile the circuit for the noisy basis gates
tqc = transpile(qc, sim_backend,optimization_level=3)

# Execute noisy simulation and get counts
job = sim_backend.run(tqc,shots=1000)
try :
  n_error = job.result().get_counts(qc)['100']
except:
  n_error = 0
import matplotlib.pyplot as plt
try :
  n_error = job.result().get_counts(qc)['100']
except:
  n_error = 0
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,6))

states = ['000', '100']
counts = [job.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
    plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()



tqc.draw("mpl")

from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
                                       and not x.configuration().simulator
                                       and x.status().operational==True))
print("least busy backend: ", backend)
tqc = transpile(qc, backend, optimization_level=3)
job_teleportation = backend.run(tqc,shots = 1000)


print(job_teleportation.status(),job_teleportation.queue_position())

print(job_teleportation.result().get_counts(),"\n\n")
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,8))
states = ['000', '100']
counts = [job.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
    plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()

from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.z(1)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.draw("mpl")


stv.draw('latex', prefix="|\\psi\\rangle =")

backend = Aer.get_backend('qasm_simulator')

N_corr = 0
N_anticorr = 0
qc3 = QuantumCircuit(2, 2)
qc3.measure(0,0)
qc3.measure(1,1)
print("                       Experimento A1B1")
qc11=qc
print(qc11)
qc11=qc.compose(qc3)
job11 = execute(qc11,backend, shots=1000)
result = job11.result()
print("Resultados :",result.get_counts(qc11))
if job11.result().get_counts().get('11') is not None:
  N_corr += job11.result().get_counts()['11']
if job11.result().get_counts().get('00') is not None:
  N_corr += job11.result().get_counts()['00']
N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10']

print()
print("                       Experimento A1B2")
qc12 = QuantumCircuit(2, 2)
qc12.rz(0,1)
qc12.ry(-2*np.pi/3,1)
qc12.barrier()
qc12=qc.compose(qc12)
qc12=qc12.compose(qc3)
print(qc12)
job12 = execute(qc12,backend, shots=1000)
result = job12.result()
print("Resultados :",result.get_counts(qc12))
N_corr += job12.result().get_counts()['11']+job12.result().get_counts()['00']
N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10']

print()
print("                       Experimento A1B3")
qc13 = QuantumCircuit(2, 2)
qc13.rz(-np.pi,1)
qc13.ry(-2*np.pi/3,1)
qc13.barrier()
qc13=qc.compose(qc13)
qc13=qc13.compose(qc3)
print(qc13)
job13 = execute(qc13,backend, shots=1000)
result = job13.result()
print("Resultados :",result.get_counts(qc13))
N_corr += job13.result().get_counts()['11']+job13.result().get_counts()['00']
N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10']

print()
print("                       Experimento A2B1")
qc21 = QuantumCircuit(2, 2)
qc21.rz(0,0)
qc21.ry(-2*np.pi/3,0)
qc21.barrier()
qc21=qc.compose(qc21)
qc21=qc21.compose(qc3)
print(qc21)
job21 = execute(qc21,backend, shots=1000)
result = job21.result()
print("Resultados :",result.get_counts(qc21))
N_corr += job21.result().get_counts()['11']+job21.result().get_counts()['00']
N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10']

print()
print("                       Experimento A2B2")
qc22 = QuantumCircuit(2, 2)
qc22.rz(0,0)
qc22.ry(-2*np.pi/3,0)
qc22.rz(0,1)
qc22.ry(-2*np.pi/3,1)
qc22.barrier()
qc22=qc.compose(qc22)
qc22=qc22.compose(qc3)
print(qc22)
job22 = execute(qc22,backend, shots=1000)
result = job22.result()
print("Resultados :",result.get_counts(qc22))
if job22.result().get_counts().get('11') is not None:
  N_corr += job22.result().get_counts()['11']
if job22.result().get_counts().get('00') is not None:
  N_corr += job22.result().get_counts()['00']
N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10']

print()
print("                       Experimento A2B3")
qc23 = QuantumCircuit(2, 2)
qc23.rz(0,0)
qc23.ry(-2*np.pi/3,0)
qc23.rz(-np.pi,1)
qc23.ry(-2*np.pi/3,1)
qc23.barrier()
qc23=qc.compose(qc23)
qc23=qc23.compose(qc3)
print(qc23)
job23 = execute(qc23,backend, shots=1000)
result = job23.result()
print("Resultados :",result.get_counts(qc23))
N_corr += job23.result().get_counts()['11']+job23.result().get_counts()['00']
N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10']

print()
print("                       Experimento A3B1")
qc31 = QuantumCircuit(2, 2)
qc31.rz(-np.pi,0)
qc31.ry(-2*np.pi/3,0)
qc31.barrier()
qc31=qc.compose(qc31)
qc31=qc31.compose(qc3)
print(qc31)
job31 = execute(qc31,backend, shots=1000)
result = job31.result()
print("Resultados :",result.get_counts(qc31))
N_corr += job31.result().get_counts()['11']+job31.result().get_counts()['00']
N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10']

print()
print("                       Experimento A3B2")
qc32 = QuantumCircuit(2, 2)
qc32.rz(-np.pi,0)
qc32.ry(-2*np.pi/3,0)
qc32.rz(0,1)
qc32.ry(-2*np.pi/3,1)
qc32.barrier()
qc32=qc.compose(qc32)
qc32=qc32.compose(qc3)
print(qc32)
job32 = execute(qc32,backend, shots=1000)
result = job31.result()
print("Resultados :",result.get_counts(qc32))
N_corr += job32.result().get_counts()['11']+job32.result().get_counts()['00']
N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10']

print()
print("                       Experimento A3B3")
qc33 = QuantumCircuit(2, 2)
qc33.rz(-np.pi,0)
qc33.ry(-2*np.pi/3,0)
qc33.rz(-np.pi,1)
qc33.ry(-2*np.pi/3,1)
qc33.barrier()
qc33=qc.compose(qc33)
qc33=qc33.compose(qc3)
print(qc33)
job33 = execute(qc33,backend, shots=1000)
result = job33.result()
print("Resultados :",result.get_counts(qc33))
if job33.result().get_counts().get('11') is not None:
  N_corr += job33.result().get_counts()['11']
if job33.result().get_counts().get('00') is not None:
  N_corr += job33.result().get_counts()['00']
N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10']
print("Total correlated:", N_corr, " Total anti-correlated:", N_anticorr)

from qiskit import IBMQ, Aer
from qiskit_aer.noise import NoiseModel
IBMQ.save_account('your-IBMQ-password', overwrite=True)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_manila')
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)

from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
                                       and not x.configuration().simulator
                                       and x.status().operational==True))
print("least busy backend: ", backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)

from qiskit import QuantumCircuit, Aer
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.z(1)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.draw("mpl")


stv.draw('latex', prefix="|\\psi\\rangle =")

backend = AerSimulator.from_backend(backend)
shots = 1000
N_corr = 0
N_anticorr = 0
qc3 = QuantumCircuit(2, 2)
qc3.measure(0,0)
qc3.measure(1,1)
print("                       Experiment A1B1")
qc11=qc
qc11=qc.compose(qc3)
print(qc11)
tqc11 = transpile(qc11, backend, optimization_level=3)
job11 = backend.run(tqc11,shots =shots)
print("Results :",job11.result().get_counts())
if job11.result().get_counts().get('11') is not None:
  N_corr += job11.result().get_counts()['11']
if job11.result().get_counts().get('00') is not None:
  N_corr += job11.result().get_counts()['00']
N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10']

print("\n                       Experiment A1B2")
qc12 = QuantumCircuit(2, 2)
qc12.rz(0,1)
qc12.ry(-2*np.pi/3,1)
qc12.barrier()
qc12=qc.compose(qc12)
qc12=qc12.compose(qc3)
print(qc12)
tqc12 = transpile(qc12, backend, optimization_level=3)
job12 = backend.run(tqc12,shots =shots)
print("Results :",job12.result().get_counts())
N_corr += job12.result().get_counts()['11']+job12.result().get_counts()['00']
N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10']

print("\n                       Experiment A1B3")
qc13 = QuantumCircuit(2, 2)
qc13.rz(-np.pi,1)
qc13.ry(-2*np.pi/3,1)
qc13.barrier()
qc13=qc.compose(qc13)
qc13=qc13.compose(qc3)
print(qc13)
tqc13 = transpile(qc13, backend, optimization_level=3)
job13 = backend.run(tqc13,shots =shots)
print("Results :",job13.result().get_counts())
N_corr += job13.result().get_counts()['11']+job13.result().get_counts()['00']
N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10']

print("\n                       Experiment A2B1")
qc21 = QuantumCircuit(2, 2)
qc21.rz(0,0)
qc21.ry(-2*np.pi/3,0)
qc21.barrier()
qc21=qc.compose(qc21)
qc21=qc21.compose(qc3)
print(qc21)
tqc21 = transpile(qc21, backend, optimization_level=3)
job21 = backend.run(tqc21,shots =shots)
print("Results :",job21.result().get_counts())
N_corr += job21.result().get_counts()['11']+job21.result().get_counts()['00']
N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10']

print("\n                        Experiment A2B2")
qc22 = QuantumCircuit(2, 2)
qc22.rz(0,0)
qc22.ry(-2*np.pi/3,0)
qc22.rz(0,1)
qc22.ry(-2*np.pi/3,1)
qc22.barrier()
qc22=qc.compose(qc22)
qc22=qc22.compose(qc3)
print(qc22)
tqc22 = transpile(qc22, backend, optimization_level=3)
job22 = backend.run(tqc22,shots =shots)
print("Results :",job22.result().get_counts())
if job22.result().get_counts().get('11') is not None:
  N_corr += job22.result().get_counts()['11']
if job22.result().get_counts().get('00') is not None:
  N_corr += job22.result().get_counts()['00']
N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10']

print("\n                        Experiment A2B3")
qc23 = QuantumCircuit(2, 2)
qc23.rz(0,0)
qc23.ry(-2*np.pi/3,0)
qc23.rz(-np.pi,1)
qc23.ry(-2*np.pi/3,1)
qc23.barrier()
qc23=qc.compose(qc23)
qc23=qc23.compose(qc3)
print(qc23)
tqc23 = transpile(qc23, backend, optimization_level=3)
job23 = backend.run(tqc23,shots =shots)
print("Results :",job23.result().get_counts())
N_corr += job23.result().get_counts()['11']+job23.result().get_counts()['00']
N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10']

print("\n                        Experiment A3B1")
qc31 = QuantumCircuit(2, 2)
qc31.rz(-np.pi,0)
qc31.ry(-2*np.pi/3,0)
qc31.barrier()
qc31=qc.compose(qc31)
qc31=qc31.compose(qc3)
print(qc31)
tqc31 = transpile(qc31, backend, optimization_level=3)
job31 = backend.run(tqc31,shots =shots)
print("Results :",job31.result().get_counts())
N_corr += job31.result().get_counts()['11']+job31.result().get_counts()['00']
N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10']

print("\n                        Experiment A3B2")
qc32 = QuantumCircuit(2, 2)
qc32.rz(-np.pi,0)
qc32.ry(-2*np.pi/3,0)
qc32.rz(0,1)
qc32.ry(-2*np.pi/3,1)
qc32.barrier()
qc32=qc.compose(qc32)
qc32=qc32.compose(qc3)
print(qc32)
tqc32 = transpile(qc32, backend, optimization_level=3)
job32 = backend.run(tqc32,shots =shots)
print("Results :",job32.result().get_counts(qc32))
N_corr += job32.result().get_counts()['11']+job32.result().get_counts()['00']
N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10']

print("\n                        Experiment A3B3")
qc33 = QuantumCircuit(2, 2)
qc33.rz(-np.pi,0)
qc33.ry(-2*np.pi/3,0)
qc33.rz(-np.pi,1)
qc33.ry(-2*np.pi/3,1)
qc33.barrier()
qc33=qc.compose(qc33)
qc33=qc33.compose(qc3)
print(qc33)
tqc33 = transpile(qc33, backend, optimization_level=3)
job33 = backend.run(tqc33,shots =shots)
print("Results :",job33.result().get_counts(qc33))
if job33.result().get_counts().get('11') is not None:
  N_corr += job33.result().get_counts()['11']
if job33.result().get_counts().get('00') is not None:
  N_corr += job33.result().get_counts()['00']
N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10']
print("\nOut of a total of",9*shots,"measurements, we obtained")
print("Total correlated measurements:", N_corr)
print("Total anti-correlated measurements:", N_anticorr," corresponding to ",np.round(100*N_anticorr/(9*shots),2),"%")


from qiskit import IBMQ, Aer
from qiskit_aer.noise import NoiseModel
IBMQ.save_account('your-IBMQ-password', overwrite=True)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_manila')
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)

from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
                                       and not x.configuration().simulator
                                       and x.status().operational==True))
print("least busy backend: ", backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)

from qiskit import QuantumCircuit, Aer
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.z(1)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.draw("mpl")

stv.draw('latex', prefix="|\\psi\\rangle =")

shots = 1000
N_corr = 0
N_anticorr = 0
qc3 = QuantumCircuit(2, 2)
qc3.measure(0,0)
qc3.measure(1,1)
print("                       Experiment A1B1")
qc11=qc
qc11=qc.compose(qc3)
print(qc11)
tqc11 = transpile(qc11, backend, optimization_level=3)
job11 = backend.run(tqc11,shots =shots)
print("\n                       Experiment A1B2")
qc12 = QuantumCircuit(2, 2)
qc12.rz(0,1)
qc12.ry(-2*np.pi/3,1)
qc12.barrier()
qc12=qc.compose(qc12)
qc12=qc12.compose(qc3)
print(qc12)
tqc12 = transpile(qc12, backend, optimization_level=3)
job12 = backend.run(tqc12,shots =shots)
print("\n                       Experiment A1B3")
qc13 = QuantumCircuit(2, 2)
qc13.rz(-np.pi,1)
qc13.ry(-2*np.pi/3,1)
qc13.barrier()
qc13=qc.compose(qc13)
qc13=qc13.compose(qc3)
print(qc13)
tqc13 = transpile(qc13, backend, optimization_level=3)
job13 = backend.run(tqc13,shots =shots)
print("\n                       Experiment A2B1")
qc21 = QuantumCircuit(2, 2)
qc21.rz(0,0)
qc21.ry(-2*np.pi/3,0)
qc21.barrier()
qc21=qc.compose(qc21)
qc21=qc21.compose(qc3)
print(qc21)
tqc21 = transpile(qc21, backend, optimization_level=3)
job21 = backend.run(tqc21,shots =shots)
print("\n                        Experiment A2B2")
qc22 = QuantumCircuit(2, 2)
qc22.rz(0,0)
qc22.ry(-2*np.pi/3,0)
qc22.rz(0,1)
qc22.ry(-2*np.pi/3,1)
qc22.barrier()
qc22=qc.compose(qc22)
qc22=qc22.compose(qc3)
print(qc22)
tqc22 = transpile(qc22, backend, optimization_level=3)
job22 = backend.run(tqc22,shots =shots)

from qiskit.providers.jobstatus import JobStatus
print(job11.status(),job11.queue_position())
print(job12.status(),job12.queue_position())
print(job13.status(),job13.queue_position())
print(job21.status(),job21.queue_position())
print(job22.status(),job22.queue_position())


print("\n                        Experiment A2B3")
qc23 = QuantumCircuit(2, 2)
qc23.rz(0,0)
qc23.ry(-2*np.pi/3,0)
qc23.rz(-np.pi,1)
qc23.ry(-2*np.pi/3,1)
qc23.barrier()
qc23=qc.compose(qc23)
qc23=qc23.compose(qc3)
print(qc23)
tqc23 = transpile(qc23, backend, optimization_level=3)
job23 = backend.run(tqc23,shots =shots)
print("\n                        Experiment A3B1")
qc31 = QuantumCircuit(2, 2)
qc31.rz(-np.pi,0)
qc31.ry(-2*np.pi/3,0)
qc31.barrier()
qc31=qc.compose(qc31)
qc31=qc31.compose(qc3)
print(qc31)
tqc31 = transpile(qc31, backend, optimization_level=3)
job31 = backend.run(tqc31,shots =shots)
print("\n                        Experiment A3B2")
qc32 = QuantumCircuit(2, 2)
qc32.rz(-np.pi,0)
qc32.ry(-2*np.pi/3,0)
qc32.rz(0,1)
qc32.ry(-2*np.pi/3,1)
qc32.barrier()
qc32=qc.compose(qc32)
qc32=qc32.compose(qc3)
print(qc32)
tqc32 = transpile(qc32, backend, optimization_level=3)
job32 = backend.run(tqc32,shots =shots)
print("\n                        Experiment A3B3")
qc33 = QuantumCircuit(2, 2)
qc33.rz(-np.pi,0)
qc33.ry(-2*np.pi/3,0)
qc33.rz(-np.pi,1)
qc33.ry(-2*np.pi/3,1)
qc33.barrier()
qc33=qc.compose(qc33)
qc33=qc33.compose(qc3)
print(qc33)
tqc33 = transpile(qc33, backend, optimization_level=3)
job33 = backend.run(tqc33,shots =shots)

print(job23.status(),job23.queue_position())
print(job31.status(),job31.queue_position())
print(job32.status(),job32.queue_position())
print(job33.status(),job33.queue_position())

N_corr = 0
N_anticorr = 0
print("                       Experiment A1B1")
print("Results :",job11.result().get_counts())
if job11.result().get_counts().get('11') is not None:
  N_corr += job11.result().get_counts()['11']
if job11.result().get_counts().get('00') is not None:
  N_corr += job11.result().get_counts()['00']
N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10']
print("                       Experiment A1B2")
print("Results :",job12.result().get_counts())
N_corr += job12.result().get_counts()['11']
N_corr += job12.result().get_counts()['00']
N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10']
print("                       Experiment A1B3")
print("Results :",job13.result().get_counts())
N_corr += job13.result().get_counts()['11']
N_corr += job13.result().get_counts()['00']
N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10']
print("                       Experiment A2B1")
print("Results :",job21.result().get_counts())
N_corr += job21.result().get_counts()['11']
N_corr += job21.result().get_counts()['00']
N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10']
print("                       Experiment A2B2")
print("Results :",job22.result().get_counts())
if job22.result().get_counts().get('11') is not None:
  N_corr += job22.result().get_counts()['11']
if job22.result().get_counts().get('00') is not None:
  N_corr += job22.result().get_counts()['00']
N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10']
print("                       Experiment A2B3")
print("Results :",job23.result().get_counts())
N_corr += job23.result().get_counts()['11']
N_corr += job23.result().get_counts()['00']
N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10']
print("                       Experiment A3B1")
print("Results :",job31.result().get_counts())
N_corr += job31.result().get_counts()['11']
N_corr += job31.result().get_counts()['00']
N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10']
print("                       Experiment A3B2")
print("Results :",job32.result().get_counts())
N_corr += job32.result().get_counts()['11']
N_corr += job32.result().get_counts()['00']
N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10']
print("                       Experiment A3B3")
print("Results :",job33.result().get_counts())
if job33.result().get_counts().get('11') is not None:
  N_corr += job33.result().get_counts()['11']
if job33.result().get_counts().get('00') is not None:
  N_corr += job33.result().get_counts()['00']
N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10']

print("\nOut of a total of",9*shots,"measurements, we obtained")
print("Total correlated measurements:", N_corr)
print("Total anti-correlated measurements:", N_anticorr," corresponding to ",np.round(100*N_anticorr/(9*shots),2),"%")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1000)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))



import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright

from qiskit import QuantumCircuit, Aer,execute
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(1,1) # Ponemos 1 qubit y 1 bit
psi = [np.cos(2*np.pi/3/2),np.sin(2*np.pi/3/2)]
qc.initialize(psi, 0)
stv = qi.Statevector.from_instruction(qc)
stv.draw('latex', prefix="|\\psi\\rangle =")
qc.measure(0,0)
qc.draw(output='mpl')

from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(psi)

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
n_shots = 1000
job = execute(qc,backend, shots=n_shots, memory=True)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))

Data =result.get_memory()
np.array(list(map(int, Data)))
print(np.array(list(map(int, Data))))
print("Suma de 1s =",sum(np.array(list(map(int, Data)))),"Suma de 0s =",n_shots-sum(np.array(list(map(int, Data)))))

from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
  qc.measure(qubit,qubit)
qc.draw("mpl")

from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.cx(1,2) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
  qc.measure(qubit,qubit)
qc.draw("mpl")

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
op =  X^Y^Y +X^X^X
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
display(Latex(f'$<\psi|Op|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))


import numpy as np
from qiskit.opflow import Z, X,Y,I, Zero, One

#operator = (X+X)** +(Y+Y)**2 +(Z+Z)**2

operator = X
psi = 1 / np.sqrt(2) * ((Zero + One))

expectation_value = (~psi @ operator @ psi).eval()
print(expectation_value.real)

psi = 1 / np.sqrt(2) * ((Zero - One))


expectation_value = (psi.adjoint() @ operator @ psi).eval()
print(expectation_value.real)

# Para más detalles ver https://arxiv.org/pdf/2206.14584.pdf

import numpy as np
from qiskit.opflow import Z, X,Y,I, Zero, One
operator = np.sin(2*np.pi/3)*X^Z+np.cos(2*np.pi/3)*Z^Z
psi = 1 / np.sqrt(2) * ((Zero ^ One) - (One ^ Zero))
expectation_value = (psi.adjoint() @ operator @ psi).eval()
print(expectation_value.real)
# Para más detalles ver https://arxiv.org/pdf/2206.14584.pdf

from qiskit import QuantumCircuit, assemble, Aer
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,2)
qc.initialize([1/np.sqrt(2),1/np.sqrt(2)], 0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.measure(0,0)
qc.measure(1,1)
qc.draw("mpl")


from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))

from qiskit.opflow import CircuitStateFn
import qiskit.quantum_info as qi
import numpy as np
psi=QuantumCircuit(3)
psi.h(0) # Hadamard gate
psi.cx(0,1) # CNOT gate
psi.cx(1,2) # CNOT gate
stv0 = qi.Statevector.from_instruction(psi)
psi=CircuitStateFn(psi)
stv0.draw('latex', prefix="|\\psi\\rangle =")

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.x(0)
qc.x(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))


from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.x(0)
qc.x(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.y(0)
qc.y(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|X\otimes Y\otimes Y|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.y(0)
qc.x(1)
qc.y(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|Y\otimes X\otimes Y|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.x(0)
qc.y(1)
qc.y(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|Y\otimes Y\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))

from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
op = X^X^X
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
for i in range(4):
  if i==0: Op = X^X^X
  if i==1: Op = X^Y^Y
  if i==2: Op = Y^X^Y
  if i==3: Op = Y^Y^X
  print("\nOp =",Op)
  display(Latex(f'$<\psi|Op|\psi>$'))
  print("=",np.round(psi.adjoint().compose(Op).compose(psi).eval().real,1))


# Código tomado de https://github.com/lvillasen/Euclidean-Algorithm
def f(i,N1,N2,n1,n2,c1,c2):
  n3=n1%n2
  e3 = n1//n2
  c3 = c1 -e3*c2
  print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)")
  print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)")
  return N1,N2,n2,n3,c2,c3

# Input the two integers here (N1 >N2)
N1 = 51
N2 = 13
n1,n2,c1,c2 = N1,N2,0,1
print("( 1 )\t",N1,"= 0 (mod",N1,")")
print("( 2 )\t",N2,"= ",N2," (mod",N1,")")
i=3
while n2>1:
  N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2)
  i+=1
if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1)
if n2 == 1:

  print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='')
  print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='')
  print("\nGCD(",N1, "," ,N2,") = ",n2)


p =3490529510847650949147849619903898133417764638493387843990820577
q = 32769132993266709549961988190834461413177642967992942539798288533
N = p*q
y = 200805001301070903002315180419000118050019172105011309190800151919090618010705
# Código tomado de https://github.com/lvillasen/Euclidean-Algorithm
def f(i,N1,N2,n1,n2,c1,c2):
  n3=n1%n2
  e3 = n1//n2
  c3 = c1 -e3*c2
  print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)")
  print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)")
  return N1,N2,n2,n3,c2,c3

# Input the two integers here (N1 >N2)
N1 = (p-1)*(q-1)
N2 = 9007
n1,n2,c1,c2 = N1,N2,0,1
print("( 1 )\t",N1,"= 0 (mod",N1,")")
print("( 2 )\t",N2,"= ",N2," (mod",N1,")")
i=3
while n2>1:
  N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2)
  i+=1
if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1)
if n2 == 1:
  print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='')
  print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='')


# Código tomado de https://github.com/jacksoninfosec/youtube-videos/blob/master/modular_exp.py
# https://www.youtube.com/watch?v=3Bh7ztqBpmw
def mod_power(a, n, m):
	r = 1
	while n > 0:
		if n & 1 == 1:
			r = (r * a) % m
		a = (a * a) % m
		n >>= 1
	return r
p =3490529510847650949147849619903898133417764638493387843990820577
q = 32769132993266709549961988190834461413177642967992942539798288533
N = p*q
y = 96869613754622061477140922254355882905759991124574319874695120930816298225145708356931476622883989628013391990551829945157815154
d = 106698614368578024442868771328920154780709906633937862801226224496631063125911774470873340168597462306553968544513277109053606095
m = mod_power(y, d, N)
print("m=",m)

s = str(m)
list =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(s)//2):
  print(s[2*i:2*i+2],end =" ")
print()
list =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(s)//2):
  print(list[int(s[2*i:2*i+2])],end =" ")

p = 1000003
q = 1000291
N = p*q
a =2
def f(i,N1,N2,n1,n2,c1,c2):
  n3=n1%n2
  e3 = n1//n2
  c3 = c1 -e3*c2
  print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)")
  print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)")
  return N1,N2,n2,n3,c2,c3

# Input the two integers here (N1 >N2)
N1 = N
N2 = a
n1,n2,c1,c2 = N1,N2,0,1
print("( 1 )\t",N1,"= 0 (mod",N1,")")
print("( 2 )\t",N2,"= ",N2," (mod",N1,")")
i=3
while n2>1:
  N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2)
  i+=1
if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1)
if n2 == 1:
  print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='')

  print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='')

  print("\n",N2, " y ",N1," son coprimos ")



import numpy as np
def mod_power(a, n, m):
	r = 1
	while n > 0:
		if n & 1 == 1:
			r = (r * a) % m
		a = (a * a) % m
		n >>= 1
	return r
a=2
a = 3
p = 1000003
p=347# 1931 , 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999
q = 307 #, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
#p=61
q =  1931
p= 1933

N = p*q
N = 15
a=4

print("N =",N,"a =",a," MCD(a,N)=",np.gcd(a,N))

#dat = [a**i % N for i in range(100)]
i=2
while (mod_power(a, i, N)) > 1:
#while (a**i % N) > 1:
  i += 2
r = i
print("Periodo = ",r)
dat = [a**i % N for i in range(3*r)]
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 8))
plt.plot(dat,'-*b')
plt.grid()
plt.draw()



p= 122949829
q = 141650939
N = p*q
i=3
while (N %i != 0):
  i += 2
print("Factores : ",i,N//i)

import numpy as np

print("Los factores primos son:",np.gcd(a**(r//2) +1,N),np.gcd(a**(r//2) -1,N))

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
def x(t):
    return 1+2*np.cos(2*np.pi*5*t)+3*np.sin(2*np.pi*7*t)
T = 1
sr = 40
ts = np.linspace(0, T, sr*T)
t = np.linspace(0, T, 1000)
Corr_cos=np.zeros((sr*T))
Corr_sen=np.zeros((sr*T))
N=np.arange(0, sr*T)

def Grafica(n):
  ax[0].clear()
  ax[1].clear()

  frec = n/T
  Corr_cos[n] = np.dot(x(ts),np.cos(-2*np.pi*n*ts/T))
  Corr_sen[n] = np.dot(x(ts),np.sin(-2*np.pi*n*ts/T))



  ax[0].plot(t, x(t),'b')
  ax[0].plot(t, np.cos(2*np.pi*n*t/T),'r')
  ax[0].plot(t, np.sin(2*np.pi*n*t/T),'g')
  ax[0].plot(ts, x(ts),'.b',ms=10)
  ax[0].plot(ts, np.cos(2*np.pi*n*ts/T),'.r',ms=10)
  ax[0].plot(ts, np.sin(2*np.pi*n*ts/T),'.g',ms=10)

  #ax[1].title('Frecuencia  Señal de Correlación = {}'.format(frec)+ ' Hz, GS'+'= {}'.format(np.round(GS,1)), fontsize=18)
  ax[0].set_xlabel('t', fontsize=18)
  ax[0].set_ylabel('x(t)', fontsize=18)
  ax[0].grid()


  ax[1].plot(N, Corr_cos,'-r',ms=10,label='Corr Cos para k={}'.format(n))
  ax[1].plot(N, Corr_sen,'-.g',ms=10,label='Corr Sen para k={}'.format(n))

  #ax[2].title('Frecuencia  Señal de Correlación = {}'.format(frec)+ ' Hz, GS'+'= {}'.format(np.round(GS,1)), fontsize=18)
  ax[1].set_xlabel('k', fontsize=18)
  ax[1].set_ylabel(r'$X_k$', fontsize=18)
  ax[1].grid()
  ax[1].legend()

fig=plt.figure(figsize=(10,6), dpi= 100)
ax= fig.subplots(2,1)
anim = animation.FuncAnimation(fig, Grafica, frames=40 , interval=800)
plt.close()
HTML(anim.to_html5_video())

from qiskit.circuit import Gate

U_f = Gate(name='U_f', num_qubits=2, params=[])

import qiskit as qk
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)

from qiskit import *
qc = QuantumCircuit(8, 8)
for q in range(4):
    qc.h(q)
# And auxiliary register in state |1>
qc.append(U_f [qr[0], qr[1]])

qc.barrier()


qc.measure(range(4), range(4))
style = {'backgroundcolor': 'lightgreen'}
qc.draw('mpl',fold=-1,style=style)  # -1 means 'do not fold'



import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
import qiskit.quantum_info as qi
from math import gcd
from numpy.random import randint
from fractions import Fraction
print("Imports Successful")
import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.x(0)
qc.y(1)
qc.z(2)
qc.h(3)
stv = qi.Statevector.from_instruction(qc)

## Create 7mod15 gate
N = 15
m = int(np.ceil(np.log2(N)))
import qiskit.quantum_info as qi

U_qc = QuantumCircuit(m)
#U_qc.x(0)
U_qc.initialize('0010')
U_qc.swap(0, 1)
U_qc.swap(1, 2)
U_qc.swap(2, 3)
for q in range(4):
    U_qc.x(q)


#U = U_qc.to_gate()
stv = qi.Statevector.from_instruction(U_qc)
#U.name ='{}Mod{}'.format(7, N)
U_qc.draw('mpl',fold=-1,style=style)

stv.draw('latex', prefix="|\\psi\\rangle =")

def c_amod15(a, power):
    """Controlled multiplication by a mod 15"""
    if a not in [2,4,7,8,11,13]:
        raise ValueError("'a' must be 2,4,7,8,11 or 13")
    U = QuantumCircuit(4)
    for iteration in range(power):
        if a in [2,13]:
            U.swap(2,3)
            U.swap(1,2)
            U.swap(0,1)
        if a in [7,8]:
            U.swap(0,1)
            U.swap(1,2)
            U.swap(2,3)
        if a in [4, 11]:
            U.swap(1,3)
            U.swap(0,2)
        if a in [7,11,13]:
            for q in range(4):
                U.x(q)
    U = U.to_gate()
    U.name = "%i^%i mod 15" % (a, power)
    c_U = U.control()
    return c_U

# Specify variables
n_count = 8  # number of counting qubits
a = 7

def qft_dagger(n):
    """n-qubit QFTdagger the first n qubits in circ"""
    qc = QuantumCircuit(n)
    # Don't forget the Swaps!
    for qubit in range(n//2):
        qc.swap(qubit, n-qubit-1)
    for j in range(n):
        for m in range(j):
            qc.cp(-np.pi/float(2**(j-m)), m, j)
        qc.h(j)
    qc.name = "QFT†"
    return qc


# Create QuantumCircuit with n_count counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(n_count + 4, n_count+ 4)

# Initialize counting qubits
# in state |+>
for q in range(n_count):
    qc.h(q)
# And auxiliary register in state |1>
qc.x(n_count)

qc.barrier()

stv1 = qi.Statevector.from_instruction(qc)
# Do controlled-U operations
for q in range(n_count):
    qc.append(c_amod15(a, 2**q),
             [q] + [i+n_count for i in range(4)])
qc.barrier()
stv2 = qi.Statevector.from_instruction(qc)

#for qubit in range(8,12):
#  qc.measure(qubit,qubit)
qc.barrier()

# Do inverse-QFT
qc.append(qft_dagger(n_count), range(n_count))

# Measure circuit
qc.measure(range(n_count), range(n_count))
style = {'backgroundcolor': 'lightgreen'}
qc.draw('mpl',fold=-1,style=style)  # -1 means 'do not fold'

stv1.draw('latex', prefix="|\\psi\\rangle =")

stv2.draw('latex', prefix="|\\psi\\rangle =")

aer_sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)

import cmath
a = 2
def suma(i):
  b=0
  for a in range(86):
    b+= cmath.exp(-2*np.pi*1j*6*i*a/512)
  return abs(b)**2
dat = [suma(i) for i in range(512)]
probability = np.array(dat)/512/86
import plotly.express as px
fig=px.line(probability,markers=True)
fig.show()


import numpy as np
a=2
N=21
r=6
print("Los factores primos son:",np.gcd(a**(r//2) +1,N),np.gcd(a**(r//2) -1,N))

# Importing everything
from qiskit import QuantumCircuit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
def create_bell_pair():
    """
    Returns:
        QuantumCircuit: Circuit that produces a Bell pair
    """
    qc = QuantumCircuit(2)
    qc.h(1)
    qc.cx(1, 0)
    return qc
def encode_message(qc, qubit, msg):
    """Encodes a two-bit message on qc using the superdense coding protocol
    Args:
        qc (QuantumCircuit): Circuit to encode message on
        qubit (int): Which qubit to add the gate to
        msg (str): Two-bit message to send
    Returns:
        QuantumCircuit: Circuit that, when decoded, will produce msg
    Raises:
        ValueError if msg is wrong length or contains invalid characters
    """
    if len(msg) != 2 or not set(msg).issubset({"0","1"}):
        raise ValueError(f"message '{msg}' is invalid")
    if msg[1] == "1":
        qc.x(qubit)
    if msg[0] == "1":
        qc.z(qubit)
    return qc
def decode_message(qc):
    qc.cx(1, 0)
    qc.h(1)
    return qc
qc = create_bell_pair()

# We'll add a barrier for visual separation
qc.barrier()

# At this point, qubit 0 goes to Alice and qubit 1 goes to Bob

# Next, Alice encodes her message onto qubit 1. In this case,
# we want to send the message '10'. You can try changing this
# value and see how it affects the circuit
message = '10'
qc = encode_message(qc, 1, message)
qc.barrier()
# Alice then sends her qubit to Bob.

# After recieving qubit 0, Bob applies the recovery protocol:
qc = decode_message(qc)

# Finally, Bob measures his qubits to read Alice's message
qc.measure_all()

# Draw our output
qc.draw("mpl")

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))

#initialization
import matplotlib.pyplot as plt
import numpy as np

# importing Qiskit
from qiskit import IBMQ, Aer, assemble, transpile,execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
import qiskit.quantum_info as qi

# import basic plot tools
from qiskit.visualization import plot_histogram

qc = QuantumCircuit(2)
qc.h(0) # Oracle
qc.h(1) # Oracle
qc.cz(0,1) # Oracle
# Diffusion operator (U_s)
qc.h([0,1])
qc.z([0,1])
qc.cz(0,1)
qc.h([0,1])
qc.measure_all()
qc.draw('mpl')

from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1000)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))

from qiskit import QuantumCircuit, transpile, assemble, Aer, execute
import qiskit.quantum_info as qi

def change_sign(circuit, target_state):
    # Aplicar una compuerta de fase controlada para cambiar el signo del estado objetivo
    
    # Crear un circuito auxiliar con un qubit de control y el estado objetivo como objetivo
    aux_circuit = QuantumCircuit(2)
    aux_circuit.x(1)  # Preparar el estado objetivo
    
    # Aplicar una compuerta de fase controlada con el qubit de control en el estado |1⟩
    aux_circuit.cp(-1 * target_state, 0, 1)
    
    # Deshacer la preparación del estado objetivo
    aux_circuit.x(1)
    
    # Agregar el circuito auxiliar al circuito principal
    circuit.compose(aux_circuit, inplace=True)

# Crear el circuito cuántico con n qubits y n bits clásicos
n = 3
circuit = QuantumCircuit(n, n)

# Definir el estado objetivo al que se le cambiará el signo
target_state = 0  # Por ejemplo, cambiamos el signo del componente |0...0⟩

# Aplicar la función change_sign al estado objetivo
change_sign(circuit, target_state)

import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
change_sign(qc, 0)
stv = qi.Statevector.from_instruction(qc)
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style=style)


stv.draw('latex', prefix="|\\psi\\rangle =")

from qiskit import QuantumCircuit, transpile, assemble, Aer, execute
from qiskit.quantum_info import Statevector

# Crear un circuito cuántico con n qubits
n = 3
circuit = QuantumCircuit(n)

# Crear el estado ∑𝑖|𝑖⟩⟨𝑖| como un Statevector
statevector = Statevector.from_label('101')  # Estado inicial |000⟩

# Aplicar el operador de densidad diagonal a los qubits utilizando el initialize method
circuit.initialize(statevector.data, range(n))

# Medir los qubits
circuit.measure_all()

# Simular y ejecutar el circuito
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1)
result = job.result()
counts = result.get_counts(circuit)
print(counts)



from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)

X = iris_data.data[0:100]
y = iris_data.target[0:100]
print(X.shape,y.shape)
for i in range(10):
    print(X[i,0:4],y[i])

from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
    print(X[i,0:4],y[i])

from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals

algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)
for i in range(10):
    print(X_train[i],y_train[i])

import pandas as pd
df = pd.read_csv("heart.csv")

print(df.head())
#print('Number of rows:',df.shape[0], ' number of columns: ',df.shape[1])
X = df.iloc[:,:-1].values
y = df.target.values
print(X.shape,y.shape)

from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
    print(X[i,0:4],y[i])

from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals

algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)

import mglearn
import matplotlib.pyplot as plt
#from matplotlib.pyplot import figure
#figure(figsize=(8, 6), dpi=80)
#plt.rcParams["figure.figsize"] = (8,8)
# generate dataset
X, y = mglearn.datasets.make_forge()
# plot dataset
mglearn.discrete_scatter(X[:, 0], X[:, 1], y)
plt.legend(["Class 0", "Class 1"], loc=4)
plt.xlabel("First feature")
plt.ylabel("Second feature")
print("X.shape:", X.shape)
mglearn.plots.plot_knn_classification(n_neighbors=5)


from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn import datasets
#from skimage import exposure
import numpy as np
import sklearn
for k in range(1,10):
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train, y_train)
    predictions = model.predict(X_test)

    score = np.round(100*model.score(X_test, y_test),1)
    print ('k=',k,'Porcentaje de aciertos:',score)

from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
classifier = SVC(kernel='linear',random_state=0)
classifier.fit(X_train,y_train)
y_pred = classifier.predict(X_test)

accuracy = accuracy_score(y_test,y_pred)
print("Support Vector Machine :")
print("Accuracy = ", accuracy)


import sklearn
import mglearn

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
%matplotlib inline

from IPython.display import display
display(mglearn.plots.plot_logistic_regression_graph())


display(mglearn.plots.plot_single_hidden_layer_graph())


display(mglearn.plots.plot_two_hidden_layer_graph())


from IPython.display import YouTubeVideo

YouTubeVideo('aircAruvnKk', width=800, height=300)

from IPython.display import YouTubeVideo

YouTubeVideo('IHZwWFHWa-w', width=800, height=300)

from IPython.display import YouTubeVideo

YouTubeVideo('Ilg3gGewQ5U', width=800, height=300)

from IPython.display import YouTubeVideo

YouTubeVideo('tIeHLnjs5U8', width=800, height=300)

from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score

classifier = MLPClassifier(solver='lbfgs', alpha=1e-5,
    hidden_layer_sizes=(5, 5,5), random_state=1)
classifier.fit(X_train,y_train)
y_pred = classifier.predict(X_test)

accuracy = accuracy_score(y_test,y_pred)
print("Neural Network Classifier :")
print("Accuracy = ", accuracy)



from sklearn import datasets
import matplotlib.pyplot as plt

digits = datasets.load_digits()
X = np.array(digits.data)
Y = np.array(digits.target)


fig=plt.figure(figsize=(10, 10))
for i in range(16):
    fig.add_subplot(4, 4, i+1)
    j = randint(0, len(y))
    plt.imshow(np.reshape(X[j],(8,8)),cmap=plt.cm.gray_r, interpolation='nearest')
    num = str(y[j])
    plt.title('N='+str(num),fontsize=15)
    plt.xticks(fontsize=10, rotation=90)
    plt.yticks(fontsize=10, rotation=0)

from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
import numpy as np
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
from random import randint

train_fraction = .8
train_len = int(train_fraction*len(X))
print ('Fraccion train:',train_fraction)

digits = datasets.load_digits()
X = np.array(digits.data)
Y = np.array(digits.target)

X_train = X[0:train_len]
Y_train = Y[0:train_len]
X_test = X[train_len:]
Y_test = Y[train_len:]

print ('Data shape:',X.shape)
print ('X_train shape:',X_train.shape)
print ('Y_train shape:',Y_train.shape)
print ('X_test shape:',X_test.shape)
print ('Y_test shape:',Y_test.shape)
for k in range(1,10):
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train, Y_train)
    predictions = model.predict(X_test)

    score = np.round(100*model.score(X_test, Y_test),1)
    print ('k=',k,'Porcentaje de aciertos:',score)


import seaborn as sb
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
model = KNeighborsClassifier(n_neighbors=4)
model.fit(X_train, Y_train)
cm = confusion_matrix(Y_test, model.predict(X_test))
plt.subplots(figsize=(10, 6))
sb.heatmap(cm, annot = True, fmt = 'g')
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()

import matplotlib.pyplot as plt
from random import randint
"""
#############################. 8x8 = 64
from sklearn import datasets
digits = datasets.load_digits()
X = digits.data
y = digits.target
print ( X.shape, y.shape )
#############################. 8x8 = 64
"""
#############################. 28x28 = 784
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X_train = X_train.reshape((60000,784))
X_test = X_test.reshape((10000,784))
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X = X_test
y = y_test
X = X[0:2000]
y = y[0:2000]
#############################. 28x28 = 784
fig=plt.figure(figsize=(10, 10))
for i in range(16):
    fig.add_subplot(4, 4, i+1)
    j = randint(0, len(y))
    #plt.imshow(np.reshape(X[j],(8,8)),cmap=plt.cm.gray_r, interpolation='nearest')
    plt.imshow(np.reshape(X[j],(28,28)),cmap=plt.cm.gray, interpolation='nearest')
    #plt.imshow(np.reshape(X[j],(28,28)),cmap=plt.cm.RdBu, interpolation='nearest')
    num = str(y[j])
    plt.title('N='+str(num),fontsize=15)
    plt.xticks(fontsize=10, rotation=90)
    plt.yticks(fontsize=10, rotation=0)

from sklearn import svm
# Scale data before applying PCA
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler

scaler=StandardScaler()


#############################. 8x8 = 64
from sklearn import datasets
digits = datasets.load_digits()
X = digits.data
y = digits.target
#############################. 8x8 = 64
"""
#############################. 28x28 = 784
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X_train = X_train.reshape((60000,784))
X_test = X_test.reshape((10000,784))
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X = X_test
y = y_test
X = X[0:2000]
y = y[0:2000]
#############################. 28x28 = 784
"""
print ( X.shape,y.shape)

scaler.fit(X)
scaled_data=scaler.transform(X)
# Use fit and transform method
pca = PCA(n_components=3)  # project from 64 to 3 dimensions
projected = pca.fit_transform(scaled_data)
print(projected.shape)
import plotly.express as px
fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2],
                   symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig.update_layout(legend_orientation="h")
fig.update_traces(marker=dict(size=4,
                              line=dict(width=2,
                                        color='DarkSlateGrey')),
                  selector=dict(mode='markers'))
fig.show()

from sklearn import svm
# Scale data before applying PCA
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler

scaler=StandardScaler()
print (X.shape,y.shape)

scaler.fit(X)
scaled_data=scaler.transform(X)
# Use fit and transform method


#tsne = TSNE(n_components=2, random_state=0)
tsne = TSNE(n_components=3, random_state=0)
projected = tsne.fit_transform(scaled_data)

print(projected.shape)
import plotly.express as px

#fig = px.scatter(x=projected[:,0], y=projected[:,1],
#                   symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2],
                   symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig.update_layout(legend_orientation="h")
fig.update_traces(marker=dict(size=8,
                              line=dict(width=2,
                                        color='DarkSlateGrey')),
                  selector=dict(mode='markers'))
fig.show()

import qiskit.tools.jupyter

%qiskit_version_table
%qiskit_copyright


from google.colab import files
uploaded = files.upload()

!ls


import pandas as pd
df = pd.read_csv("heart.csv")

print(df.head())
print('Number of rows:',df.shape[0], ' number of columns: ',df.shape[1])
X = df.iloc[:,:-1].values
y = df.target.values

from sklearn import svm
# Scale data before applying PCA
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler

scaler=StandardScaler()
print (X.shape,y.shape)

scaler.fit(X)
scaled_data=scaler.transform(X)
# Use fit and transform method

#pca = PCA(n_components=2)  # project from 13 to 3 dimensions
pca = PCA(n_components=4)  # project from 13 to 3 dimensions
#tsne = TSNE(n_components=2, random_state=0)
#tsne = TSNE(n_components=3, random_state=0)
projected = pca.fit_transform(scaled_data)
#projected = tsne.fit_transform(scaled_data)

print(projected.shape)
import plotly.express as px

#fig = px.scatter(x=projected[:,0], y=projected[:,1],
#                   symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2],
                   symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig.update_layout(legend_orientation="h")
fig.update_traces(marker=dict(size=8,
                              line=dict(width=2,
                                        color='DarkSlateGrey')),
                  selector=dict(mode='markers'))
fig.show()

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    X,y, random_state=0)
print(X_train.shape,X_test.shape,y_train.shape,y_test.shape)

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn import datasets
#from skimage import exposure
import numpy as np
import sklearn
for k in range(1,10):
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train, y_train)
    predictions = model.predict(X_test)

    score = np.round(100*model.score(X_test, y_test),1)
    print ('k=',k,'Porcentaje de aciertos:',score)


from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    projected, y, random_state=0)
print(X_train.shape,X_test.shape,y_train.shape,y_test.shape)

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn import datasets
#from skimage import exposure
import numpy as np
import sklearn
for k in range(1,10):
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train, y_train)
    predictions = model.predict(X_test)

    score = np.round(100*model.score(X_test, y_test),1)
    print ('k=',k,'Porcentaje de aciertos:',score)


#Import svm model
from sklearn.svm import SVC
print(X_train.shape,X_test.shape,y_train.shape,y_test.shape)
clf = SVC(kernel='rbf',  C=1000, gamma=.1) # Linear Kernel
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
from sklearn import metrics
print("Porcentaje de aciertos:",metrics.accuracy_score(y_test, y_pred))

from sklearn.model_selection import GridSearchCV
# defining parameter range
param_grid = {'C': [0.1,  10,  1000],
              'gamma': [1,  0.01, 0.0001],
              'kernel': ['rbf']}
grid = GridSearchCV(SVC(),param_grid,refit=True,verbose=2)

# fitting the model for grid search
grid.fit(X_train, y_train)

# print best parameter after tuning
print(grid.best_params_)

# print how our model looks after hyper-parameter tuning
print(grid.best_estimator_)

grid_predictions = grid.predict(X_test)

# print classification report
print(classification_report(y_test, grid_predictions))

from qiskit.circuit.library import ZZFeatureMap
from qiskit.circuit.library import ZFeatureMap
from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2


from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute
import numpy as np
def my_circuit1(X, reps_feature_map,theta,rep_ansatz):
  feature_map = ZFeatureMap(feature_dimension=len(X), reps=reps_feature_map)

  qc = QuantumCircuit(len(X),1)
  qc.append(feature_map.decompose(), range(len(X)))
  qc.barrier()

  qc = qc.bind_parameters(X)
  #W = RealAmplitudes(num_qubits=len(X), reps=rep_ansatz)
  W = EfficientSU2(num_qubits=len(X), reps=rep_ansatz)
  #W = W.bind_parameters(theta)
  qc.append(W.decompose(), range(4))

  qc.barrier()
  qc.measure(0, 0)
  return qc

reps_feature_map = 1
rep_ansatz = 1
theta_dim = 4+4*rep_ansatz
#theta = np.zeros(theta_dim)
theta = range(theta_dim)
qc = my_circuit1(X_train[0], 1,theta,rep_ansatz)

qc.decompose().draw(output="mpl", fold=20)


from qiskit import QuantumCircuit

import numpy as np
qc = QuantumCircuit(1)
qc.p(np.pi/2,0)
qc.decompose().draw(output="mpl", fold=20)

from qiskit.circuit.library import ZZFeatureMap,ZFeatureMap

num_features = len(X_train[0])

feature_map = ZFeatureMap(feature_dimension=num_features, reps=1)
feature_map.decompose().draw(output="mpl", fold=20)

from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2
num_features = len(X_train[0])
ansatz = RealAmplitudes(num_qubits=num_features, reps=1)
ansatz.decompose().draw(output="mpl", fold=20)

from qiskit.algorithms.optimizers import COBYLA,SPSA,SLSQP
optimizer = COBYLA(maxiter=60)

from qiskit.primitives import Sampler
sampler = Sampler()

from matplotlib import pyplot as plt
from IPython.display import clear_output
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
def callback_graph(weights, obj_func_eval):
    clear_output(wait=True)
    objective_func_vals.append(obj_func_eval)
    plt.title("Objective function value against iteration")
    plt.xlabel("Iteration")
    plt.ylabel("Objective function value")
    plt.plot(range(len(objective_func_vals)), objective_func_vals)
    plt.show()


import time
from qiskit_machine_learning.algorithms.classifiers import VQC

vqc = VQC(
    sampler=sampler,
    feature_map=feature_map,
    ansatz=ansatz,
    optimizer=optimizer,
    callback=callback_graph,
)

# clear objective value history
objective_func_vals = []

start = time.time()
vqc.fit(X_train, y_train)
elapsed = time.time() - start

print(f"Training time: {round(elapsed)} seconds")

train_score_q4 = vqc.score(X_train, y_train)
test_score_q4 = vqc.score(X_test, y_test)

print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset:     {test_score_q4:.2f}")

from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)

X = iris_data.data[0:100]
y = iris_data.target[0:100]
print(X.shape,y.shape)
for i in range(10):
    print(X[i,0:4],y[i])

from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
    print(X[i,0:4],y[i])

from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals

algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)
for i in range(10):
    print(X_train[i],y_train[i])

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute
import numpy as np
import qiskit.quantum_info as qi
def my_circuit0(X,theta):
  qc = QuantumCircuit(len(X),1) # Ponemos 3 qubits y 1 bit
  # Aplicamos algunas compuertas
  for i,X_i in enumerate (X):
    qc.h(i)
    qc.p(2*X_i,i)
      
  qc.barrier()
    
  for i in range(len(X)):
    qc.ry(theta[i],i)
  for i in range(len(X)-1,0,-1):
    qc.cx(i-1,i)
  for i in range(len(X)):
    qc.rx(theta[i+len(X)],i)
  for i in range(len(X)-1,0,-1):
    qc.cx(i-1,i)
  for i in range(len(X)):
    qc.rx(theta[i+2*len(X)],i)
      
  qc.barrier()
    
  qc.measure(0,0)
  return qc
theta =range(12)
qc = my_circuit0(X_train[0],theta)


qc.draw(output='mpl')

from qiskit.circuit.library import ZZFeatureMap
from qiskit.circuit.library import ZFeatureMap
from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2


from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute
import numpy as np
def my_circuit1(X, reps_feature_map,theta,rep_ansatz):
  feature_map = ZFeatureMap(feature_dimension=len(X), reps=reps_feature_map)

  qc = QuantumCircuit(len(X),1)
  qc.append(feature_map.decompose(), range(len(X)))
  qc.barrier()

  qc = qc.bind_parameters(X)
  W = RealAmplitudes(num_qubits=len(X), reps=rep_ansatz)
  W = W.bind_parameters(theta)
  qc.append(W.decompose(), range(4))

  qc.barrier()
  qc.measure(0, 0)
  return qc
theta = np.zeros(12)
#theta = range(12)
qc = my_circuit1(X_train[0], 1,theta,2)

qc.decompose().draw(output="mpl", fold=20)

def prediction(X,theta,shots):
  #qc=my_circuit1(X, 1,theta,2)
  qc=my_circuit0(X,theta)
  simulator = Aer.get_backend('qasm_simulator')
  job = execute(qc, simulator, shots=shots)
  result = job.result()
  counts = result.get_counts()
  try: counts["0"]
  except: return 0

  else: return counts["0"]/shots
print(prediction(X_train[3],np.zeros(12),1000))

def loss (X,y,theta,shots):
  return (prediction(X,theta,shots)-y)**2
def loss_epoch (n_data,X,y,theta,shots):
    loss_initial = 0
    for i in range(n_data):
        loss_initial += loss (X_train[i],y_train[i],theta,shots)
    return loss_initial/n_data
print(loss(X_train[2],y[2],np.zeros(12),1000))
print(loss_epoch(80,X_train,y_train,np.zeros(12),1000))


def gradient(X,y,theta,shots):
    delta = .01
    grad=np.zeros(len(theta))
    grad=np.zeros(len(theta))
    theta1 = theta.copy()
    L = loss(X,y,theta,shots)
    for j in range(len(theta)):
        theta_new = theta.copy()
        theta_new [j] += delta
        #print(theta,theta_new)
        grad[j]= (loss(X,y,theta_new,shots) -L)/delta
    return grad,L

def gradient_epoch(n_data,X,y,theta,shots):
    delta = .01
    grad=np.zeros(len(theta))
    theta1 = theta.copy()
    L = loss_epoch(n_data,X,y,theta,shots)
    for j in range(len(theta)):
        theta_new = theta.copy()
        theta_new [j] += delta
        #print(theta,theta_new)
        grad [j]=(loss_epoch(n_data,X,y,theta_new,shots) -L)/delta
    return grad,L
theta = np.zeros(12)
shots = 10000
eta = 1
grad, L = gradient(X_train[2],y_train[2],theta,shots)
print(theta)
theta = theta - eta*grad
print(theta)
theta = np.zeros(12)
grad, L = gradient_epoch(80,X_train,y_train,theta,shots)
print(theta)
theta = theta - eta*grad
print(theta)
    


def accuracy (N_points,X,y,theta,shots):
  acc = 0
  for i in range(N_points):
    #print(prediction(X[i],theta,shots), y[i])
    if (np.round(prediction(X[i],theta,shots),0) == y[i]): acc += 1
  return (acc/N_points)
accuracy (20,X_train,y_train,theta,shots)

shots = 1000
n_data = 80

eta = 1
n_epochs = 50
from matplotlib import pyplot as plt
from IPython.display import clear_output
theta = np.zeros(12)
loss_initial = 0
for i in range(n_data):
 loss_initial += loss(X_train[i],y_train[i],theta,shots)
mean_loss = [loss_initial/n_data]
acc_list = [accuracy (20,X_test,y_test,theta,shots)]
plt.rcParams["figure.figsize"] = (12, 6)


def graph(mean_loss,acc_list):
    clear_output(wait=True)
    fig, ax1 = plt.subplots()

    ax2 = ax1.twinx()
    ax1.plot(range(len(mean_loss)), mean_loss, 'g-')
    ax2.plot(range(len(mean_loss)), acc_list, 'b-')
    
    ax1.set_xlabel('Iteraciones sobre los Datos')
    ax1.set_ylabel('Función Loss', color='g')
    ax2.set_ylabel('Porcentaje de Aciertos en Test', color='b')
    
    plt.show()
    

for j in range(n_epochs):
    if (j>0 and j%5 == 0): eta = eta/2
    tot_loss = 0
    for i in range(n_data):
        grad, L = gradient(X_train[i],y_train[i],theta,shots)
        theta = theta - eta * grad
        tot_loss += L
    mean_loss.append(tot_loss/n_data)
    acc_list.append(accuracy (20,X_test,y_test,theta,shots))
    graph(mean_loss,acc_list)


    

shots = 1000
n_data = 80

eta = 1
n_epochs = 50
from matplotlib import pyplot as plt
from IPython.display import clear_output
theta = np.zeros(12)
loss_initial = 0
for i in range(n_data):
 loss_initial += loss (X_train[i],y_train[i],theta,shots)
mean_loss = [loss_initial/n_data]
acc_list = [accuracy (20,X_test,y_test,theta,shots)]
plt.rcParams["figure.figsize"] = (12, 6)



def graph(mean_loss,acc_list):
    clear_output(wait=True)
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.plot(range(len(mean_loss)), mean_loss, 'g-')
    ax2.plot(range(len(mean_loss)), acc_list, 'b-')
    ax1.set_xlabel('Iteraciones sobre los Datos')
    ax1.set_ylabel('Función Loss', color='g')
    ax2.set_ylabel('Porcentaje de Aciertos en Test', color='b')
    plt.show()
    

for j in range(n_epochs):
    if (j>0 and j%5 == 0): eta = eta/2
    grad, L = gradient_epoch(80,X_train,y_train,theta,shots)
    theta = theta - eta * grad
    mean_loss.append(L)
    acc_list.append(accuracy (20,X_test,y_test,theta,shots))
    graph(mean_loss,acc_list)
  


plt.title("Accuracy for X_test against iteration")
plt.xlabel("Iteration")
plt.ylabel("Accuracy")
plt.plot(range(len(acc_list)), acc_list)
plt.grid()
plt.show()

from sklearn.datasets import load_iris

iris_data = load_iris()

print(iris_data.DESCR)

X = iris_data.data[0:100]
y = iris_data.target[0:100]
print(X.shape,y.shape)
for i in range(10):
    print(X[i,0:4],y[i])

from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
    print(X[i,0:4],y[i])

from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals

algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)

from qiskit.circuit.library import ZZFeatureMap,ZFeatureMap

num_features = X.shape[1]

feature_map = ZFeatureMap(feature_dimension=num_features, reps=2)
feature_map.decompose().draw(output="mpl", fold=20)

from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2


ansatz = EfficientSU2(num_qubits=num_features, reps=1)
ansatz.decompose().draw(output="mpl", fold=20)

from qiskit.algorithms.optimizers import COBYLA # Constrained Optimization By Linear Approximation optimizer.
# https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.COBYLA.html
from qiskit.algorithms.optimizers import SPSA # Simultaneous Perturbation Stochastic Approximation optimizer
# https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.SPSA.html
from qiskit.algorithms.optimizers import SLSQP # Sequential Least SQuares Programming optimizer
# https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.SLSQP.html
optimizer = COBYLA(maxiter=100)

from qiskit.primitives import Sampler

sampler = Sampler()

from matplotlib import pyplot as plt
from IPython.display import clear_output

objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)


def callback_graph(weights, obj_func_eval):
    clear_output(wait=True)
    objective_func_vals.append(obj_func_eval)
    plt.title("Objective function value against iteration")
    plt.xlabel("Iteration")
    plt.ylabel("Objective function value")
    plt.plot(range(len(objective_func_vals)), objective_func_vals)
    plt.grid()
    plt.show()

import time
from qiskit_machine_learning.algorithms.classifiers import VQC

vqc = VQC(
    sampler=sampler,
    feature_map=feature_map,
    ansatz=ansatz,
    optimizer=optimizer,
    callback=callback_graph,
)

# clear objective value history
objective_func_vals = []

start = time.time()
vqc.fit(X_train, y_train)
elapsed = time.time() - start

print(f"Training time: {round(elapsed)} seconds")

train_score_q4 = vqc.score(X_train, y_train)
test_score_q4 = vqc.score(X_test, y_test)

print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset:     {test_score_q4:.2f}")

from qiskit.utils import algorithm_globals

algorithm_globals.random_seed = 12345

from qiskit_machine_learning.datasets import ad_hoc_data

adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
    training_size=20,
    test_size=5,
    n=adhoc_dimension,
    gap=0.3,
    plot_data=False,
    one_hot=False,
    include_sample_total=True,
)

import matplotlib.pyplot as plt
import numpy as np


def plot_features(ax, features, labels, class_label, marker, face, edge, label):
    # A train plot
    ax.scatter(
        # x coordinate of labels where class is class_label
        features[np.where(labels[:] == class_label), 0],
        # y coordinate of labels where class is class_label
        features[np.where(labels[:] == class_label), 1],
        marker=marker,
        facecolors=face,
        edgecolors=edge,
        label=label,
    )
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):

    plt.figure(figsize=(5, 5))
    plt.ylim(0, 2 * np.pi)
    plt.xlim(0, 2 * np.pi)
    plt.imshow(
        np.asmatrix(adhoc_total).T,
        interpolation="nearest",
        origin="lower",
        cmap="RdBu",
        extent=[0, 2 * np.pi, 0, 2 * np.pi],
    )

    # A train plot
    plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")

    # B train plot
    plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")

    # A test plot
    plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")

    # B test plot
    plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")

    plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
    plt.title("Ad hoc dataset")

    plt.show()

plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)

from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel

adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")

sampler = Sampler()

fidelity = ComputeUncompute(sampler=sampler)

adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)

adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)

fig, axs = plt.subplots(1, 2, figsize=(10, 5))

axs[0].imshow(
    np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")

axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")

plt.show()

from sklearn.svm import SVC
adhoc_svc = SVC(kernel="precomputed")

adhoc_svc.fit(adhoc_matrix_train, train_labels)

adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)

print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")


from qiskit_machine_learning.algorithms import QSVC

qsvc = QSVC(quantum_kernel=adhoc_kernel)

qsvc.fit(train_features, train_labels)

qsvc_score = qsvc.score(test_features, test_labels)

print(f"QSVC classification test score: {qsvc_score}")

from IPython.display import IFrame
IFrame("https://arxiv.org/pdf/1304.3061.pdf", width=600, height=300)

!pip install  pyscf
!pip install --upgrade qiskit-nature

from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.mappers import DirectMapper
from qiskit_nature.second_q.problems import HarmonicBasis
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
#from qiskit_nature.drivers import PySCFDriver
from qiskit_nature.second_q.drivers import PySCFDriver
import matplotlib.pyplot as plt
import numpy as np

#driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
n=40 # Numero de puntos +1
d = [0.735*i/10 for i in range(1,n)]
atom_array = [ "H 0 0 0; H 0 0 " + str(0.735*i/10) for i in range(1,n)]
E =[]
for i in  range(0,n-1):
  driver = PySCFDriver(
      #atom="H 0 0 0; H 0 0 0.735",
      atom=atom_array[i],
      basis="sto3g",
      charge=0,
      spin=0,
      #unit=DistanceUnit.ANGSTROM,
  )
  #basis = HarmonicBasis([2, 2, 2, 2])
  vib_problem = driver.run()
  vib_problem.hamiltonian.truncation_order = 2

  mapper = DirectMapper()

  solver_without_filter = NumPyMinimumEigensolver()
  #solver_with_filter = NumPyMinimumEigensolver(
  #    filter_criterion=vib_problem.get_default_filter_criterion())

  gsc_wo = GroundStateEigensolver(mapper, solver_without_filter)
  result_wo = gsc_wo.solve(vib_problem)

  #gsc_w = GroundStateEigensolver(mapper, solver_with_filter)
  #result_w = gsc_w.solve(vib_problem)
    

  #print(result_wo)
  #print(f"Total ground state energy = {result_wo.total_energies[0]:.4f}")

  #print("\n\n")
  #print(result_w)
  E.append(result_wo.total_energies[0])
plt.figure(figsize=(10, 6))
#print (E)
plt.plot(d,E,  '--bo', label='Energías vs distance')
plt.grid()
print ("Energía mininima =", np.round(min(E),5), " para d =", d[E.index(min(E))])

from IPython.display import YouTubeVideo

YouTubeVideo('_ediOdFUr10', width=800, height=300)

import pennylane as qml
import numpy as np

symbols = ["H", "H"]
#coordinates = np.array([0.0, 0.0, 0, 0.0, 0.0, 0.735])# in Angtrons
coordinates =  np.array([0.0, 0.0, 0.0, 0.0, 0.0, 1.3889487])# in au
import pennylane as qml

H, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates)
print("Number of qubits = ", qubits)
print("The Hamiltonian is ", H)

dev = qml.device("default.qubit",wires=qubits)
@qml.qnode(dev)
def energy(state):
    qml.BasisState(np.array(state),wires=range(qubits))
    return qml.expval(H)
energy([1,1,0,0])
hf =qml.qchem.hf_state(electrons = 2, orbitals = 4)
print("Estado de Hartree-Fock:", hf)
print("Energía del estado base=",energy(hf),"Ha")
print("Energía del estado base=",energy(hf)* 27.211386245988,"eV")