473,624 Members | 2,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bullet proof passing numeric values from NMEA data stream.

Folks,
I am looking for a fast but most importantly a bullet proof method to pass
and NMEA data stream (GPS output) ascii numeric strings. The best I can
offer is:

def fint(a):
try: return int(float(a))
except: return 0

The reason for this is the quality of the data from the huge variety of
GPS units available varies considerably. Some units do not follow the
standard and I want to pass the data as best I can without hanging the
code for an oddball data value.

Can anyone suggest better?

For example, each of the following throw the exception so do not return
the correct value:

int('00.')
int(' 00.')
float('- 00')
float(' - 00')
float(' - 00')
float(' - 00.')
float('- 00.')
float('- 10.')
float('- 10.')
float('- 10.')
int('- 10.')
int('- 10.')
float('- 10.')
int('1.0')

Also, why should I consider the string module? Is it faster/better?

TIA,
Doug
Mar 20 '07 #1
4 2252
Doug Gray wrote:
Folks,
I am looking for a fast but most importantly a bullet proof method to pass
and NMEA data stream (GPS output) ascii numeric strings. The best I can
offer is:

def fint(a):
try: return int(float(a))
except: return 0

The reason for this is the quality of the data from the huge variety of
GPS units available varies considerably. Some units do not follow the
standard and I want to pass the data as best I can without hanging the
code for an oddball data value.

Can anyone suggest better?

For example, each of the following throw the exception so do not return
the correct value:

int('00.')
int(' 00.')
float('- 00')
float(' - 00')
float(' - 00')
float(' - 00.')
float('- 00.')
float('- 10.')
float('- 10.')
float('- 10.')
int('- 10.')
int('- 10.')
float('- 10.')
int('1.0')

Also, why should I consider the string module? Is it faster/better?

TIA,
Doug
Try something like

def fint(s):
return float(s.replace (" ", ""))

I really don't think it's a good idea to silently ignore conversion
errors in GPS positioning.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Mar 20 '07 #2
On Tue, 20 Mar 2007 12:09:29 +0000, Doug Gray wrote:
Folks,
I am looking for a fast but most importantly a bullet proof method to pass
and NMEA data stream (GPS output) ascii numeric strings. The best I can
offer is:

def fint(a):
try: return int(float(a))
except: return 0

Will your application calculate the wrong results if it starts getting a
whole lot of spurious zeroes? Wouldn't it better to signal "this value is
invalid" rather than a false zero?

Do you actually want ints? It seems to me that if your data stream is
delivering floats, you're throwing away a lot of data. For example, if the
data stream is:

2.4, 5.7, 3.9, 5.1, ...

you're getting:

2, 5, 3, 5, ...

which is possibly not even the right way to convert to ints. Shouldn't you
be rounding to nearest (i.e. 2, 6, 4, 5, ...)?

[snip]
For example, each of the following throw the exception so do not return
the correct value:
[snip examples]

All your examples include spurious whitespace. If that is the only
problem, here's a simple fix:

def despace(s):
"""Remove whitespace from string s."""
return

def fix_data(value) :
"""Fix a GPS value string and return as a float."""
return float(''.join(v alue.split()))
If only a few values are malformed, you might find this is faster:

def fix_data2(value ):
try:
return float(value)
except ValueError:
return float(''.join(v alue.split()))

Only measurement with actual realistic data will tell you which is faster.

If you expect to get random non-numeric characters, then here's another
solution:

import string
# initialize some global data
table = string.maketran s("", "") # all 8 bit characters
keep = "1234567890 .-+"
dontkeep = ''.join([c for c in table if c not in keep])

