#!/usr/bin/env python """Auxiliary numerical tools """ import Numeric def mean(x): """Mean value of a vector """ return(float(Numeric.sum(x))/len(x)) def cov(x, y=None): """Covariance of vectors x and y. If y is None: return cov(x, x) """ if y is None: y = x assert(len(x)==len(y)) N = len(x) cx = x - mean(x) cy = y - mean(y) p = Numeric.innerproduct(cx,cy)/N return(p) def err(x, y=0, n=2, relative=True): """Relative error of ||x-y|| to ||y|| n = 2: Two norm n = None: Max norm If denominator evaluates to zero or if y is omitted, absolute error is returned """ x = ensure_numeric(x) if y: y = ensure_numeric(y) if n == 2: err = norm(x-y) if relative is True: try: err = err/norm(y) except: pass else: err = max(abs(x-y)) if relative is True: try: err = err/max(abs(y)) except: pass return err def norm(x): """2-norm of x """ y = Numeric.ravel(x) p = Numeric.sqrt(Numeric.innerproduct(y,y)) return p def corr(x, y=None): """Correlation of x and y If y is None return autocorrelation of x """ from math import sqrt if y is None: y = x varx = cov(x) vary = cov(y) if varx == 0 or vary == 0: C = 0 else: C = cov(x,y)/sqrt(varx * vary) return(C) def ensure_numeric(A, typecode = None): """Ensure that sequence is a Numeric array. Inputs: A: Sequence. If A is already a Numeric array it will be returned unaltered If not, an attempt is made to convert it to a Numeric array typecode: Numeric type. If specified, use this in the conversion. If not, let Numeric decide This function is necessary as array(A) can cause memory overflow. """ from Numeric import ArrayType, array if typecode is None: if type(A) == ArrayType: return A else: return array(A) else: if type(A) == ArrayType: if A.typecode == typecode: return array(A) #FIXME: Shouldn't this just return A? else: return A.astype(typecode) else: return array(A).astype(typecode)