Visualizing circuits in qiskit with matplotlib - python

I'm learning how to use qiskit and I'm using the jupyter notebook, but everytime I try to visualize the circuit with the attribute draw I get this error:
import qiskit
from qiskit import *
from qiskit import IBMQ
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw(output='mpl')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-bd220039ee1c> in <module>
----> 1 circuit.draw(output='mpl')
AttributeError: module 'qiskit.circuit' has no attribute 'draw'
I also try applying a Hadamard gate and I get:
circuit.h(qr(0))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-59-c8b4318b743b> in <module>
----> 1 circuit.h(qr(0))
AttributeError: module 'qiskit.circuit' has no attribute 'h'

It seems that there is a name conflict. It is taking the circuit in from qiskit import circuit instead of circuit = ....
You just probably need to restat your notebook kernel.

Try another name for your circuit variable, right now python thinks you want the qiskit.circuit module to draw something. QuantumCircuit objects are the ones that have a draw method. You can see these two objects here if you call both, note I put one qubit and classical bit in the QuantumCircuit just per example as well you do not need the dots here it is just to make it more clear, just running circuit and QuantumCircuit(1,1) respectively would yield the same result.
You would get desired results if you tried a different variable name:
When I try using the variable name circuit it works for me, but try to use descriptive variable names that also could never be confused with modules or classes from the packages you import.
Also all your import statements can be combined into 1:
from qiskit import *
The star lets you import everything from qiskit including IBMQ. It can help you save a line or two.

Related

AttributeError: 'DatasetSeries' object has no attribute 'all_data'

import glob
from os.path import join
import yt
from yt.config import ytcfg
path = ytcfg.get("yt", "test_data_dir")
from mpl_toolkits.mplot3d import Axes3D
my_fns = glob.glob(join(path, "Orbit", "puredef_hdf5_chk_000000"))
my_fns.sort()
fields = ["particle_velocity_x", "particle_velocity_y", "particle_velocity_z"]
ds = yt.load(my_fns[:])
dd = ds.all_data()
indices = dd["particle_index"].astype("int")
print (indices)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-27-1bae40a7b7ba> in <module>
1 ds = yt.load(my_fns[:])
----> 2 dd = ds.all_data()
3 indices = dd["particle_index"].astype("int")
4 print (indices)
AttributeError: 'DatasetSeries' object has no attribute 'all_data'
I have looked at other posts on here, but many of them deal with different aspects of this error that deals with lens or other statements.
I had exactly the same error recently, with a very similar code. First of all, a mistake I did was giving the code the symbolic links to the real data files, while it should work directly with the data.
Another issue was a problem with the installation of the yt library, version 3.6.1. I had installed it using the pip command, but it wasn't working well, so I uninstalled it and I used the "all-in-one" script they provide on their homepage.
Fixing these two things together solved completely this problem.

unable to import normalize_corpus python 3

