I am new to python so I appreciate your help!
I am writing a simple code to read GPS data and print the speed value.
The gps sends serial lines of text like this:
$GNRMC,055945.00,A,3509.40388,N,10642.56412,W,0.080,,060321,,,D*72
$GNVTG,,T,,M,0.080,N,0.148,K,D*3D
$GNGGA,055945.00,3509.40388,N,10642.56412,W,2,12,0.64,1581.1,M,-23.9,M,,0000*4E
$GNGSA,A,3,29,05,18,15,13,20,23,25,51,46,26,16,1.20,0.64,1.02*1E
$GNGSA,A,3,65,87,88,72,66,79,81,,,,,,1.20,0.64,1.02*10
and my code currently looks for the correct line and the correct value using if statements:
import serial
import time
gps = serial.Serial("/dev/serial0", baudrate = 9600)
while True:
line = gps.readline()
data = line.decode().split(",")
if data[0] == "$GNRMC":
if data[2] == "A":
if data[4] == "N":
if data[6] =="W":
knotdata = data[7]
mphdata = knotdata * 1.15
print(mphdata)
however I am getting the following error:
Traceback (most recent call last):
File "txgpsreadconv.py", line 15, in <module>
mphdata = knotdata * 1.15
TypeError: can't multiply sequence by non-int of type 'float'
I have tried many different approaches to rectify the issue with no success. I'm sure the solution is simple and I just don't have enough experience to figure it out, so your help is much appreciated!
The traceback is suggesting that knotdata is a sequence, which is not a data type that can be multiplied by a floating point number.
Essentially you're trying to multiply a string that represents a numeric value instead of the value itself, so you should do a casting before the operation:
knotdata = float(data[7])
Also you can improve the structure of your if statements like this:
if data[0:8:2] == ["$GRNMC", "A", "N", "W"]:
print(float(data[7]) * 1.15)
since your data[7] is a float variable, you can use type casting float
mphdata = float(knotdata) * 1.15
Related
Traceback (most recent call last):
File "main.py", line 17, in <module>
max_height = max(botmoves)
TypeError: '>' not supported between instances of 'tuple' and 'int'
This is the error I'm trying to find the biggest value in a list but it saying something about a ">" here is my code
from random import randint
points = 0
botmoves = [-1000]
for i in range(20):
guess = randint(0, 100)
print('Bot',"guessed the number was", guess)
print("The bot was",abs(guess-100),"off")
print("The bot gets",50 - abs(guess-100),"points")
points = 50 - abs(guess-100),"points"
botmoves.append(points)
max_height = max(botmoves) #this is where the error is
print(botmoves)
The max function needs to be able to compare values to each other, and it does that with the > operator. What the error is telling you is that there are different types of elements in the list, which cannot sensibly be compared to each other. In this case, an int and a tuple.
The reason for that is this line:
points = 50 - abs(guess-100),"points"
The ,"points" at the end makes points into a tuple, for example (37, "points"). The parentheses are optional in many cases.
Probably that's just a copy/paste mistake from the line above, and you didn't mean to put that there:
points = 50 - abs(guess-100)
I'm trying to create a GUI for a signal analysis simulation that i'm writing in Python. For that, I use AppJar. However, when I call the function that generates the signal, I get a ValueError like in the title.
I've read every single ValueError post on stackOverflow (i could have missed one maybe, but i did my best) and all of them are about extra spacings, letters that can not be parsed as a floating point number, etc. None of that seems to apply here.
Basically, i'm using this code to call a function to generate my signal:
signal_axes = app.addPlot("signal", *logic.signal(5, 2), 0, 0, 1)
And the relevant part of the function itself (in the file logic.py, which is imported)
def signal(electrodes, length):
velocity = math.sqrt((3.2e-19 * kinetic_energy) / (mass * 1.66e-27))
frequency = velocity / length
This is not the whole function, the variables are all declared and unused variables are used later in the function.
The error specifically points to the line with "frequency = velocity / length", telling me:
TypeError: unsupported operand type(s) for /: 'float' and 'str'
When i try to fix it by using "float(length)" i get the error:
ValueError: could not convert string to float:
In one of the answers on StackExchange someone suggested using .strip() to get rid of invisible spaces. So i tried using:
length.strip()
But that gives me the following error:
AttributeError: 'float' object has no attribute 'strip'
I am slowly descending into madness here. The following code, by the way, stand-alone, works:
import numpy as np
kinetic_energy = 9000
mass = 40
length = 2e-2
velocity = np.sqrt((3.2e-19 * kinetic_energy) / (mass * 1.66e-27))
frequency = float(velocity) / float(length)
print(frequency)
Can anyone see what could be wrong? I've included all the relevant code below, it's not my complete file but this alone should give an output, at least.
run.py
import logic
from appjar import gui
def generate(btn):
app.updatePlot("signal", *logic.signal(app.getEntry("electrodes"), app.getEntry("length")))
showSignalLabels()
def showSignalLabels():
signal_axes.set_xlabel("time (us)")
signal_axes.set_ylabel("amplitude (uV)")
app.refreshPlot("signal")
app = gui()
signal_axes = app.addPlot("signal", *logic.signal(5, 0.02), 0, 0, 1)
app.addLabelEntry("electrodes", 1, 0, 1)
app.addLabelEntry("length", 2, 0, 1)
showSignalLabels()
app.addButton("Generate", generate)
app.go()
logic.py
import numpy as np
import math
import colorednoise as cn
steps = 5000
amplitude = 1
offset_code = 0
kinetic_energy = 9000
mass = 40
centered = 1
def signal(electrodes, length):
velocity = math.sqrt((3.2e-19 * kinetic_energy) / (mass * 1.66e-27))
frequency = velocity / length
time = 2 * (electrodes / frequency)
--- irrelevant code ---
return OutputTime, OutputSignal
edit: here is the full traceback.
Exception in Tkinter callback
Traceback (most recent call last):
File "E:\Internship IOM\WPy64-3720\python-3.7.2.amd64\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "E:\Internship IOM\PythonScripts\appJar\appjar.py", line 3783, in <lambda>
return lambda *args: funcName(param)
File "E:/Internship IOM/PythonScripts/appJar/testrun.py", line 12, in generate
app.updatePlot("signal", *logic.signal(app.getEntry("electrodes"), app.getEntry("length")))
File "E:\Internship IOM\PythonScripts\appJar\logic.py", line 33, in signal
frequency = velocity / length
TypeError: unsupported operand type(s) for /: 'float' and 'str'
You should convert at the calling site, i.e. do:
def generate(btn):
app.updatePlot("signal", *logic.signal(app.getEntry("electrodes"),
float(app.getEntry("length"))))
...
Because otherwise your function logic.signal receives different type (str and float). That's why you receive the other error about float has no strip because somewhere else in your code you do:
signal_axes = app.addPlot("signal", *logic.signal(5, 0.02), 0, 0, 1)
Here you pass it a float.
Since your original error was could not convert string to float with an apparently empty string, you need to take an extra measure to prevent empty values from the app. You can use a try ... except:
def generate(btn):
try:
length = float(app.getEntry("length"))
except ValueError:
# Use some default value here, or re-raise.
length = 0.
app.updatePlot("signal", *logic.signal(app.getEntry("electrodes"), length))
I'm attempting to create a script that will take a .GTiff file as an argument input and then extract some information out of the file to create a stats.txt file that will give me the classID, fractional coverage and total number of pixels of that classID.
Thus far I believe I have everything I need but I keep running into the same error and my attempts to rectify the error haven't proven to be very fruitful.
#!/usr/bin/env python
import sys
import calendar
import os
import gdal
import numpy as np
from scipy.stats import mode
from IPython import embed
GDAL2NUMPY = { gdal.GDT_Byte : np.uint8,
gdal.GDT_UInt16 : np.uint16,
gdal.GDT_Int16 : np.int16,
gdal.GDT_UInt32 : np.uint32,
gdal.GDT_Int32 : np.int32,
gdal.GDT_Float32 : np.float32,
gdal.GDT_Float64 : np.float64,
gdal.GDT_CInt16 : np.complex64,
gdal.GDT_CInt32 : np.complex64,
gdal.GDT_CFloat32 : np.complex64,
gdal.GDT_CFloat64 : np.complex128
}
#Open the original training data .tif map file.
fname = sys.argv[1]
lc_dataset = gdal.Open(fname)
lc = lc_dataset.ReadAsArray()
lc = np.array(lc)
#Calculating total number of pixels with a valid Land Cover ID.
fill_value = 0
number_of_pixels = np.where(lc != fill_value)[0].shape[0]
#Get the number of classes and corresponding IDs.
lc_classes = np.unique(lc)
#Split each class into its contituante pixel and write result to file.
for classID in range(1, lc_classes):
lc_class_pixels = np.where(lc == classID)[0].shape[0]
FractionalCover = lc_class_pixels/number_of_pixels
f.write(classID, FractionalCoverage, lc_class_pixels)
f.close()
When I run this, it chuck up the following traceback:
Traceback (most recent call last):
File "GeneratingLCstats.py", line 45, in <module>
for classID in range(1, lc_classes):
TypeError: only size-1 arrays can be converted to Python scalars
I've attempted a few changes as I'm sure the error is related to numpy data and native python data interactions, but converting all my arrays to numpy arrays and attempting to reformat the code has proved in vain as the same error persists.
If anyone can suggest a fix that would be greatly appreciated!
Thanks.
Well, the function lc_classes = np.unique(lc) returns an array. When you try to write the for loop as
for classID in range(1, lc_classes)
Here, lc_classes is an array and trying to give it as a bound for the range causes the error. If you want to iterate over the length of the array, you can modify the code to :
for classID in range(1, len(lc_classes))
I am working on the following python code:
import wave
from bitstring import BitArray
w = wave.open('file.wav','rb')
totalFrames = w.getnframes() #Total number of samples
bytesData = w.readframes(totalFrames)
binData = BitArray(bytesData)
bin2Data = (binData.bin)
The file.wav has 88200 samples at a sampling rate of 44.1KHz.
My goal is to be able to get the 2's compliment of the binary data I obtain from file.wav. 'binData.bin' gives me the binary form of the bytes (\x00\x00N\x00n\xff..) obtained through w.readframes but in a string format.
I was using this to obtain 2'scompliment:
2comp = ~(bin2Data) + 0b1
but in vain. It would show the following error:
Traceback (most recent call last):
File "speaker_bin.py", line 16, in <module>
bin2Data = ~((binData.bin)) + 0b1
TypeError: bad operand type for unary ~: 'str'
I tried int(bin2Data) to convert it but it would not work (It would not print anything at all. I guess because of the size of the data.)
What am I doing wrong?
I would really appreciate any feedback. (even a simple nudge in the right direction)
You need to use
int(binData.bin, 2)
To create an int, you can specify the base as a second parameter, otherwise it will just assume the value is in base 10. As you can see from the docs, the default base is 10, which is why you need to specify a different base other than 10
Also do the same with 0b1
I am trying to take the inverse Fourier transform of a list, and for some reason I keep getting the following error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "simulating_coherent_data.py", line 238, in <module>
exec('ift%s = np.fft.ifft(nd.array(FTxSQRT_PS%s))'(x,x))
TypeError: 'str' object is not callable
And I can't figure out where I have a string. The part of my code it relates to is as follows
def FTxSQRT_PS(FT,PS):
# Import: The Fourier Transform and the Power Spectrum, both as lists
# Export: The result of FTxsqrt(PS), as a list
# Function:
# Takes each element in the FT and PS and finds FTxsqrt(PS) for each
# appends each results to a list called signal
signal = []
print type(PS)
for x in range(len(FT)):
indiv_signal = np.abs(FT[x])*math.sqrt(PS[x])
signal.append(indiv_signal)
return signal
for x in range(1,number_timesteps+1):
exec('FTxSQRT_PS%s = FTxSQRT_PS(fshift%s,power_spectrum%s)'%(x,x,x))
exec('ift%s = np.fft.ifft(FTxSQRT_PS%s)'(x,x))
Where FTxSQRT_PS%s are all lists. fshift%s is a np.array and power_spectrum%s is a list. I've also tried setting the type for FTxSQRT_PS%s as a np.array but that did not help.
I have very similar code a few lines up that works fine;
for x in range(1,number_timesteps+1):
exec('fft%s = np.fft.fft(source%s)'%(x,x))
where source%s are all type np.array
The only thing I can think of is that maybe np.fft.ifft is not how I should be taking the inverse Fourier transform for Python 2.7.6 but I also cannot find an alternative.
Let me know if you'd like to see the whole code, there is about 240 lines up to where I'm having trouble, though a lot of that is commenting.
Thanks for any help,
Teresa
You are missing a %
exec('ift%s = np.fft.ifft(FTxSQRT_PS%s)'(x,x))
Should be:
exec('ift%s = np.fft.ifft(FTxSQRT_PS%s)'%(x,x))