def list_derivative(f, x, n, o=3, p=5): """ Returns the nth derivative of f with respect to x, where zip(x,f) are datapoints, using curve-fit polynomials of order o to p points. """ assert p % 2 == 1 # should be odd imo assert len(f) >= p # won't work otherwise derivative = [] for i in xrange(len(f)): start = i - (p - 1) / 2 if start < 0: start = 0 end = start + p if end >= len(f): start = -1 - p end = -1 spline = polyfit(x[start:end], f[start:end], o) derivative.append(polyval(polyder(spline, n), x[i])) print("diff in list lengths: " + str(len(f) - len(derivative))) return array(derivative)
def analyze_olfaction_covariance(covariance, receptors): ''' Covariance: n x n covariance matrix. Positions: list of n positions ''' positions = [pose.get_2d_position() for pose, sens in receptors] #@UnusedVariable positions = array(positions).transpose().squeeze() require_shape(square_shape(), covariance) n = covariance.shape[0] require_shape((2, n), positions) distances = create_distance_matrix(positions) correlation = cov2corr(covariance) flat_distances = distances.reshape(n * n) flat_correlation = correlation.reshape(n * n) # let's fit a polynomial deg = 4 poly = polyfit(flat_distances, flat_correlation, deg=deg) knots = linspace(min(flat_distances), max(flat_distances), 2000) poly_int = polyval(poly, knots) poly_fder = polyder(poly) fder = polyval(poly_fder, distances) Ttheta = create_olfaction_Ttheta(positions, fder) Tx, Ty = create_olfaction_Txy(positions, fder, distances) report = Node('olfaction-theory') report.data('flat_distances', flat_distances) report.data('flat_correlation', flat_correlation) with report.data_file('dist_vs_corr', 'image/png') as filename: pylab.figure() pylab.plot(flat_distances, flat_correlation, '.') pylab.plot(knots, poly_int, 'r-') pylab.xlabel('distance') pylab.ylabel('correlation') pylab.title('Correlation vs distance') pylab.legend(['data', 'interpolation deg = %s' % deg]) pylab.savefig(filename) pylab.close() with report.data('fder', fder).data_file('fder', 'image/png') as filename: pylab.figure() pylab.plot(knots, polyval(poly_fder, knots), 'r-') pylab.title('f der') pylab.savefig(filename) pylab.close() report.data('distances', distances) report.data('correlation', correlation) report.data('covariance', covariance) report.data('f', polyval(poly, distances)) f = report.figure(id='cor-vs-distnace', caption='Estimated kernels', shape=(3, 3)) f.sub('dist_vs_corr') f.sub('fder') f.sub('f', display='scale') f.sub('distances', display='scale') f.sub('correlation', display='posneg') f.sub('covariance', display='posneg') T = numpy.zeros(shape=(3, Tx.shape[0], Tx.shape[1])) T[0, :, :] = Tx T[1, :, :] = Ty T[2, :, :] = Ttheta T_report = create_report_figure_tensors(T, report_id='tensors', caption="Predicted learned tensors") report.add_child(T_report) return report