Changeset 167

Show
Ignore:
Timestamp:
04/30/08 13:37:56 (7 months ago)
Author:
edsuom
Message:

Getting model unit tests working again after refactoring

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • projects/AsynCluster/trunk/svpmc/model.py

    r166 r167  
    7373        M = modelObj 
    7474 
    75     def likelihood(paramContainer, wiggle): 
    76         L, v, h = M.likelihood(paramContainer, wiggle) 
    77         return Packer(L, v, h)() 
     75    def likelihood(paramContainer, sigma): 
     76        result = M.likelihood(paramContainer, sigma) 
     77        if result is None: 
     78            return 
     79        return Packer(*result)() 
    7880 
    7981    ########################################################################### 
    8082    """ 
    81     def __init__(self, paramNames, tsList): 
    82         self.modelObj = Model(paramNames=paramNames, tsList=tsList
     83    def __init__(self, paramNames, y): 
     84        self.modelObj = Model(paramNames=paramNames, y=y
    8385        self.queue = NullQueue(1) 
    8486        reactor.addSystemEventTrigger( 
     
    114116        return d 
    115117     
    116     def likelihood(self, paramContainer, wiggle, remote=False, local=False): 
     118    def likelihood(self, paramContainer, sigma, remote=False, local=False): 
    117119        """ 
    118120        Computes the log-likelihood of the parameters in the supplied 
     
    124126 
    125127        Returns a deferred that fires with a reference to the paramContainer 
    126         when the likelihood computation is done and the it has been updated. 
    127         """ 
    128         def gotPackedLikelihood(result): 
     128        when the likelihood computation is done and it has been updated. 
     129        """ 
     130        def gotLikelihood(result): 
    129131            if result is None: 
    130132                # An error from the remote likelihood method call is treated as 
    131133                # infinitely low likelihood 
    132                 paramContainer.Lx = -s.inf 
    133                 paramContainer.z = [] 
    134                 paramContainer.h = [] 
    135             else: 
    136                 return gotLikelihood(list(pack.Unpacker(result))) 
    137  
    138         def gotLikelihood(result): 
     134                result = [-s.inf, [], []] 
     135            elif isinstance(result, str): 
     136                # Unpack string result from remote call 
     137                result = list(pack.Unpacker(result)) 
    139138            for k, name in enumerate(('Lx', 'z', 'h')): 
    140139                setattr(paramContainer, name, result[k]) 
     
    143142        if (remote or self.remoteMode) and not local: 
    144143            d = self.client.run( 
    145                 'likelihood', paramContainer, wiggle, timeout=self.timeout) 
    146             d.addCallback(gotPackedLikelihood) 
     144                'likelihood', paramContainer, sigma, timeout=self.timeout) 
    147145        else: 
    148146            d = self.queue.call( 
    149                 self.modelObj.likelihood, paramContainer, wiggle) 
    150             d.addCallback(gotLikelihood) 
    151         return d.addErrback(self._oops) 
     147                self.modelObj.likelihood, paramContainer, sigma) 
     148        return d.addCallbacks(gotLikelihood, self._oops) 
    152149 
    153150 
     
    187184    process with correlated volatility (v) and return (w) shocks. 
    188185 
    189     @ivar tsList: A sequence of one or more time-series objects containing 
    190       observation data. 
     186    @ivar y: A 2-D array containing my observation data. 
    191187 
    192188    @ivar Mv: Number of volatility draws per likelihood evaluation. 
     
    197193    _logU_index = -1 
    198194 
    199     keyAttrs = {'tsList':None, 'Mv':50, 'Mz':50} 
     195    keyAttrs = {'y':None, 'Mv':50, 'Mz':50} 
    200196 
    201197    #--- Properties ----------------------------------------------------------- 
    202198 
    203199    def _get_p(self): 
    204         return len(self.tsList) 
     200        return self.y.shape[0] 
    205201    p = property(_get_p) 
    206      
    207     def _get_y(self): 
    208         if 'y' not in self.cache: 
    209             tsObj = self.tsList[0] 
    210             y = s.empty((self.p, len(tsObj))) 
    211             for k in xrange(self.p): 
    212                 if k > 0: 
    213                     # No need to intersect first object with itself 
    214                     tsObj = tsObj.intersect(self.tsList[k]) 
    215                 y[k,:] = tsObj() 
    216             self.cache['y'] = y 
    217         return self.cache['y'] 
    218     y = property(_get_y) 
    219202     
    220203    def _get_n(self): 
     
    290273        """ 
    291274        z = z.copy() 
    292         self.inline( 
    293             'z', 'M', 'wiggle', M=self.Mz, wiggle=sigma) 
     275        self.inline('z', 'M', 'wiggle', M=self.Mz, wiggle=sigma) 
    294276        return z 
    295277     
     
    323305            y[:,0] = s.sqrt(1 - self.g**2) 
    324306            y[:,1] = s.log(s.sqrt(2*s.pi) * y[:,0]) 
    325             # Inverse of concurrent cross-correlations between innovation shocks 
    326             ri = linalg.inv( 
    327                 linalg.cholesky( 
     307            # Inverse of concurrent cross-correlations between innovation 
     308            # shocks, will raise exception if invalid 
     309            ri = linalg.inv(linalg.cholesky( 
    328310                self.covarMatrix(s.ones(self.p), self.cr), lower=True)) 
    329311            self.cache['lv_work'] = y, ri 
     
    351333        # variates, if positive definite... 
    352334        v = s.array(rv*z) 
    353         if v is None: 
    354             # (If not, return worst possible likelihood for this illegal fs, fr 
    355             # parameter combination) 
    356             return 
    357335        # ...and initial log-volatilites, from the offset alone... 
    358336        h0 = self.d 
     
    404382        cross-correlation to form volatility shocks, and VAR(1) to form the 
    405383        log-volatilities. The Metropolis-Hastings proposals are scaled based on 
    406         the supplied fractional I{wiggle}. The simulation is governed by the 
     384        the supplied fractional I{sigma}. The simulation is governed by the 
    407385        log-likelihood of my observation data given the supplied parameters and 
    408386        the simulated log-volatilities. 
    409387 
    410         The method returns a list containing the following values reached at 
    411         the end of the log-volatility simulation: 
     388        If a L{linalg.LinAlgError} is raised due to an invalid correlation 
     389        matrix parameter, the method returns with no result. Otherwise, it 
     390        returns a list containing the following values reached at the end of 
     391        the log-volatility simulation: 
    412392         
    413393            1. The value of the log-likelihood. 
     
    428408        z = paramContainer.z.copy() 
    429409        # Concurrent cross-correlations between volatility shocks, bail out 
    430         # with worst possible likelihood if invalid 
     410        # with no result if invalid 
    431411        try: 
    432412            rv = s.matrix(linalg.cholesky( 
    433413                self.covarMatrix(self.fs, self.fr), lower=True)) 
    434414        except linalg.LinAlgError: 
    435             return -s.inf, z 
     415            return 
    436416        # Innovations as residuals of the reversed VAR(1) 
    437417        x = self.var.reverse(self.a, self.b) 
    438418        # Run the hybrid Gibbs rounds, returning the likelihood from the last 
    439         # one along with the state of the IID variate vector at that point 
    440         for k in xrange(self.Mv-1): 
    441             self.hybridGibbs(z, x, rv, sigma) 
     419        # one along with the state of the IID variate vector at that point, 
     420        # bailing out with no result if invalid parameter raises exception 
     421        try: 
     422            for k in xrange(self.Mv-1): 
     423                self.hybridGibbs(z, x, rv, sigma) 
     424        except linalg.LinAlgError: 
     425            return 
    442426        return list(self.hybridGibbs(z, x, rv, sigma)) + [z] 
    443427     
  • projects/AsynCluster/trunk/svpmc/project.py

    r166 r167  
    6868        specDir = os.path.dirname(specFile) 
    6969        self.tables = self._parseSpec(specFile) 
    70         tsList, seriesTitles = self._setupTimeSeries(specDir) 
    71         tsData = s.row_stack([ts() for ts in tsList]) 
     70        tsData, seriesTitles = self._setupTimeSeries(specDir) 
    7271        self.p, self.n = tsData.shape 
    7372        paramTitles, dimensions = self._setupParams() 
     
    7574            os.path.join(specDir, ncFileName), 
    7675            tsData, seriesTitles, paramTitles, dimensions) 
    77         self.mgr = model.ModelManager(self.paramNames, tsList
     76        self.mgr = model.ModelManager(self.paramNames, tsData
    7877     
    7978    def _parseSpec(self, filePath): 
     
    108107        directory. 
    109108 
    110         Returns a list of the objects along with a list of the time series 
    111         titles. 
     109        Returns a 2-D array of the time series data, samples across columns and 
     110        time series across rows, along with a list of the time series titles. 
    112111        """ 
    113112        prevObj = None 
     
    123122            titles.append(title) 
    124123            prevObj = tsObject 
    125         return tsList, titles 
     124        return s.row_stack([ts() for ts in tsList]), titles 
    126125 
    127126    def _setupParams(self): 
  • projects/AsynCluster/trunk/svpmc/test/test_model.py

    r161 r167  
    3636 
    3737 
    38 class Test_SpecParser(util.TestCase): 
    39     def setUp(self): 
    40         self.sp = model.SpecParser( 
    41             os.path.join(os.path.dirname(__file__), "project-spec.txt")) 
    42  
    43     def test_parse(self): 
    44         paramNames = [row[0] for row in self.sp.tables['parameter']] 
    45         for name, rows in self.sp.tables.iteritems(): 
    46             if name == 'series': 
    47                 self.failUnlessEqual(len(rows), 3) 
    48             elif name == 'parameter': 
    49                 self.failUnlessEqual(len(rows), 8) 
    50             else: 
    51                 self.failUnless(name in paramNames) 
    52  
    53     def test_timeSeries(self): 
    54         tsList = self.sp.timeSeries()[0] 
    55         self.failUnlessEqual(len(tsList), 3) 
    56  
    57     def test_priorContainer(self): 
    58         container = self.sp.priorContainer()[0] 
    59         self.failUnlessEqual(container.a.shape, (3,)) 
    60         self.failUnlessEqual(container.b.shape, (3,3)) 
    61         self.failUnlessEqual(container.cr.shape, (6,)) 
     38def likelihoodFunc(paramContainer, drift): 
     39    return (-(paramContainer.a - drift)**2).sum() 
    6240 
    6341 
    6442class Mock_Model(params.Parameterized, util.Mock): 
    65     N_params = 3 
    66     def likelihood(self, X): 
    67         return s.exp(-X**2) 
     43    drift = 1.5 
     44    p, n = 8, 937 
     45 
     46    def likelihood(self, paramContainer, sigma): 
     47        return likelihoodFunc(paramContainer, self.drift) 
    6848 
    6949 
     
    9171        # Adapted from the manager's nodecode string 
    9272        if args[0] == 'likelihood': 
    93             X = pack.Unpacker(args[2])() 
    94             d = util.deferToLater(self.model.likelihood, X, delay=0.01) 
    95             d.addCallback(lambda x: float(x)) 
    96             return d 
    97         if args[0] == 'callModel': 
    98             method = getattr(self.model, args[2]) 
    9973            return util.deferToLater( 
    100                 pack.packwrap(method)(*args[3:]), delay=0.01) 
    101  
    102  
    103 class Test_ModelCaller_Basics(util.TestCase): 
     74                self.model.likelihood, args[1], args[2], delay=0.01) 
     75 
     76 
     77class Test_ModelManager_Basics(util.TestCase): 
    10478    def setUp(self): 
    10579        self.model = Mock_Model() 
    10680        self.JobClient = model.jobs.JobClient 
    10781        model.jobs.JobClient = Mock_Client 
    108         self.caller = model.ModelCaller(self.model) 
     82        self.mgr = model.ModelManager(self.model) 
    10983 
    11084    def tearDown(self): 
     
    11387    def test_localIsDefault(self): 
    11488        def gotResult(result): 
    115             self.failUnlessElementsEqual(result, s.exp(-X**2)) 
     89            self.failUnlessEqual( 
     90                result[0], likelihoodFunc(paramContainer, 1.5)) 
    11691            self.nextCall(Mock_Model.calls) 
    11792            self.nextCall('likelihood') 
    11893 
    11994        Mock_Model.clearCalls() 
    120         X = s.array([0.0, 0.1]) 
    121         return self.caller.call('likelihood', X).addCallback(gotResult) 
     95        paramContainer = util.Mock_ParameterContainer() 
     96        d = self.mgr.call('likelihood', paramContainer, 1.0) 
     97        d.addCallback(gotResult) 
     98        return d 
    12299 
    123100    def test_setRemoteMode_generic(self): 
     
    142119        Mock_Client.clearCalls() 
    143120        X = s.array([0.0, 0.1]) 
    144         d = self.caller.setRemoteMode(None) 
    145         d.addCallback(lambda _: self.caller.call('likelihood', X)) 
     121        d = self.mgr.setRemoteMode(None) 
     122        d.addCallback(lambda _: self.mgr.likelihood(X)) 
    146123        d.addCallback(gotResult) 
    147124        return d 
    148125 
    149126 
    150 class Test_Prior(util.TestCase): 
    151     def test_uniformPrior(self): 
    152         p = model.Prior(dname='uniform', loc=1, scale=2) 
    153         X = p.rvs(1000) 
    154         self.failUnlessEqual(X.shape, (1000,)) 
    155         self.failUnless(s.greater(X, 1).all()) 
    156         self.failUnless(s.less(X, 3).all()) 
    157         self.failUnless(s.equal(p.pdf(X), 0.5).all()) 
    158  
    159  
    160 class Multivariate_BaseCase(util.TestCase): 
    161     y = s.row_stack([ 
    162         util.TS_LIST[k].intersect(util.TS_LIST[1-k])() for k in (0,1)]) 
    163  
    164     def rv(self, fs, fr): 
    165         return s.matrix(linalg.cholesky( 
    166             self.model.covarMatrix(fs, fr), lower=True)) 
     127class BaseCase(util.TestCase): 
     128    N = 100 
     129    params = { 
     130        'a': [0], 
     131        'b': [[0]], 
     132        'cr': [], 
     133        'd': [0], 
     134        'e': [[0]], 
     135        'fs': [1.0], 
     136        'fr': [], 
     137        'g': [0], 
     138        } 
     139 
     140    def modelFactory(self, **kw): 
     141        """ 
     142        Instantiate a model to be tested and set its parameters 
     143        """ 
     144        kw['paramNames'] = ['a', 'b', 'cr', 'd', 'e', 'fs', 'fr', 'g'] 
     145        for name, value in self.params.iteritems(): 
     146            if name != 'y': 
     147                if name in kw: 
     148                    value = kw[name] 
     149                kw[name] = s.array(value) 
     150        if 'y' not in kw: 
     151            if hasattr(self, 'y'): 
     152                kw['y'] = self.y 
     153            else: 
     154                kw['y'] = s.zeros((len(kw['fs']), self.N)) 
     155        return model.Model(**kw) 
     156 
     157    def _covarMatrix(self, cs, cr): 
     158        i = 0 
     159        p = len(cs) 
     160        cv = s.zeros((p, p)) 
     161        for j in xrange(p): 
     162            cv[j,j] = cs[j]**2 
     163            for k in xrange(j+1, p): 
     164                cv[j, k] = cv[k, j] = cr[i] * cs[j] * cs[k] 
     165                i += 1 
     166        return cv 
     167 
     168    def _rv(self, cs, cr): 
     169        return s.matrix(linalg.cholesky(self._covarMatrix(cs, cr), lower=True)) 
    167170     
    168171    def _check_uncorr(self, x, y, plot=True): 
     
    214217 
    215218 
    216 class Test_VAR(Multivariate_BaseCase): 
     219class Test_VAR(BaseCase): 
    217220    def setUp(self): 
     221        self.y = s.row_stack([ 
     222            util.TS_LIST[k].intersect(util.TS_LIST[1-k])() for k in (0,1)]) 
    218223        self.var = model.VAR(self.y) 
    219224 
     
    285290 
    286291 
    287 class Test_Model_misc(util.TestCase): 
     292class Test_Model_misc(BaseCase): 
    288293    def test_covarMatrix(self): 
    289294        def tryCoeffs(cs, cr, x): 
    290295            x = s.array(x) 
    291             modelObj.tsList = [None] * x.shape[0] 
     296            modelObj.y = s.empty((x.shape[0], 100)) 
    292297            y = modelObj.covarMatrix(cs, cr) 
    293298            self.failUnlessEqual(y.shape, x.shape) 
     
    295300                s.absolute(y-x).max() < 1E-8, 
    296301                "Generated array \n%s\n != \n%s" % (y, x)) 
    297          
    298         modelObj = model.Model() 
     302 
     303        modelObj = self.modelFactory() 
    299304        tryCoeffs([1.0], [], [[1.0]]) 
    300305        tryCoeffs([1.0, 1.0], [0.2], [[1.0, 0.2], [0.2, 1.0]]) 
     
    334339        N = 1000 
    335340        z = s.zeros((2,3)) 
    336         modelObj = model.Model() 
     341        modelObj = self.modelFactory() 
    337342        z1 = s.empty(N) 
    338343        z2 = s.empty(N) 
     
    343348        self._check_normality(z1[0.7*N:]) 
    344349        self._check_normality(z2[0.7*N:]) 
    345         self.failUnless(stats.pearsonr(z1, z2)[1] > 0.05) 
    346         if VERBOSE: 
    347             self.fig.add_subplot(111).plot(z1, z2) 
     350        self._check_uncorr(z1, z2) 
    348351 
    349352    def test_decaySamples(self): 
     
    352355        var = model.VAR(x) 
    353356        a = s.zeros(5) 
    354         modelObj = model.Model(tsList=util.TS_LIST
     357        modelObj = self.modelFactory(
    355358        for j in xrange(20): 
    356359            # Keep all coefficients small enough to ensure stability 
     
    373376         
    374377 
    375 class Test_Model_logVolatilities_VAR(Multivariate_BaseCase): 
    376     def setUp(self): 
    377         self.model = model.Model(tsList=util.TS_LIST) 
    378  
    379     def _draw_h(self): 
    380         self.model.cs = s.array([1.0, 1.0]) 
    381         self.model.cr = [0.0] 
    382         self.model.g = s.array([0.0]) 
    383         z = s.randn(self.model.p, self.model.n) 
    384         v = s.array(self.rv(self.model.fs, self.model.fr) * z) 
    385         return self.model.logVolatilities( 
    386             z, v, s.zeros_like(z), self.model.d.copy())[2] 
     378class Test_Model_logVolatilities_VAR(BaseCase): 
     379    N = 1000 
     380     
     381    def _draw_h(self, modelObj): 
     382        modelObj.cs = s.array([1.0, 1.0]) 
     383        modelObj.cr = [0.0] 
     384        modelObj.g = s.array([0.0]) 
     385        z = s.randn(modelObj.p, modelObj.n) 
     386        v = s.array(self._rv(modelObj.fs, modelObj.fr) * z) 
     387        return modelObj.logVolatilities( 
     388            z, v, s.zeros_like(z), modelObj.d.copy())[2] 
    387389 
    388390    def test_univariate_LPF(self): 
    389391        e = 0.95 
    390         self.model.tsList = [self.model.tsList[0]] 
    391         n = self.model.n 
    392         self.model.cs = [1.0] 
    393         self.model.cr = [] 
    394         self.model.d = s.array([0.0]) 
    395         self.model.e = s.array([[e]]) 
    396         self.model.g = s.array([0.0]) 
    397         z = s.randn(1, self.model.n) 
    398         h = self.model.logVolatilities( 
     392        # Univariate model 
     393        modelObj = self.modelFactory( 
     394            y = s.zeros((1, self.N)), 
     395            cs = [1.0], 
     396            cr = [], 
     397            d = s.array([0.0]), 
     398            e = s.array([[e]]), 
     399            g = s.array([0.0])) 
     400        z = s.randn(1, self.N) 
     401        h = modelObj.logVolatilities( 
    399402            z, z.copy(), s.zeros_like(z), s.array([0.0]))[2] 
    400403        # IIR filtering 
     
    402405 
    403406    def test_indep_offset(self): 
    404         n = self.model.n 
    405         self.model.d = s.array([1.0, 1.0]) 
    406         self.model.fs = [1.0, 1.0] 
    407         self.model.fr = [0.0] 
     407        modelObj = self.modelFactory( 
     408            d = s.array([1.0, 1.0]), 
     409            fs = [1.0, 1.0], 
     410            fr = [0.0]) 
    408411        for j in xrange(10): 
    409412            e1, e2 = 0.8*s.rand(2) + 0.1 
    410             self.model.e = s.array([[e1, 0.0], [0.0, e2]]) 
     413            modelObj.e = s.array([[e1, 0.0], [0.0, e2]]) 
    411414            for k in xrange(20): 
    412                 h = self._draw_h(
     415                h = self._draw_h(modelObj
    413416            for m, em in enumerate((e1, e2)): 
    414                 ratio = h[m,n/2:].mean() /  ( 1.0/(1-em) ) 
     417                ratio = h[m,self.N/2:].mean() /  ( 1.0/(1-em) ) 
    415418                self.failUnlessAlmostEqual(ratio, 1.0, 0) 
    416419 
    417420    def test_indep_shocks(self): 
    418         n = self.model.n 
    419421        e1, e2 = 0.95, 0.8 
    420         self.model.d = s.array([0.0, 0.0]) 
    421         self.model.e = s.array([[e1, 0.0], [0.0, e2]]) 
    422         self.model.fs = [1.0, 1.0] 
    423         self.model.fr = [0.0] 
    424         h = self._draw_h() 
     422        modelObj = self.modelFactory( 
     423            d = s.array([0.0, 0.0]), 
     424            e = s.array([[e1, 0.0], [0.0, e2]]), 
     425            fs = [1.0, 1.0], 
     426            fr = [0.0]) 
     427        h = self._draw_h(modelObj) 
    425428        # Uncorrelated 
    426429        self._check_uncorr(h[0,:], h[1,:]) 
     
    428431        self._check_psd(h, e1, e2) 
    429432 
    430     def _check_xcorr(self, dPeak): 
    431         n = self.model.n 
    432         h = self._draw_h(
     433    def _check_xcorr(self, dPeak, **kw): 
     434        modelObj = self.modelFactory(**kw) 
     435        h = self._draw_h(modelObj
    433436        # Correlation 
    434437        nd = 6 
    435438        d = s.arange(-nd, nd+1) 
    436         r = s.array( 
    437             [s.correlate(h[0,nd+lag:n-nd+lag], h[1,nd:n-nd])[0] for lag in d]) 
     439        r = s.array([ 
     440            s.correlate(h[0,nd+lag:self.N-nd+lag], h[1,nd:self.N-nd])[0] 
     441            for lag in d]) 
    438442        lagMetric = r[nd+dPeak] / \ 
    439443                    max(s.concatenate([r[:nd+dPeak], r[nd+dPeak:]])) 
     
    445449 
    446450    def test_xcorr_var(self): 
    447         self.model.d = s.array([0.0, 0.0]) 
    448         self.model.e = s.array([[0.0, 0.9], [0.0, 0.0]]) 
    449         self.model.fs = [1.0, 1.0] 
    450         self.model.fr = [0.0] 
    451         self._check_xcorr(1) 
     451        self._check_xcorr( 
     452            1, 
     453            d = [0.0, 0.0], 
     454            e = [[0.0, 0.9], [0.0, 0.0]], 
     455            fs = [1.0, 1.0], 
     456            fr = [0.0], 
     457            ) 
    452458 
    453459    def test_xcorr_concurrent(self): 
    454         self.model.d = s.array([0.0, 0.0]) 
    455         self.model.e = s.array([[0.0, 0.0], [0.0, 0.0]]) 
    456         self.model.fs = [1.0, 1.0] 
    457         self.model.fr = [0.5] 
    458         self._check_xcorr(0) 
    459  
    460  
    461 class Test_Model_logVolatilities_decorrelate(Multivariate_BaseCase): 
     460        self._check_xcorr( 
     461            0, 
     462            d = [0.0, 0.0], 
     463            e = [[0.0, 0.0], [0.0, 0.0]], 
     464            fs = [1.0, 1.0], 
     465            fr = [0.5], 
     466            ) 
     467 
     468 
     469class Test_Model_logVolatilities_decorrelate(BaseCase): 
     470    N = 1000 
     471    y = s.randn(1, N) 
     472 
    462473    def setUp(self): 
    463         self.model = model.Model() 
    464  
     474        self.model = self.modelFactory() 
     475     
    465476    def _pGenerator(self, low, high): 
    466477        for p in xrange(low, high): 
    467478            # Tweak the model object to make it testable for this p value 
    468             self.model.tsList = [util.TS_LIST[0]] * p 
     479            self.model.y = s.zeros((p, self.N)) 
    469480            self.model.d = s.zeros(p) 
    470481            self.model.e = s.zeros((p, p)) 
     
    481492            # Use the logVolatilities method to decorrelate the innovations 
    482493            # that the caller put into the container I just yielded 
    483             for self.model.c, x in container[1:]: 
     494            for self.model.cr, x in container[1:]: 
    484495                xd = s.zeros_like(x) 
    485496                for k in xrange(x.shape[1]): 
     
    495506     
    496507    def test_basic(self): 
    497         n = 1000 
    498508        for pc in self._pGenerator(2, 4): 
    499509            p = pc[0] 
     
    505515                    print r 
    506516                c = correlation * s.ones(sum([p-k-1 for k in xrange(p)])) 
    507                 x = random.multivariate_normal(s.zeros(p), r, n).transpose() 
     517                x = random.multivariate_normal( 
     518                    s.zeros(p), r, self.N).transpose() 
    508519                pc.append((c, x)) 
    509520 
    510521    def test_complex(self): 
    511         n = 1000 
    512522        for pc in self._pGenerator(2, 7): 
    513523            p = pc[0] 
     
    521531                # Generate some multivariate normal test data having the 
    522532                # generated correlations 
    523                 r = self.model.covarMatrix([1.0], c) 
     533                r = self._covarMatrix(s.ones(p), c) 
    524534                if VERBOSE: 
    525535                    print "\n\n", p 
    526536                    print r 
    527                 x = random.multivariate_normal(s.zeros(p), r, n).transpose() 
     537                x = random.multivariate_normal( 
     538                    s.zeros(p), r, self.N).transpose() 
    528539                pc.append((c, x)) 
    529540 
    530541 
    531 class Model_BC_Mixin(object): 
    532     def _get_model(self): 
    533         if not hasattr(self, '_model'): 
    534             # Instantiate a model to be tested and set its parameters 
    535             if not hasattr(self, 'x'): 
    536                 self.x = s.zeros(self.N) 
    537             self._model = model.Model(tsList=[tseries.TimeSeries( 
    538                 'test', data=s.column_stack([s.arange(self.N), self.x]))]) 
    539             for name, value in self.params.iteritems(): 
    540                 setattr(self._model, name, s.array(value)) 
    541         return self._model 
    542     model = property(_get_model) 
    543  
    544  
    545 class Test_Model_logVolatilities(Model_BC_Mixin, util.TestCase): 
     542class Test_Model_logVolatilities(BaseCase): 
    546543    N = 100 
    547     params = { 
    548         'a': [0], 
    549         'b': [[0]], 
    550         'cs': [1.0], 
    551         'cr': [], 
    552         'd': [0], 
    553         'e': [[0]], 
    554         'fs': [1.0], 
    555         'fr': [], 
    556         'g': [0], 
    557         } 
     544 
     545    def setUp(self): 
     546        self.model = self.modelFactory() 
    558547 
    559548    def _check_L(self, distObj, hValue): 
     
    580569 
    581570 
    582 class Test_Model_likelihood(Model_BC_Mixin, Multivariate_BaseCase): 
     571class Test_Model_likelihood(BaseCase): 
    583572    N = 1000 
    584573    corr = 0.0 
     
    596585 
    597586    def _setupModel(self, **kw): 
    598         # Any special model parameters 
    599         for name, value in kw.iteritems(): 
    600             setattr(self.model, name, s.array(value)) 
     587        self.model = self.modelFactory(**kw) 
    601588        # Simulate a single time series of data per the parameters 
    602589        self.iv = random.multivariate_normal( 
     
    608595        x = s.exp(0.5 * self.h) * self.iv[0,:] 
    609596        # Instantiate a model to be tested and set its parameters 
    610         self.model.tsList=[tseries.TimeSeries( 
    611             'test', data=s.column_stack([s.arange(self.N), x]))] 
    612597        self.x = s.row_stack([x]) 
     598        self.model.y = self.x 
    613599     
    614600    def _runHG(self, N, sigma): 
    615601        L = [] 
    616602        z = s.randn(1, self.N) 
    617         rv = self.rv(self.model.fs, self.model.fr) 
     603        rv = self._rv(self.model.fs, self.model.fr) 
    618604        print "RV\n", rv, "\n" 
    619605        for k in xrange(N): 
    620             L_this = self.model.hybridGibbs(z, self.x, rv, sigma) 
     606            L_this = self.model.hybridGibbs(z, self.x, rv, sigma)[0] 
    621607            L.append(L_this) 
    622608            print "%03d: L=%6.1f" % (k, L_this) 
  • projects/AsynCluster/trunk/svpmc/test/test_params.py

    r166 r167  
    194194                    y[j, k], j*k * (100*j + k), 
    195195                    "Error doing addThese method for j=%d, k=%d" % (j,k)) 
    196  
    197  
    198 class Test_ParameterContainer(util.TestCase): 
    199     pass 
    200  
    201196 
    202197 
     
    245240 
    246241    def test_proposal(self): 
    247         pass 
     242        self.fail("TODO") 
    248243     
  • projects/AsynCluster/trunk/svpmc/test/test_project.py

    r166 r167  
    6060    def test_setupTimeSeries(self): 
    6161        self._parseSpec() 
    62         tsList, titles = self.mgr._setupTimeSeries(self.specDir) 
    63         self.failUnlessEqual(len(tsList), 3) 
    64         lengths = [] 
    65         for tsObject in tsList: 
    66             self.failUnless(isinstance(tsObject, tseries.TimeSeries)) 
    67             lengths.append(len(tsObject)) 
    68         self.failUnlessEqual(min(lengths), max(lengths)) 
     62        tsData, titles = self.mgr._setupTimeSeries(self.specDir) 
     63        self.failUnlessEqual(tsData.shape[0], 3) 
    6964        self.failUnlessEqual(len(titles), 3) 
    7065        for title in titles: 
     
    9287        self._parseSpec() 
    9388        self.mgr.m = 10000 
    94         tsList, seriesTitles = self.mgr._setupTimeSeries(self.specDir) 
    95         tsData = s.row_stack([ts() for ts in tsList]) 
     89        tsData, seriesTitles = self.mgr._setupTimeSeries(self.specDir) 
    9690        paramTitles, dimensions = self.mgr._setupParams() 
    9791        cdf = self.mgr._setupCDF( 
     
    116110 
    117111 
    118 class Mock_ParameterContainer(util.Mock): 
    119     p, xcorrs = 3, 6 
    120     paramNames =  ['a', 'b', 'cr', 'd', 'e', 'fs', 'fr', 'g'] 
    121     paramShapes = [(p,), (p,p), (xcorrs,), (p,), (p,p), (p,), (xcorrs,), (p,)] 
    122  
    123     def __init__(self, scale): 
    124         for k, name in enumerate(self.paramNames): 
    125             array = k * scale * s.ones(self.paramShapes[k]) 
    126             setattr(self, name, array) 
    127         self.h = self.p * scale * s.ones(self.p) 
    128         self.Lx = 0.0 
    129          
    130  
    131112class Test_ProjectManager_writeParams(util.TestCase): 
    132113    def setUp(self): 
     
    139120        parameters = params.FlexArray(len(scales)) 
    140121        for k, scale in enumerate(scales): 
    141             parameters[k] = Mock_ParameterContainer(scale) 
     122            parameters[k] = util.Mock_ParameterContainer(scale) 
    142123        return parameters 
    143124         
  • projects/AsynCluster/trunk/svpmc/test/util.py

    r160 r167  
    162162 
    163163 
     164class Mock_ParameterContainer(Mock): 
     165    p, xcorrs = 3, 6 
     166    paramNames =  ['a', 'b', 'cr', 'd', 'e', 'fs', 'fr', 'g'] 
     167    paramShapes = [(p,), (p,p), (xcorrs,), (p,), (p,p), (p,), (xcorrs,), (p,)] 
     168 
     169    def __init__(self, scale=1.0): 
     170        for k, name in enumerate(self.paramNames): 
     171            array = k * scale * s.ones(self.paramShapes[k]) 
     172            setattr(self, name, array) 
     173        self.h = self.p * scale * s.ones(self.p) 
     174        self.Lx = 0.0 
     175 
     176 
    164177class TestCase(unittest.TestCase): 
    165178    """