I am working on some NLP task, trying to import normalize_corpus from the normalization module.
I am getting the below error.
from normalization import normalize_corpus
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-13-5919bba55473> in <module>()
----> 1 from normalization import normalize_corpus
ImportError: cannot import name 'normalize_corpus'
The normalization module you have installed (probably https://pypi.org/project/normalization/) does not correspond to the code you are trying to run (possibly from "Text Analytics with Python").
Uninstall the normalization module and track down the code from the book. (A place to start: https://github.com/dipanjanS/text-analytics-with-python)
For whoever lands here because you are reading "Text analytics with Python". The author of the book is referring to a custom script they built and is hosted in the first edition - chapter 4 or 5 -
https://github.com/dipanjanS/text-analytics-with-python/blob/master/Chapter-4/normalization.py
https://github.com/dipanjanS/text-analytics-with-python/blob/b4f6cefc9dd96e2a3e74e01bda391019bd7fb053/Old-First-Edition/Ch05_Text_Summarization/normalization.py

jupyter notebook/lab fails on imported function

I have a boolean subsetting function that works on a pandas dataframe:
def operational(df):
return df[(df['cf'] != 0) & (df['ta'] > 0)]
it works well in a script and in a jupiter notebook, when entered in cell:
#df = ...
df2 = operational(df)
However, if I keep function definiton in pick.py and import in to jupyter, things go unexpected. It seems upon import of a module jupiter does not reconise the types of variables inside a function:
import pick
pick.operational(df).head()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-374442fd7c0a> in <module>()
1 import pick
----> 2 pick.operational(df).head()
C:\Users\Евгений\Documents\GitHub\sandbox\pick.py in operational(_df)
11
12 def operational(df):
---> 13 return df[(df['cf'] != 0) & (df['ta'] > 0)]
14
15
TypeError: 'method' object is not subscriptable
Is importing something to notebook a generally bad idea? I use jupiter lab, if that matters.
Okay, from the comments it sounds like you were expecting the notebook to automatically pick up changes in an imported script. By default, Python caches imports, so most of the time changes to imported modules won't get picked up until you restart Python.
Fortuitously, Jupyter notebooks run on IPython, which supplies a code reloading cell magic. All you need to do is run:
%autoreload 2
in any cell, and your notebook should, from then on, automatically pick up any changes in pick.py as you make them (you still have to save the changes to disk before the reload magic can see them, of course).

Different import syntaxes not equivalent?

I tried two different import syntaxes I thought were equivalent. Weirdness seems to ensue:
In [7]: import sympy
In [8]:sympy.physics.units.find_unit("Giga Electron Volt")
Traceback (most recent call last):
File "<ipython-input-8-8a26ac4a085a>", line 1, in <module>
sympy.physics.units.find_unit("Giga Electron Volt")
AttributeError: 'module' object has no attribute 'physics'
In [9]:import sympy.physics.units as u
In [10]:u.find_unit("coul")
Out[10]: ['coulomb', 'coulombs']
In [11]:import sympy
In [12]:sympy.physics.units.find_unit("coul")
Out[12]: ['coulomb', 'coulombs']
Take a look at the source code of sympy here: https://github.com/sympy/sympy/blob/master/sympy/init.py#L55
from .calculus import *
# Adds about .04-.05 seconds of import time
# from combinatorics import *
# This module is slow to import:
#from physics import units
from .plotting import plot, textplot, plot_backends, plot_implicit
They are not importing the physics module, because it takes obviously quite some time to load. This is why you get the error in the first try.
After loading it manually, the interpreter has it loaded and knows where it is (from your manual import). Thats why it works on the second try.
So the phenomenon is not regarded to python import functionality, but to the module initialization.
P.S.
If you uncomment the line that loads unit from the physics module, it would be
import sympy
sympy.units.find_unit("coul")

Random Gaussian issues

I'm trying to generate a random.gauss numbers but I have message error. Here is my code:
import sys,os
import numpy as np
from random import gauss
previous_value1=1018.163072765074389
previous_value2=0.004264112033664
alea_var_n=random.gauss(1,2)
alea_var_tau=random.gauss(1,2)
new_var_n= previous_value1*(1.0+alea_var_n)
new_var_tau=previous_value2*(1.0+alea_var_tau)
print 'new_var_n',new_var_n
print 'new_var_tau',new_var_tau
I got this error:
Traceback (most recent call last):
File "lolo.py", line 15, in <module>
alea_var_n=random.gauss(1,2)
AttributeError: 'builtin_function_or_method' object has no attribute 'gauss'
Someone know what's wrong, I'm a newbye with python. Or is it a numpy version problem.
For a faster option, see Benjamin Bannier's solution (which I gave a +1 to). Your present code that you posted will not work for the following reason: your import statement
from random import gauss
adds gauss to your namespace but not random. You need to do this instead:
alea_var_n = gauss(1, 2)
The error in your post, however, is not the error you should get when you run the code that you have posted above. Instead, you will get the following error:
NameError: name 'random' is not defined
Are you sure you have posted the code that generated that error? Or have you somehow included the wrong error in your post?
Justin Barber shows you an immediate solution for your problem.
Since you are using NumPy you could however use their generators as well since they appear to be significantly faster (about a factor 5-7 on my machine), e.g.
alea_var_n = np.random.normal(1, 2)

Categories

Resources