Changeset 167
- Timestamp:
- 04/30/08 13:37:56 (7 months ago)
- Files:
-
- projects/AsynCluster/trunk/svpmc/model.py (modified) (11 diffs)
- projects/AsynCluster/trunk/svpmc/project.py (modified) (4 diffs)
- projects/AsynCluster/trunk/svpmc/test/test_model.py (modified) (21 diffs)
- projects/AsynCluster/trunk/svpmc/test/test_params.py (modified) (2 diffs)
- projects/AsynCluster/trunk/svpmc/test/test_project.py (modified) (4 diffs)
- projects/AsynCluster/trunk/svpmc/test/util.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
projects/AsynCluster/trunk/svpmc/model.py
r166 r167 73 73 M = modelObj 74 74 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)() 78 80 79 81 ########################################################################### 80 82 """ 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) 83 85 self.queue = NullQueue(1) 84 86 reactor.addSystemEventTrigger( … … 114 116 return d 115 117 116 def likelihood(self, paramContainer, wiggle, remote=False, local=False):118 def likelihood(self, paramContainer, sigma, remote=False, local=False): 117 119 """ 118 120 Computes the log-likelihood of the parameters in the supplied … … 124 126 125 127 Returns a deferred that fires with a reference to the paramContainer 126 when the likelihood computation is done and theit has been updated.127 """ 128 def got PackedLikelihood(result):128 when the likelihood computation is done and it has been updated. 129 """ 130 def gotLikelihood(result): 129 131 if result is None: 130 132 # An error from the remote likelihood method call is treated as 131 133 # 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)) 139 138 for k, name in enumerate(('Lx', 'z', 'h')): 140 139 setattr(paramContainer, name, result[k]) … … 143 142 if (remote or self.remoteMode) and not local: 144 143 d = self.client.run( 145 'likelihood', paramContainer, wiggle, timeout=self.timeout) 146 d.addCallback(gotPackedLikelihood) 144 'likelihood', paramContainer, sigma, timeout=self.timeout) 147 145 else: 148 146 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) 152 149 153 150 … … 187 184 process with correlated volatility (v) and return (w) shocks. 188 185 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. 191 187 192 188 @ivar Mv: Number of volatility draws per likelihood evaluation. … … 197 193 _logU_index = -1 198 194 199 keyAttrs = {' tsList':None, 'Mv':50, 'Mz':50}195 keyAttrs = {'y':None, 'Mv':50, 'Mz':50} 200 196 201 197 #--- Properties ----------------------------------------------------------- 202 198 203 199 def _get_p(self): 204 return len(self.tsList)200 return self.y.shape[0] 205 201 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 itself214 tsObj = tsObj.intersect(self.tsList[k])215 y[k,:] = tsObj()216 self.cache['y'] = y217 return self.cache['y']218 y = property(_get_y)219 202 220 203 def _get_n(self): … … 290 273 """ 291 274 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) 294 276 return z 295 277 … … 323 305 y[:,0] = s.sqrt(1 - self.g**2) 324 306 y[:,1] = s.log(s.sqrt(2*s.pi) * y[:,0]) 325 # Inverse of concurrent cross-correlations between innovation shocks326 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( 328 310 self.covarMatrix(s.ones(self.p), self.cr), lower=True)) 329 311 self.cache['lv_work'] = y, ri … … 351 333 # variates, if positive definite... 352 334 v = s.array(rv*z) 353 if v is None:354 # (If not, return worst possible likelihood for this illegal fs, fr355 # parameter combination)356 return357 335 # ...and initial log-volatilites, from the offset alone... 358 336 h0 = self.d … … 404 382 cross-correlation to form volatility shocks, and VAR(1) to form the 405 383 log-volatilities. The Metropolis-Hastings proposals are scaled based on 406 the supplied fractional I{ wiggle}. The simulation is governed by the384 the supplied fractional I{sigma}. The simulation is governed by the 407 385 log-likelihood of my observation data given the supplied parameters and 408 386 the simulated log-volatilities. 409 387 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: 412 392 413 393 1. The value of the log-likelihood. … … 428 408 z = paramContainer.z.copy() 429 409 # Concurrent cross-correlations between volatility shocks, bail out 430 # with worst possible likelihoodif invalid410 # with no result if invalid 431 411 try: 432 412 rv = s.matrix(linalg.cholesky( 433 413 self.covarMatrix(self.fs, self.fr), lower=True)) 434 414 except linalg.LinAlgError: 435 return -s.inf, z415 return 436 416 # Innovations as residuals of the reversed VAR(1) 437 417 x = self.var.reverse(self.a, self.b) 438 418 # 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 442 426 return list(self.hybridGibbs(z, x, rv, sigma)) + [z] 443 427 projects/AsynCluster/trunk/svpmc/project.py
r166 r167 68 68 specDir = os.path.dirname(specFile) 69 69 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) 72 71 self.p, self.n = tsData.shape 73 72 paramTitles, dimensions = self._setupParams() … … 75 74 os.path.join(specDir, ncFileName), 76 75 tsData, seriesTitles, paramTitles, dimensions) 77 self.mgr = model.ModelManager(self.paramNames, ts List)76 self.mgr = model.ModelManager(self.paramNames, tsData) 78 77 79 78 def _parseSpec(self, filePath): … … 108 107 directory. 109 108 110 Returns a list of the objects along with a list of the time series111 ti tles.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. 112 111 """ 113 112 prevObj = None … … 123 122 titles.append(title) 124 123 prevObj = tsObject 125 return tsList, titles124 return s.row_stack([ts() for ts in tsList]), titles 126 125 127 126 def _setupParams(self): projects/AsynCluster/trunk/svpmc/test/test_model.py
r161 r167 36 36 37 37 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,)) 38 def likelihoodFunc(paramContainer, drift): 39 return (-(paramContainer.a - drift)**2).sum() 62 40 63 41 64 42 class 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) 68 48 69 49 … … 91 71 # Adapted from the manager's nodecode string 92 72 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 d97 if args[0] == 'callModel':98 method = getattr(self.model, args[2])99 73 return util.deferToLater( 100 pack.packwrap(method)(*args[3:]), delay=0.01)101 102 103 class Test_Model Caller_Basics(util.TestCase):74 self.model.likelihood, args[1], args[2], delay=0.01) 75 76 77 class Test_ModelManager_Basics(util.TestCase): 104 78 def setUp(self): 105 79 self.model = Mock_Model() 106 80 self.JobClient = model.jobs.JobClient 107 81 model.jobs.JobClient = Mock_Client 108 self. caller = model.ModelCaller(self.model)82 self.mgr = model.ModelManager(self.model) 109 83 110 84 def tearDown(self): … … 113 87 def test_localIsDefault(self): 114 88 def gotResult(result): 115 self.failUnlessElementsEqual(result, s.exp(-X**2)) 89 self.failUnlessEqual( 90 result[0], likelihoodFunc(paramContainer, 1.5)) 116 91 self.nextCall(Mock_Model.calls) 117 92 self.nextCall('likelihood') 118 93 119 94 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 122 99 123 100 def test_setRemoteMode_generic(self): … … 142 119 Mock_Client.clearCalls() 143 120 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)) 146 123 d.addCallback(gotResult) 147 124 return d 148 125 149 126 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)) 127 class 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)) 167 170 168 171 def _check_uncorr(self, x, y, plot=True): … … 214 217 215 218 216 class Test_VAR( Multivariate_BaseCase):219 class Test_VAR(BaseCase): 217 220 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)]) 218 223 self.var = model.VAR(self.y) 219 224 … … 285 290 286 291 287 class Test_Model_misc( util.TestCase):292 class Test_Model_misc(BaseCase): 288 293 def test_covarMatrix(self): 289 294 def tryCoeffs(cs, cr, x): 290 295 x = s.array(x) 291 modelObj. tsList = [None] * x.shape[0]296 modelObj.y = s.empty((x.shape[0], 100)) 292 297 y = modelObj.covarMatrix(cs, cr) 293 298 self.failUnlessEqual(y.shape, x.shape) … … 295 300 s.absolute(y-x).max() < 1E-8, 296 301 "Generated array \n%s\n != \n%s" % (y, x)) 297 298 modelObj = model.Model()302 303 modelObj = self.modelFactory() 299 304 tryCoeffs([1.0], [], [[1.0]]) 300 305 tryCoeffs([1.0, 1.0], [0.2], [[1.0, 0.2], [0.2, 1.0]]) … … 334 339 N = 1000 335 340 z = s.zeros((2,3)) 336 modelObj = model.Model()341 modelObj = self.modelFactory() 337 342 z1 = s.empty(N) 338 343 z2 = s.empty(N) … … 343 348 self._check_normality(z1[0.7*N:]) 344 349 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) 348 351 349 352 def test_decaySamples(self): … … 352 355 var = model.VAR(x) 353 356 a = s.zeros(5) 354 modelObj = model.Model(tsList=util.TS_LIST)357 modelObj = self.modelFactory() 355 358 for j in xrange(20): 356 359 # Keep all coefficients small enough to ensure stability … … 373 376 374 377 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] 378 class 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] 387 389 388 390 def test_univariate_LPF(self): 389 391 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( 399 402 z, z.copy(), s.zeros_like(z), s.array([0.0]))[2] 400 403 # IIR filtering … … 402 405 403 406 def test_indep_offset(self): 404 n = self.model.n405 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]) 408 411 for j in xrange(10): 409 412 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]]) 411 414 for k in xrange(20): 412 h = self._draw_h( )415 h = self._draw_h(modelObj) 413 416 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) ) 415 418 self.failUnlessAlmostEqual(ratio, 1.0, 0) 416 419 417 420 def test_indep_shocks(self): 418 n = self.model.n419 421 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) 425 428 # Uncorrelated 426 429 self._check_uncorr(h[0,:], h[1,:]) … … 428 431 self._check_psd(h, e1, e2) 429 432 430 def _check_xcorr(self, dPeak ):431 n = self.model.n432 h = self._draw_h( )433 def _check_xcorr(self, dPeak, **kw): 434 modelObj = self.modelFactory(**kw) 435 h = self._draw_h(modelObj) 433 436 # Correlation 434 437 nd = 6 435 438 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]) 438 442 lagMetric = r[nd+dPeak] / \ 439 443 max(s.concatenate([r[:nd+dPeak], r[nd+dPeak:]])) … … 445 449 446 450 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 ) 452 458 453 459 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 469 class Test_Model_logVolatilities_decorrelate(BaseCase): 470 N = 1000 471 y = s.randn(1, N) 472 462 473 def setUp(self): 463 self.model = model.Model()464 474 self.model = self.modelFactory() 475 465 476 def _pGenerator(self, low, high): 466 477 for p in xrange(low, high): 467 478 # Tweak the model object to make it testable for this p value 468 self.model. tsList = [util.TS_LIST[0]] * p479 self.model.y = s.zeros((p, self.N)) 469 480 self.model.d = s.zeros(p) 470 481 self.model.e = s.zeros((p, p)) … … 481 492 # Use the logVolatilities method to decorrelate the innovations 482 493 # 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:]: 484 495 xd = s.zeros_like(x) 485 496 for k in xrange(x.shape[1]): … … 495 506 496 507 def test_basic(self): 497 n = 1000498 508 for pc in self._pGenerator(2, 4): 499 509 p = pc[0] … … 505 515 print r 506 516 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() 508 519 pc.append((c, x)) 509 520 510 521 def test_complex(self): 511 n = 1000512 522 for pc in self._pGenerator(2, 7): 513 523 p = pc[0] … … 521 531 # Generate some multivariate normal test data having the 522 532 # generated correlations 523 r = self. model.covarMatrix([1.0], c)533 r = self._covarMatrix(s.ones(p), c) 524 534 if VERBOSE: 525 535 print "\n\n", p 526 536 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() 528 539 pc.append((c, x)) 529 540 530 541 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): 542 class Test_Model_logVolatilities(BaseCase): 546 543 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() 558 547 559 548 def _check_L(self, distObj, hValue): … … 580 569 581 570 582 class Test_Model_likelihood( Model_BC_Mixin, Multivariate_BaseCase):571 class Test_Model_likelihood(BaseCase): 583 572 N = 1000 584 573 corr = 0.0 … … 596 585 597 586 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) 601 588 # Simulate a single time series of data per the parameters 602 589 self.iv = random.multivariate_normal( … … 608 595 x = s.exp(0.5 * self.h) * self.iv[0,:] 609 596 # 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]))]612 597 self.x = s.row_stack([x]) 598 self.model.y = self.x 613 599 614 600 def _runHG(self, N, sigma): 615 601 L = [] 616 602 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) 618 604 print "RV\n", rv, "\n" 619 605 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] 621 607 L.append(L_this) 622 608 print "%03d: L=%6.1f" % (k, L_this) projects/AsynCluster/trunk/svpmc/test/test_params.py
r166 r167 194 194 y[j, k], j*k * (100*j + k), 195 195 "Error doing addThese method for j=%d, k=%d" % (j,k)) 196 197 198 class Test_ParameterContainer(util.TestCase):199 pass200 201 196 202 197 … … 245 240 246 241 def test_proposal(self): 247 pass242 self.fail("TODO") 248 243 projects/AsynCluster/trunk/svpmc/test/test_project.py
r166 r167 60 60 def test_setupTimeSeries(self): 61 61 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) 69 64 self.failUnlessEqual(len(titles), 3) 70 65 for title in titles: … … 92 87 self._parseSpec() 93 88 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) 96 90 paramTitles, dimensions = self.mgr._setupParams() 97 91 cdf = self.mgr._setupCDF( … … 116 110 117 111 118 class Mock_ParameterContainer(util.Mock):119 p, xcorrs = 3, 6120 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.0129 130 131 112 class Test_ProjectManager_writeParams(util.TestCase): 132 113 def setUp(self): … … 139 120 parameters = params.FlexArray(len(scales)) 140 121 for k, scale in enumerate(scales): 141 parameters[k] = Mock_ParameterContainer(scale)122 parameters[k] = util.Mock_ParameterContainer(scale) 142 123 return parameters 143 124 projects/AsynCluster/trunk/svpmc/test/util.py
r160 r167 162 162 163 163 164 class 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 164 177 class TestCase(unittest.TestCase): 165 178 """
