Complete values are not writing to the file using Python - python-3.x

My idea is to write some large number of bits to a file (almost 64*4800 bits). It is writing but not all the bits.
The console output looks like
[1. 1. 0. ... 1. 0. 1.]
If I decrement the number of bits to be saved then it will work.
I will paste my code here. This code is sampling the analog to digital
y= function(x) # Inside this function I am generating binary values and stored to y
################ y is in numpy.ndarray form
################ x is a sine wave
f=open('filename.txt',"w+")
f.write(str(y)) #we have to convert the numpy.ndarray to str.
f.close()
when I open my filename.txt file it is showing the binary values as
[1. 1. 0. ... 1. 0. 1.]
which is same as in the console.
Please help me to resolve this issue. I need all the bits (64*4800) to be saved inside the file

Try converting your numpy array to a list first:
y = function(x) # Inside this function I am generating binary values and stored to y
################ y is in numpy.ndarray form
################ x is a sine wave
y_list = y.tolist() # Convert to python list
# use the with context manager and you don't need to call .close() explicitly
with open('filename.txt',"w+") as f:
f.write(str(y_list)) #we have to convert the numpy.ndarray to a list and then to str(y_list) which will write the entire bits.

Related

Appending to numpy array within a loop

I really hope to not have missed something, that had been clarified before, but I couldn't find something here.
The task seems easy, but I fail. I want to continuously append a numpy array to another one while in a for-loop:
step_n = 10
steps = np.empty([step_n,1])
for n in range(step_n):
step = np.random.choice([-1, 0, 1], size=(1,2))
#steps.append(step) -> if would be lists, I would do it like that
a = np.append(steps,step)
#something will be checked after each n
print(a)
The output should be ofc of type <class 'numpy.ndarray'> and look like:
[[-1. 0.]
[ 0. 0.]
[-1. -1.]
[ 1. -1.]
[ 1. 1.]
[ 0. -1.]
[-1. 1.]
[-1. 0.]
[ 0. -1.]
[ 1. 1.]]
However the code fails for some (most probably obvious) reasons.
Can someone give me a hint?
import numpy as np
step_n = 10
steps = np.random.choice([-1, 0, 1], size=(1,2))
for n in range(step_n-1):
step = np.random.choice([-1, 0, 1], size=(1,2))
print(steps)
steps = np.append(steps, step, axis=0)
#something will be checked after each n
print(steps)
One of the problems is that your steps variable that is initialized outside the for loop has a different size than each step inside. I changed how you initialized the variable steps, by creating your first step outside of the for loop. This way, your steps variable already has the matching size. But notice you need to reduce 1 iteration in the for loop because of this.
Also, you want to update the steps variable in each for loop, and not create a new variable "a" inside it. In your code, you would just end up with the steps array (that never changes) and only the last step.

Finding more indices in a list close to zero

I have a list of values, which represents a damping function when this is plotted (so a form of a sinusoide). This function passes the y=0 thus several times until it levels out on y=0. I need to find the index at the moment when the function passes zero for the third time.
All values are floats, so I have a function that finds the index closest to zero:
def find_index(list_, value):
array = np.asarray(list_)
idx = (np.abs(array - value)).argmin()
return idx
Where 'list_' is the list and 'value' is zero.
This function does work, but it can only retrieve the index of the first moment the damping function (and thus the list) is closest to zero. Meaning that it will show an index of zero (because the damping function starts at zero). However, I need the index of the third time when it is closest to zero.
How can I obtain the index of the third time it will be closest to zero, instead of the first time?
You are looking for a change in the sign.
import numpy as np
x = np.array([10.0, 1.0, -1.0, -2.0, 1.0, 4.0])
y = np.sign(x) # -1 or 1
print(y)
>>> [ 1. 1. -1. -1. 1. 1.]
If you calculate the difference between consecutive elements using np.diff it will be either -2 or 2, both are boolean True.
>>> [ 0. -2. 0. 2. 0.]
Now get the indices of them using np.nonzero, which returns a tuple for each dimension. Pick the first one.
idx = np.nonzero(np.diff(y))[0]
print(idx)
>>> [1 3]

Could not convert String to float in numpy ndarray

