October 22, 2010

basic python math calculation in gnuradio

/gnuradio3.2.2/gr-wxgui/src/python/common.py

####################
# Shared Functions
#####################
import numpy
import math

"""
# Python is a general purpose programming language.
It is interpreted and dynamically typed and is very
suited for interactive work and quick prototyping,
while being powerful enough to write large applications in.
# NumPy is a Python extension module, written mostly in C,
that defines the numerical array and matrix types
and basic operations on them.
"""

def get_exp(num):
"""
Get the exponent of the number in base 10.
@param num the floating point number
@return the exponent as an integer
"""
if num == 0: return 0
return int(math.floor(math.log10(abs(num))))

def get_clean_num(num):
"""
Get the closest clean number match to num with bases 1, 2, 5.
@param num the number
@return the closest number
"""
if num == 0: return 0
sign = num > 0 and 1 or -1
exp = get_exp(num)
nums = numpy.array((1, 2, 5, 10))*(10**exp)
return sign*nums[numpy.argmin(numpy.abs(nums - abs(num)))]
#numpy.argmin: Return the indices of the minimum values along an axis.

def get_clean_incr(num):
"""
Get the next higher clean number with bases 1, 2, 5.
@param num the number
@return the next higher number
"""
num = get_clean_num(num)
exp = get_exp(num)
coeff = int(round(num/10**exp))
return {
-5: -2,
-2: -1,
-1: -.5,
1: 2,
2: 5,
5: 10,
}[coeff]*(10**exp)

def get_clean_decr(num):
"""
Get the next lower clean number with bases 1, 2, 5.
@param num the number
@return the next lower number
"""
num = get_clean_num(num)
exp = get_exp(num)
coeff = int(round(num/10**exp))
return {
-5: -10,
-2: -5,
-1: -2,
1: .5,
2: 1,
5: 2,
}[coeff]*(10**exp)

def get_min_max(samples):
"""
Get the minimum and maximum bounds for an array of samples.
@param samples the array of real values
@return a tuple of min, max
"""
scale_factor = 3
mean = numpy.average(samples)
rms = numpy.max([scale_factor*((numpy.sum((samples-mean)**2)/len(samples))**.5),
.1])
min = mean - rms
max = mean + rms
return min, max

No comments:

Post a Comment

Days of our lives

Daisypath Anniversary tickers