Apparent creation of array from another array? - python

I have the following code snippet from SciPy:
resDat = data[scipy.random.randint(0,N,(N,))]
What I try to understand is how and why this line works. the randint function seems to return a list of N integer values in the range of the data indizes, so what I interpret this line of code to do is that resDat will become an array with N random values from data.
I tried to replicate this in the Python shell:
a=[1,2,3,4,5,6]
b=[1,2]
c=a[b]
However if I try this I get - on line 3 - the error
TypeError: list indices must be integers, not list
Which to my knowledge means, that I need to give it a number instead of a list. But why is the line at the top working then? I have the feeling I am missing some important distinction, but can't figure out which one.
Coming from a mainly .NET background the first line looks a bit like a LinQ statement, but is it comparable?

I believe data would be of type -
numpy.ndarray
You can do type(data) it should comes out as numpy.ndarray .
Also , scipy.random.randint() also returns a value of type numpy.ndarray .
You may not be able to do lst[[1,2]] , but you can use numpy.ndarray as a subscript to another numpy.ndarray .
A Simple example -
import numpy as np
data = np.array([10,15,20,25,30])
print(data[np.array([1,2,3])])
>> array([15,20,25])

Related

TypeError: size; expecting a recognized type filling string dict

I have been working on Python script for Abaqus and it has to do with dynamic changes in the parameters of the model. The script opens up a .txt file and reads different values. The values are separated using tabs and I am using split() function of the Abaqus-Python to read the values properly once I have assigned them to a list.
The last index is [5] and it contains mesh size, again a float value. The structure is properly drawn in ABAQUS, the only error it throws me is while assigning the mesh size:
File "C:/Users/ANANT/PyCharmProjects/test_final/test_copy.py", line 104, in <module>
beamPart.seedPart(deviationFactor=0.1, minSizeFactor=0.1, size=mesh)
TypeError: size; found 'module', expecting a recognized type filling string dict
So I tried using repr() to make it a string, but I was it will throw me that the input should be float/integer value and it did exactly the same. Now I am stuck and I can't work any further. I even tried to truncate the float value to 3-decimal points for the mesh size, but it would still throw the same error.
Any help is much appreciated, thanks a lot :)
input file with truncated mesh size
The error message says that seedPart expects a size argument that fulfills the requirement "a recognized type filling string dict". I don't know what this means, but the example here is:
p.seedPart(size=2.0)
So you probably need a float. But mesh is a module. You probably have something like:
import mesh
Or:
import ... as mesh
in your code.
Try to print mesh before the line that raises the error.
so, the 'size=mesh' parameter passed is apparently not of correct type. mesh is of type 'module'. is this intended?

Treating two arrays depending on one another without using loops, TypeError: only size-1 array can be converted to Python scalars

i'm new to python and i've been searching for a while though I didn't find any answer. The start of the code is:
import numpy as np
import matplotlib.pyplot as plt
NTAB=np.array([25,40,60,100,160,250,400,600])
x,h=np.linspace(0,3,NTAB,retstep=True)
I need the value of x depending on NTAB. Obviously python is giving me the error:
TypeError: only size-1 arrays can be converted to Python scalars
I don't want to use a loop to find the value. I tried many ways including defining original functions but it's still giving me the same error. What am I missing?
Thanks a lot!
The third argument of np.linspace is num which is the number of samples to be generated in the specified interval. This must be a positive integer.
So, try passing a scalar value instead:
In [43]: NTAB=np.array([25,40,60,100,160,250,400,600])
In [44]: x,h=np.linspace(0,3,NTAB[0],retstep=True)

Cannot cast array data from dtype('O') to dtype('float64')

