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

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.

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.

Error with oct2py when the octave function have load param

I'm using oct2py to call a octave function in my python code. Everything should be OK, and the octave function exectuted with octave works but when I call the function with python I have this error:
import os
pathToExecutable = ('C:\\Octave\\Octave-5.2.0\\mingw64\\bin\\octave-cli.exe')
os.environ['OCTAVE_EXECUTABLE'] = pathToExecutable
from oct2py import octave
import pprint
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
octave.addpath(octave.genpath('E:/funcs/software/octave_calls'))
octave.eval('MSPP')
Oct2PyError: Octave evaluation error: error: 'AvgPwr' undefined near
line 22 column 15 error: called from:
MSPP at line 22, column 8
The octave code in this line is the next:
Power=AvgPwr
When AvgPower is defined when I import it from a .mat file with
load params.mat %<--transcription corrected (before it was load(params.mat)
EDIT:
First lines of MSSP.
warning off
close all;
clear all;
clc;
%% Load pameters
load params.mat
################################################################################
%% CW Laser
Plaser = 10^((AvgPwr-30)/10); % Average Laser Power
emzm = 1.0;
params.mat is generated in another octave file where I load all parameters and it contains the variable AvgPwr, I think it's everything correct with the octave code because it works well when I use octave to run it.

Name error when calculating the average error between two data sets

I want to calculate the average error between two data sets and write the result to a file but my code gives this error:
NameError: name 'first1' is not defined
Could you please tell me how to fix this error?
The command I use to run the code is here:
python script.py input1.txt input2.txt > output.txt
My code:
import numpy
from numpy import *
import scipy
import scipy.stats
import matplotlib. pyplot as plt
import matplotlib.patches as patches
from pylab import *
import scipy.integrate
from operator import itemgetter, attrgetter
import sys
def main(argv):
t = open(sys.argv[1])
first1 = t.readline()
tt = open(argv[2])
second2 = tt.readline()
return [first1], [second2]
def analysis(first1, second2):
first = np.array(first1, dtype = np.float64)
second = np.array(second2, dtype = np.float64)
#Average error
avgerr = (first - second).mean()
return [avgerr]
analysis(first1, second2)
if __name__ == '__main__':
sys.exit(main(sys.argv))
input1.txt:
2.5
2.8
3.9
4.2
5.8
input2.txt:
0.8
2.5
3.2
5.8
6.3
Where are you stuck on this? The first active statement executed in your main program is
analysis(first1, second2)
Neither of those variables is defined anywhere in the main program.
That's why you get the error. The sequence you have is something like this:
import stuff
define (but don't execute) main function
define (but don't execute) analysis function
call analysis, giving it variables first1 & second2
Again, those variables are not defined yet.
Your line:
analysis(first1, second2)
Is causing the error. This is because you are calling the function without providing values.
The way you have structured your code is it's expected to be run via command line.
If you want to test your script without using command line, you could change your code line above to..
analysis('input1.txt', 'input2.txt')

statsmodels package code works in spyder's ipython console but not in python script

This is a python script in the Spyder IDE of Anaconda. I have Python 3.6.2. The last two lines do nothing (apparently) when I run the script, but work if I type them in the IPython console of Spyder. How do I get them to work in the script please?
# import packages
import os # misc operating system functions
import sys # system parameters and functions
import pandas as pd # data frame handling
import statsmodels.formula.api as sm # stats module
import matplotlib.pyplot as plt # matlab-like plotting
import numpy as np # big, fast arrays for maths
# set working directory to here
os.chdir(os.path.dirname(sys.argv[0]))
# read data using pandas
datafile = '1314 Powerview Pasture Potential.csv'
data1 = pd.read_csv(datafile)
#list(data) # to show column names
# plot some data
# don't know how to pop out a separate window
plt.scatter(data1['long'],data1['lat'],s=40,facecolors='none',edgecolors='b')
# simple multiple regression
Y = data1[['Pasture and Crop eaten t DM/ha']]
X = data1[['Net imported Supplements per Ha',
'LWT/ha',
'lat']]
result = sm.OLS(Y,X).fit()
result.summary()

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

Categories

Resources