#!/usr/bin/env python import numpy, math, sys, csv from scipy.optimize import curve_fit ############################################## # DECIMAL RANGE # # A float version of Python's range function # ############################################## # start - the start value for the range # # stop - the stop value for the range # # step - the step value for the range # ############################################## def drange(start, stop, step): r = start while r < stop: yield r r += step ############################################## # TRIG SERIES # # A function for curve_fit. This function # # is a trig series with elements: # # sin2x, cos2x, sinx, cosx # ############################################## def trig_series(x, a, b, c, d, e): return a*numpy.cos(x) + b*numpy.sin(x) + c*numpy.cos(2*x) + d*numpy.sin(2*x) + e def linsum(time, z_cellb): sum = 0. ndegs = len(z_cellb) for deg in range(ndegs): sum += z_cellb[deg] * math.pow(time, ndegs - deg - 1) return sum def trigsum(time, z_cellb): sum = 0. pairs = zip(z_cellb[::4], z_cellb[1::4], z_cellb[2::4], z_cellb[3::4]) for a, b, c, d in pairs: sum += a * numpy.cos(time * b) + c * numpy.sin(d) return sum # prepare the initial parameters header = None time_in = list() cellb_raw = dict() y_cellb = dict() z_cellb = dict() resolution = 10 reader = csv.reader(sys.stdin, dialect='excel-tab') # read in the data for row in reader: if not header: header = row for col in header[1:]: cellb_raw[col] = list() else: if len(row) > 1 and row[0] != '': time_in.append(float(row[0])) for col in range(1, len(row)): cellb_raw[header[col]].append(float(row[col])) # obtain the program parameters x_time = numpy.array(time_in) max_x = max(time_in) if len(sys.argv) > 1: resolution = sys.argv[1] if len(sys.argv) > 2: max_x = float(sys.argv[2]) # calculate the linear regression print >> sys.stderr, x_time for key in cellb_raw: y_cellb = numpy.array(cellb_raw[key]) print >> sys.stderr, key + ": " + str(y_cellb) z_cellb[key] = numpy.polyfit(x_time, y_cellb, resolution) #z_cellb, z_pcov = curve_fit(func1, x_time, y_cellb, p0=(1.0,0.2)) #z_cellb, z_pcov = curve_fit(func1a, x_time, y_cellb, p0=(1.0,1.2,1.0,0.2)) csv_out = csv.writer(sys.stdout, dialect='excel-tab') csv_out.writerow(header) for time in drange(0, max_x + 0.01, 0.01): #sum = trigsum(time, z_cellb) row = ['%.2f' % (time)] for key in header[1:]: sum = linsum(time, z_cellb[key]) row.append('%.4f' % (sum)) csv_out.writerow(row)