def fix_data3(value ):
try: # a fast conversion first
return float(value)
except ValueError: # fall-back conversion
return float(string.tr anslate(value, table, don'tkeep))

Once you've built the character tables, the translate function itself is
executed in C and is very fast.

Also, why should I consider the string module? Is it faster/better?
Most of the time you should use string methods, e.g.:

"hello world".upper()

instead of

string.upper("h ello world")

The only time you should use the string module is when you need one of the
functions (or data objects) that don't exist as string methods (e.g.
translate).

--
Steven.

Mar 20 '07 #3
On Wed, 21 Mar 2007 00:29:00 +1100, Steven D'Aprano wrote:
All your examples include spurious whitespace. If that is the only
problem, here's a simple fix:

def despace(s):
"""Remove whitespace from string s."""
return
Gah! Ignore that stub. I forgot to delete it :(
While I'm at it, here's another solution: simply skip invalid values,
using a pair of iterators, one to collect raw values from the device and
one to strip out the invalid results.

def raw_data():
"""Generato r to collect raw data and pass it on."""
while 1:
# grab a single value
value = grab_data_value _from_somewhere ()
if value is "": # Some special "END TRANSMISSION" value.
return
yield value

def converter(strea m):
"""Generato r to strip out values that can't be converted to float."""
for value in stream:
try:
yield float(value)
except ValueError:
pass

values_safe_to_ use = converter(raw_d ata())

for value in values_safe_to_ use:
print value
Naturally you can extend the converter to try harder to convert the string
to a float before giving up.
--
Steven.

Mar 20 '07 #4
On Wed, 21 Mar 2007 00:29:00 +1100, Steven D'Aprano wrote:
On Tue, 20 Mar 2007 12:09:29 +0000, Doug Gray wrote:
>Folks,
I am looking for a fast but most importantly a bullet proof method to pass
and NMEA data stream (GPS output) ascii numeric strings. The best I can
offer is:

def fint(a):
try: return int(float(a))
except: return 0


Will your application calculate the wrong results if it starts getting a
whole lot of spurious zeroes? Wouldn't it better to signal "this value is
invalid" rather than a false zero?

Do you actually want ints? It seems to me that if your data stream is
delivering floats, you're throwing away a lot of data. For example, if the
data stream is:

2.4, 5.7, 3.9, 5.1, ...

you're getting:

2, 5, 3, 5, ...

which is possibly not even the right way to convert to ints. Shouldn't you
be rounding to nearest (i.e. 2, 6, 4, 5, ...)?

[snip]
Thanks, a very helpful response. I'll need some time to fully digest.
Yes I will need a float variant, the int version was by way of example. I
can deal with the rounding etc as necessary, but I was after an
pythonistic view of the generic problem.

Re the examples: whitespace and mal positioned signs and decimal point
would be the obvious errors I might expect but of course this is
speculation. The few GPS units I have tried have all tripped up my first
cut less tolerant code. I am going to revise the interface to work around
potential problems and my preliminary test efforts highlighted more
exceptions than I expected.

Doug
Mar 20 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1887
by: Siggi | last post by:
Hi, - In my (Java)program I read a POST-request from a Web-client over a socket and might pass this request to a PHP/cgi-Modul, to get PHP's generated HTML-stream. The request comes in parts as follows: .. .. -----------------------------7d42241a0302
58
10114
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
3
6518
by: success_ny | last post by:
Does anyone have a code snippet to compare those values so I can sort the array of alpha-numeric values that include both characters and integers in it? I.e., if we have values like 4236 and 123234, I want 4236 to be second because 4 is bigger than 1 rather than using the numeric comparison. The strings can include character values and strings. Basically, I have the bubble sort function, the question is how to compare those types of...
4
1727
by: deko | last post by:
I've created an mde out of my mdb in and effort to prevent users from changing settings/forms/etc. But I've discovered that the database window is still available if I hold down the Shift key when opening the mde. Forms can no longer be opened in Design View, which is good, but queries and tables are still vulnerable. I've unchecked "Display Database Window" in Tools >> Start Up, but that does not seem to help if the Shift key is held...
0
4096
by: jjs0713 | last post by:
Hi, Everyone ! I made a C program. I want to know serial communication at micom which is ATMEL 89C52. It's received to micom RX pin(serial comm.) NMEA format from some set. I'd like to take UTC Time. then I'll display to LCD output. I really need to help which is to get UTC time from NMEA format. 1. NMEA format $GPGGA,000915.5,3727.85245,N,12702.53467,E,0,00,,684.6,M,18.5,M,,*71
7
1651
by: Sheldon | last post by:
Hi, I have the following loop that I think can be written to run faster in Numeric. I am currently using Numeric. range_va = main.xsize= 600 main.ysize= 600 #msgva is an (600x600) Numeric array with mutiple occurrences of the values in range_va #sat_id is an (600x600) Numeric array with values ranging from -2 to 2
2
2271
by: goetzie | last post by:
I am using Python 2.4.1 and Numeric 23.8 and running on Windows XP. I am passing a Numeric array of strings (objects) to a C Extension module using the following python code: import Numeric import TestDLL # my C Extension Module a = Numeric.array(, 'O' ) print 'a =', a print 'type a =', type(a)
43
2594
by: SLH | last post by:
hi people. im trying to validate input received via a text area on an ASP page before writing it to a database. i cant use client side javascript due to policy, so it all has to happen on the server. here is what i was trying, but pieces of it continue to break for one reason or another. the thinking behind this function was like this: if the input is less than 10 characters long, fail. if its 10 characters or greater, but it doesnt...
3
2877
by: Antony Sequeira | last post by:
Hi I was trying to improve my understanding of generics. Reading the tutorial http://java.sun.com/docs/books/tutorial/extra/generics/methods.html I had a doubt and wanted to check it out. I modified the example code slightly by adding a line of code that says a = c.iterator().next();
0
8231
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8672
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8614
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8330
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5561
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4167
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2603
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1474
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.