Different import syntaxes not equivalent? - python

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")

Related

Scipy strange import behaviour

Scipy has an different way of handling submodules to Numpy, for example
import scipy as sp
import numpy as np
A = np.eye(4)
np.linalg.det(A)
sp.linalg.det(A)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'scipy' has no attribute 'linalg'
This is moderately annoying because of the asymmetry with respect to Numpy, but it is exactly the behaviour that the documentation describes. The proper usage according to the docs is
from scipy import linalg
import numpy as np
A = np.eye(4)
np.linalg.det(A)
linalg.det(A) # using Scipy
which works just fine.
Now, here's the weird thing
import scipy as sp
import numpy as np
from scipy.linalg import expm # extra line inserted into first example
A = np.eye(4)
np.linalg.det(A)
sp.linalg.det(A)
then the Numpy-style code works just fine. The extra line causes linalg to be added to the namespace sp, a side effect of the extra import.
I get the programming pattern I want but the third line is not easy to explain in example code.
QUESTION: why does Scipy do this? is there any more straightforward way to have it so that Scipy behaves more Numpyish?
In fact, you almost never need or to want import scipy as sp or anything like that.
There is almost nothing in the top level scipy namespace. All useful stuff is in subpackages (one exception is LowLevelCallable which is in the top-level namespace). This way, users are better off either importing from subpackages, from scipy.signal import detrend, or importing subpackages themselves (from scipy import signal; signal.detrend(...)).
As to the disparity with numpy, numpy is very much the opposite: a lot of useful stuff is in the top-level namespace, so you import it from there.
Unless you're using np.linalg, np.random, np.fft or np.testing, which are public-facing usable submodules.

Visualizing circuits in qiskit with matplotlib

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.

Why can't I import statsmodels directly?

I'm certainly missing something very obvious here, but why does this work:
a = [0.2635,0.654654,0.365,0.4545,1.5465,3.545]
import statsmodels.robust as rb
print rb.scale.mad(a)
0.356309343367
but this doesn't:
import statsmodels as sm
print sm.robust.scale.mad(a)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-1ce0c872b0be> in <module>()
----> 1 print statsmodels.robust.scale.mad(a)
AttributeError: 'module' object has no attribute 'robust'
Long answer see http://www.statsmodels.org/stable/importpaths.html
Statsmodels has intentionally mostly empty __init__.py but has a parallel import collection through the api.py.
The recommended import for interactive work import statsmodels.api as sm imports almost all of statsmodels, numpy, pandas and patsy, and large parts of scipy. This is slooow on cold start.
If we want to import just a specific part of statsmodels, then we don't need to import all these extras. Having empty __init__.py means that we can import just a single module (which of course imports the dependencies of that module).
e.g. from statsmodels.robust.scale import mad or
import statmodels.robust scale as smscale
smscale.mad(...)
(Small caveat: Some of the very low level imports might not remain always backwards compatible if the internal structure changes. However, the general policy is to deprecate functions over one or two releases while maintaining the old access structure.)
You can, you just have to import robust as well:
import statsmodels as sm
import statsmodels.robust
Then:
>>> sm.robust.scale.mad(a)
0.35630934336679576
robust is a subpackage of statsmodels, and importing a package does not in general automatically import subpackages (unless the package is written to do so explicitly).

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)

Why am I getting NameError: name 'array' is not defined

I'm using spyder and have written the following class:
class Ray:
def __init__(self, r, p, k):
if r.shape == (3,):
self.r = r
if p.shape == (3,):
self.p = p
if k.shape == (3,):
self.k = k
r = array(range(3))
p = array(range(3))
k = array(range(3))
It is stored in /home/user/workspace/spyder/project and the console working directory is that one. In the console I can run an array(range(3)) and it returns an array with values 0,1,2. However when doing
import ray
I get the following error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ray.py", line 8, in <module>
class Ray:
File "ray.py", line 20, in ray
r = array(range(3));
NameError: name 'array' is not defined
EDIT:
by default spyder has the following behaviour, don't really understand why array() works by default I thought it was only part of numpy.
import numpy as np # NumPy (multidimensional arrays, linear algebra, ...)
import scipy as sp # SciPy (signal and image processing library)
import matplotlib as mpl # Matplotlib (2D/3D plotting library)
import matplotlib.pyplot as plt # Matplotlib's pyplot: MATLAB-like syntax
from mayavi import mlab # 3D plotting functions
from pylab import * # Matplotlib's pylab interface
ion() # Turned on Matplotlib's interactive mode
Within Spyder, this intepreter also provides:
* special commands (e.g. %ls, %pwd, %clear)
* system commands, i.e. all commands starting with '!' are subprocessed
(e.g. !dir on Windows or !ls on Linux, and so on)
You need from numpy import array.
This is done for you by the Spyder console. But in a program, you must do the necessary imports; the advantage is that your program can be run by people who do not have Spyder, for instance.
I am not sure of what Spyder imports for you by default. array might be imported through from pylab import * or equivalently through from numpy import *. If you want to directly copy code from the Spyder console to a program, you might need from numpy import * or even from pylab import *. It is officially not recommended to do this in a program, though, as this pollutes the program's namespace; doing import numpy as np and then np.array(…) is customary.

Categories

Resources