Search code examples
pythonimporterrorqiskit

How can I import a .py file in IBM Quantum Lab?


I created a separate Python file for numerical calculations when implementing a quantum circuit. Now, I'm trying to use IBM Quantum Lab to apply this code to a circuit using Qiskit.

%matplotlib inline

import math
import decomposition_2qubit as d2
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
from qiskit.extensions import *
from qiskit.quantum_info import Statevector

matrix = (1/2)*np.array([
[1,1,1,1],
[1,-1,1,-1],
[1,1,-1,-1],
[1,-1,-1,1]])

qc = QuantumCircuit(2,2)
#qc.x(0)
#qc.x(1)
qc.barrier()

d2.twoqubit_to_single(qc, matrix)

ket = Statevector(qc)
ket.draw('latex')

qc.draw('mpl')

However, when I try to import the decomposition_2qubit.py file, I encounter this error. How can I resolve this?

Traceback (most recent call last):
  Cell In[1], line 4
    import decomposition_2qubit as d2
ModuleNotFoundError: No module named 'decomposition_2qubit'

Use %tb to get the full traceback.

I have the 'decomposition_2qubit.py' file located in the same folder as the current Jupyter Notebook file I am using. Additionally, since IBM Quantum Lab appears to use Jupyter Notebook as its base, I tried searching for solutions when encountering such errors in Jupyter Notebook, but unfortunately, I couldn't resolve the issue.


Solution

  • You are probably facing an issue with the file path. As suggested here, you can either specify your own import path explicitly or just prepend path modifiers like .. and/or /.