""" John Rachlin DS 2000: Intro to Programming with Data Filename: dataproc.py Description: A personal library of data processing utilities """ import math import random as rnd import matplotlib.pyplot as plt def deg2rad(theta): """ Convert an angle, theta, from degrees to radians """ return theta * math.pi / 180.0 def rad2deg(theta): """ Convert an angle, theta, from radians to degrees """ return theta * 180.0 / math.pi def avg(L): """ Compute the numerical average of a list of numbers. If list is empty, return None """ if len(L) > 0: return sum(L) / len(L) else: return None def moving_average(L, window_size=10): """ Compute a moving average using a specified window size. L - A list of numbers window_size - The window size for data smoothing (default=10) """ mavg = [] for i in range(len(L)): lower = max(i - window_size // 2, 0) upper = i + window_size // 2 window = L[lower:upper] smooth = avg(window) mavg.append(smooth) return mavg def percentiles(L): """ Compute percentiles of values in a list """ srt = sorted(L) # Sort items in assending order length = len(L) pct = [0.0] # smallest value is at the zeroth percentile for i in range(1, length): if srt[i] == srt[i-1]: # value unchanged pct.append(pct[i-1]) else: pct.append(i / length) return pct def main(): # Some test code to 'exercise' our functions alist = [math.sin(deg2rad(deg))+rnd.uniform(-0.2,0.2) for deg in range(360)] plt.figure(figsize=(10,10), dpi=150) plt.scatter(range(360), alist) mavg = moving_average(alist, window_size=20) plt.plot(mavg, color='r') if __name__ == '__main__': main()