Changeset 173

Show
Ignore:
Timestamp:
05/05/08 16:21:36 (8 months ago)
Author:
edsuom
Message:

Starting work on Rao-Blackwellization

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • projects/AsynCluster/trunk/doc/svpmc/example/svpmc.conf

    r171 r173  
    5757a           Distribution    Loc         Scale       a       b 
    5858------------------------------------------------------------------------------- 
    59 :           beta            0.00        0.04        2       4 
     59:           beta            0.00        0.005       2       5 
    6060 
    6161 
     
    7373d           Distribution    Loc         Scale       a       b 
    7474------------------------------------------------------------------------------- 
    75 :           beta            0.0         0.3         2       3 
     75:           beta            0.0         0.4         2       2 
    7676 
    7777 
     
    8989fr          Distribution    Loc         Scale       a       b 
    9090------------------------------------------------------------------------------- 
    91 :           beta            0.0         0.9         2       3 
     91:           beta            0.0         0.9         2       2 
    9292 
    9393 
    9494g           Distribution    Loc         Scale       a       b 
    9595------------------------------------------------------------------------------- 
    96 :           beta           -0.9         1.8         2       2 
     96:           beta           -0.9         1.8         3       2 
  • projects/AsynCluster/trunk/svpmc/model.py

    r172 r173  
    4444    """ 
    4545    remoteMode = False 
    46     timeout = 4
     46    timeout = 8
    4747 
    4848    nodecode = """ 
  • projects/AsynCluster/trunk/svpmc/params.py

    r172 r173  
    348348        return paramContainer 
    349349 
    350     def proposal(self, paramContainer, wiggle): 
     350    #                                    <-- TODO -> 
     351    def proposal(self, paramContainer, v, vMixInfo): 
    351352        """ 
    352353        Returns a new instance of L{ParameterContainer} with a random-walk 
    353354        proposal based on the supplied I{paramContainer}, my priors, and the 
    354         supplied I{wiggle}. 
     355        supplied jump deviation I{v}. 
    355356 
    356357        The returned parameter container object will have a copy of the 
    357358        supplied instance's latent parameter array I{z} and new values of I{Lp} and 
    358359        I{Lj} corresponding to the proposal. 
     360 
     361        The value of I{Lj} is  
    359362        """ 
    360363        if wiggle < 0.0: 
     
    379382                    break 
    380383            else: 
    381                 print "\nWARNING: Failed to generate a valid proposal" 
     384                #print "\nWARNING: Failed to generate a valid proposal" 
    382385                return paramContainer 
    383386            Lp += s.log(pPriors).sum() 
  • projects/AsynCluster/trunk/svpmc/pmc.py

    r172 r173  
    4747        self.rMax = N - self.rMin*(self.P-1) 
    4848        self.updateAllocations() 
     49 
     50    def allocations(self): 
     51        """ 
     52        Returns a list of 2-tuples containing each jump deviation and the 
     53        number of population members currently allocated to it. 
     54        """ 
     55        result = [] 
     56        for k, v in enumerate(self.V): 
     57            result.append((v, self.R[k])) 
     58        return result 
    4959     
    5060    def subsetIndex(self, k): 
     
    186196        def weight(paramContainer): 
    187197            if s.isfinite(paramContainer.Lx): 
    188                 L = paramContainer.Lx + paramContainer.Lp - paramContainer.Lj 
     198                Lj =  
     199                L = paramContainer.Lx + paramContainer.Lp - Lj 
    189200                print "-+"[int(L>-1000)], 
    190201            else: 
     
    213224 
    214225    @defer.deferredGenerator 
    215     def run(self, N_iter, V=None): 
    216         """ 
    217         Does a PMC run with I{N_iter} iterations and the supplied sequence I{V} 
    218         of jump deviations. The portion of the population members allocated to 
    219         each jump variance will go up or down, depending on the performance for 
    220         that setting. 
     226    def run(self, N_iter): 
     227        """ 
     228        Does a PMC run with I{N_iter} iterations and the sequence of jump 
     229        deviations in my I{V} attribute. The portion of the population members 
     230        allocated to each jump variance will go up or down, depending on the 
     231        performance for that setting. 
    221232 
    222233        Returns a deferred that fires when the run is done. No output value is 
     
    226237        @param N_iter: The number of iterations to produce after burn-in. 
    227238 
    228         @param V: A sequence of variance values to use instead of the default. 
    229          
    230239        """ 
    231240        if self.socket: 
     
    233242            yield wfd; wfd.getResult() 
    234243        N_members = self.pm.m 
    235         # The variance settings (default of 6) 
    236         if V is None: 
    237             V = self.V 
    238         allocator = Allocator(N_members, V) 
     244        allocator = Allocator(N_members, self.V) 
    239245        # Initialize some arrays 
    240246        X = self.initialPopulation(N_members) 
     
    245251            print "\n%03d:" % (i+1,), 
    246252            dList, resultList = [], [] 
     253            self.mixInfo = allocator.allocations() 
    247254            for v, I, d in allocator.assembler(resultList): 
    248255                d.addCallback(lambda _: self.weightedProposals(X[I], v)) 
     
    252259            if i > 0: 
    253260                self.pm.writeParams(X) 
     261            # "Wait" here for all the proposals to be evaluated 
    254262            wfd = defer.waitForDeferred(defer.DeferredList(dList)) 
    255263            yield wfd 
    256264            wfd.getResult() 
    257265            XP, W = resultList 
    258             #print "\n   %s" % \ 
    259             #      (" ".join(["%9d" % ii for ii in s.arange(N_members)]),) 
    260             #print "W: %s" % (" ".join(["%+9.2g" % w for w in W]),) 
    261             W = W[s.isfinite(W).nonzero()[0]] 
    262             if len(W): 
     266            I0 = s.isfinite(W).nonzero()[0] 
     267            if len(I0): 
    263268                # Resample everything together 
    264                 I = self.resampler(W, N_members) 
    265                 X = XP[I] 
    266                 #print "I: %s\n" % (" ".join(["%9d" % ii for ii in I]),) 
     269                I1 = self.resampler(W[I0], N_members) 
     270                X = XP[I0][I1] 
    267271                allocator.updateAllocations(I) 
    268272            else: 
    269273                # Nothing in the proposed population had any plausibility 
    270274                allocator.updateAllocations() 
    271                 #print "I []" 
    272275        wfd = defer.waitForDeferred(self.pm.done()) 
    273276        yield wfd 
  • projects/AsynCluster/trunk/svpmc/project.py

    r172 r173  
    4242    def shutdown(self): 
    4343        return self.defer.succeed(None) 
     44 
     45 
     46class CDF_Wrapper(object): 
     47    """ 
     48    With python2.5, as of 2008-05-01, accessing a NetCDF variable object with a 
     49    slice raises a 'Floating Point Exception'! So I am a wrapper for the poor 
     50    vulnerable little thing... 
     51 
     52    B{YAGNI Strikes Again!!!!} 
     53 
     54    Just installed the latest development version (2.7.8) of Scientific from 
     55    http://sourcesup.cru.fr/frs/download.php/1835/ScientificPython-2.7.8.tar.gz 
     56    and problem solved. 
     57    """ 
     58    class VariableDict_Wrapper(object): 
     59        """ 
     60        I emulate the I{variables} dict-like object of an open NetCDF file 
     61        object. 
     62        """ 
     63        class Variable_Wrapper(object): 
     64            """ 
     65            I emulate a single variable of an open NetCDF file object. 
     66            """ 
     67            def __init__(self, var, *dims): 
     68                self.var = var 
     69                self.dims = dims 
     70 
     71            def __getitem__(self, key): 
     72                # TODO 
     73                pass 
     74 
     75            def __setitem__(self, key, value): 
     76                print "SI", key, value 
     77 
     78         
     79        def __init__(self, variables, dimensions): 
     80            self._variables = {} 
     81            self.variables = variables 
     82            self.dimensions = dimensions 
     83 
     84        def __getitem__(self, name): 
     85            if name not in self._variables: 
     86                var = self.variables[name] 
     87                dims = [self.dimensions[dimName] for dimName in var.dimensions] 
     88                self._variables[name] = self.Variable_Wrapper(var, *dims) 
     89            return self._variables[name] 
     90             
     91             
     92    def __init__(self, cdf): 
     93        self.cdf = cdf 
     94        self.variables = self.VariableDict_Wrapper( 
     95            self.cdf.variables, self.cdf.dimensions) 
     96 
     97    def __getattr__(self, name): 
     98        return getattr(self.cdf, name) 
     99 
     100    def __setattr__(self, name, value): 
     101        if name not in ('cdf', 'variables'): 
     102            setattr(self.cdf, name, value) 
     103        else: 
     104            object.__setattr__(self, name, value) 
    44105 
    45106 
     
    91152        self.p, self.n = tsData.shape 
    92153        paramTitles, dimensions = self._setupParams() 
     154        self.mgr = model.ModelManager(self, tsData) 
    93155        self._setupCDF( 
    94156            os.path.join(specDir, ncFileName), 
    95157            tsData, seriesTitles, paramTitles, dimensions) 
    96         self.mgr = model.ModelManager(self, tsData) 
    97      
     158        # Write the observation data 
     159        for k, title in enumerate(seriesTitles): 
     160            obs = self.cdf.variables['observations'] 
     161            obs[k,:] = tsData[k,:].astype('f') 
     162            setattr(obs, "series_%02d" % (k,), title) 
     163 
    98164    def _parseSpec(self, filePath): 
    99165        tables = {} 
     
    206272        """ 
    207273        """ 
    208         cdf = self.cdf = NetCDF.NetCDFFile(filePath, 'w') 
     274        cdf = NetCDF.NetCDFFile(filePath, 'w') 
     275        self.cdf = cdf 
     276        #self.cdf = CDF_Wrapper(cdf) 
    209277        cdf.title = self.tables['project'][0][0] 
    210278        # Dimensions 
     
    217285        obs.long_name = "Observations, %d time series " % self.p +\ 
    218286                        "with %d samples each" % self.n 
    219         for k, title in enumerate(sTitles): 
    220             obs[k,:] = tsData[k,:].astype('f') 
    221             setattr(obs, "series_%02d" % (k,), title) 
    222287        # Last-Sample Log-Volatility 
    223288        logVol = cdf.createVariable( 
     
    234299        # Done setting up, save what we've got thus far 
    235300        cdf.sync() 
    236         return cdf 
    237301             
    238302    def writeParams(self, parameters): 
  • projects/AsynCluster/trunk/svpmc/test/test_pmc.py

    r169 r173  
    4141    def test_init(self): 
    4242        self.failUnlessElementsEqual(self.allocator.R, [34, 33, 33]) 
     43 
     44    def test_allocations(self): 
     45        self.failUnlessEqual( 
     46            self.allocator.allocations(), 
     47            [(0.1,34), (0.01,33), (0.001,33)]) 
    4348     
    4449    def test_subsetIndex(self): 
  • projects/AsynCluster/trunk/svpmc/test/test_project.py

    r168 r173  
    4343 
    4444    def _parseSpec(self): 
    45         specFile = os.path.join(self.specDir, "project-spec.txt") 
     45        specFile = os.path.join(self.specDir, "svpmc.conf") 
    4646        self.mgr.tables = self.mgr._parseSpec(specFile) 
    4747        return self.mgr.tables 
     
    8989        tsData, seriesTitles = self.mgr._setupTimeSeries(self.specDir) 
    9090        paramTitles, dimensions = self.mgr._setupParams() 
    91         cdf = self.mgr._setupCDF( 
     91        self.mgr._setupCDF( 
    9292            cdfPath, tsData, seriesTitles, paramTitles, dimensions) 
    9393        # Make sure we can write to the open file 
     94        cdf = self.mgr.cdf 
    9495        var = cdf.variables['a'] 
    9596        x = s.rand(self.mgr.p, 2).astype('f') 
     
    114115        projectDir = os.path.dirname(__file__) 
    115116        self.cdfPath = os.path.join(projectDir, "svpmc.nc") 
    116         self.specFile = os.path.join(projectDir, "project-spec.txt") 
     117        self.specFile = os.path.join(projectDir, "svpmc.conf") 
    117118        self.mgr = project.ProjectManager(self.specFile, m=5) 
    118119