I have been doing some reading from fer 2013 csv file containing three columns emotion, pixel value and usage. the pixel value is said to have given in string format and I want to rescale my pixel values from 0-255 to between 0-1 , so I need to convert it to int/float and then only I would be able to do any mathematical operations on them.
I first tried to read the csv file using pandas read_csv function and then using iloc I read the value of the pixel value in a variable called x_tr. Then upon printing its value it shows its d type as object.confused on that too.x_tr is numpy ndarray then how should I convert it into integral value.
I tried the x_tr.astype(np.float) but it gave up the error as mentioned in the code.
x_tr = train.iloc[:,1].values
x_tr
what I tried to convert to float
x_tr = train.iloc[:,1].values
x_tr = x_tr.astype(np.float)
and what I've got as error
Please Help.
Don't convert your pixel into an array, instead treat it as a simple string. Then use numpy.fromstring() method. Here's an example for reference.
>>> s = '1 2 3 4'
>>> f = np.fromstring(s, dtype=float, sep=' ')
>>> f
array([1., 2., 3., 4.])

convert python map objects to array or dataframe

How can we convert map objects(derived from ndarray objects) to a dataframe or array object in python.
I have a normally distributed data with size 10*10 called a. There is one more data containing 0 and 1 of size 10*10 called b. I want to add a to b if b is not zero else return b.
I am doing it through map. I am able to create the map object called c but can't see the content of it. Can someone please help.
a=numpy.random.normal(loc=0.0,scale=0.001,size=(10,10))
b = np.random.randint(2, size=a.shape)
c=map(lambda x,y : y+x if y!=0 else x, a,b)
a=[[.24,.03,.87],
[.45,.67,.34],
[.54,.32,.12]]
b=[[0,1,0],
[1,0,0],
[1,0,1]]
then c should be as shown below.
c=[[0,1.03,.87],
[1.45,0,0],
[1.54,0,1.12]
]
np.multiply(a,b) + b
should do it
Here is the output
array([[0. , 1.03, 0. ],
[1.45, 0. , 0. ],
[1.54, 0. , 1.12]])
Since, a and b are numpy arrays, there is a numpy function especially for this use case as np.where (documentation).
If a and b are as follows,
a=np.array([[.24,.03,.87],
[.45,.67,.34],
[.54,.32,.12]])
b=np.array([[0,1,0],
[1,0,0],
[1,0,1]])
Then the output of the following line,
np.where(b!=0, a+b, b)
will be,
[[0. 1.03 0. ]
[1.45 0. 0. ]
[1.54 0. 1.12]]

How to program sound card to output a specific signal?

I'm trying to program my sound card to output specific values.
Let's say, I have below sequence
[1,2,3,2,10,4,1,50,20,1]
I want the sound card to output the specified analog signal according to this sequence.
I can use Windows Multimedia API of course. However, my task is light-weighted and I don't want to use such heavy framework.
Any suggestions on this?
I propose you generate a .wav file and play it with a media player.
It's easy with python and its wave module. In my below example I worked with python 3.3
import wave
import struct
# define your sequence
frames = [1,2,3,2,10,4,1,50,20,1]
output = wave.open('out.wav', mode='wb') # create the file that will contain your sequence
output.setnchannels(1) # 1 for mono
output.setsampwidth(1) # resolution in number of bytes
output.setframerate(10) # sampling rate, being usually 44100 Hz
output.setnframes(len(frames)) # sequence length
for i in range(0, len(frames)):
output.writeframes(struct.pack('h',frames[i])) # convert to string in hex format
# close the file, you're done
output.close()
You can do this in one line if you use Matlab or the free equivalent, Octave. The relevant documentation is here.
soundsc(x, fs, [ lo, hi ])
Scale the signal so that [lo, hi] -> [-1, 1], then play it
at sampling rate fs. If fs is empty, then the default 8000 Hz
sampling rate is used.
Your function call in the console would look like this ...
soundsc([1,2,3,2,10,4,1,50,20,1], fs, [1 50]);
... or like this with manual normalisation of the positive integer vector to give values between +/- 1 ...
x = [1,2,3,2,10,4,1,50,20,1];
x=x-min(x); % get values to range from zero up
x=x/max(x); % get floating point values to range between 0.0 and 1.0
x=x*2-1; % get values to range between +/- 1.0;
soundsc(x);

Resources