I am using scipy's curve_fit to fit a function to some data, and receive the following error;
Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
which points me to this line in my code;
popt_r, pcov = curve_fit(
self.rightFunc, np.array(wavelength)[beg:end][edgeIndex+30:],
np.dstack(transmitted[:,:,c][edgeIndex+30:])[0][0],
p0=[self.m_right, self.a_right])
rightFunc is defined as follows;
def rightFunc(self, x, m, const):
return np.exp(-(m*x + const))
As I understand it, the 'O' type refers to a python object, but I can't see what is causing this error.
Complete Error:
Any ideas for what I should investigate to get to the bottom of this?
Just in case it could help someone else, I used numpy.array(wavelength,dtype='float64') to force the conversion of objects in the list to numpy's float64. Works well for me.
Typically these scipy functions require parameters like:
curvefit( function, initial_values, (aux_values,), ...)
where the tuple of aux_values is passed through to your function along with the current value of the main variable.
Is the dstack expression this aux_values? Or a concatenation of several. It may need to be wrapped in a tuple.
(np.dstack(transmitted[:,:,c][edgeIndex+30:])[0][0],)
We may need to know exactly where this error arises, not just which line of your code does it. We need to know what value is being converted. Where is there an array with dtype object?
Just to clarify, I had the same problem, did not see the right answers in the comments, before solving it on my own. So I just repeat them here:
I have resolved the issue. I was passing an array with one element to the p0 list, rather than the element itself. Thank you for your help – Jacobadtr Sep 12 at 17:51
An O dtype often results when constructing an array from a list of sublists that differ in size. If np.array(...) can't make a clean n-d array of numbers, it resorts to making an array of objects. – hpaulj Sep 12 at 17:15
That is, make sure that the tuple of parameters you pass to curve_fit can be properly casted to an numpy array
From here, apparently numpy struggles with index type. The proposed solution is:
One thing you can do is use np.intp as dtype whenever things have to do with indexing or are logically related to indexing/array sizes. This is the natural dtype for it and it will normally also be the fastest one.
Does this help?

Python SciPy FFT function - Input?

I am currently writing some code which is supposed to perform FFT on a set of data. I have a python list of points and I can easily create a time list. When I run fft(datalist), I get the 'TypeError: 'numpy.ndarray' object is not callable' error. I think (but please correct me) the issue is that the list is one dimension and they have no attachment to time at all by using that one line of code above. My question is, do I have to input a two dimensional array with time and data points? or am I completely wrong and have to rethink?
Thanks, Mike
Edit - forgot to add some code. The t=time. Could it be because the number of entries in the array isnt equal to 2^n where N is an integer?
sample_rate=10.00
t=r_[0:191.6:1/sample_rate]
S = fft([mylist])
print S
The Numpy and SciPy fft functions are looking to have numpy arrays as input, not native python lists. Also they work just fine with lengths that are not powers of two. You probably just need to cast your list as an array before passing it to the fft.
From your example code above try:
from numpy.fftpack import fft
from numpy import array
""" However you generate your list goes here """
S = fft(array([mylist]))

MATLAB to Python Conversion, matrices and lists

How would I translate the following into Python from Matlab? I'm still trying to wrap my head around lists/matrices and arrays in numpy, etc.
outframe(:,[4:4:nout-1]) = 0.25*inframe(:,[1:n-1]) + 0.75*inframe(:,[2:n])
pos=(beamnum>0)*(beamnum<=nbeams)*(binnum>0)*(binnum<=nbins)*((beamnum-1)*nbins+binnum)
for index =1:512:
outarray(index,:) =uint8(interp1([1:n],inarray64(index,:),[1:.25:n],method))
(There's other stuff, these are just the particular statements I'm not sure how to make sense of. I have numpy imported,
The main workhorse in numpy is the ndarray (or array). It will for the most part replace matlab matrices when you translate code. Like a matlab matrix, the ndarray stores homogeneous data (ie float64) and is optimized for numerical operations.
The numpy matrix is a subclass of the ndarray which can be convenient for some linear algebra intensive applications. Here is more info about the differences between the two.
The python list is more like a matlab cell array (though not exactly the same). It's one of the basic python data structures, but in scientific applications I find that it comes up most often when you need to hold heterogeneous data. (Or when you're doing something very simple and don't want to go to the trouble of creating a numpy array).
Your code above can be converted almost verbatim to python using the ndarray and replacing () with [] for indexing and taking into account that indexing starts at 1 in MATLAB and 0 in python
i.e. : the first element in MATLAB is element 1, and in python it is element 0.
Let's try this line by line:
outframe(:,[4:4:nout-1]) = 0.25*inframe(:,[1:n-1]) + 0.75*inframe(:,[2:n])
would translate in "English" to: all rows of outframe, but only every 4th column starting from 4 to nout-1 (i.e.4,8..). I assume you understand what inframe references mean.
pos=(beamnum>0)*(beamnum<=nbeams)*(binnum>0)*(binnum<=nbins)*((beamnum-1)*nbins+binnum)
Possibly beamnum is a vector and (beamnum >0) returns a vector of {0,1} such that the elements are '1' where the respective beamnum element is >0, else 0. The rest of it is clear, i hope.
The second last line is a for-loop and the last line should hopefully be clear.

Categories