Changeset 175

Show
Ignore:
Timestamp:
05/08/08 23:30:51 (7 months ago)
Author:
edsuom
Message:

Got D-Kernel PMC running with what I hope is Rao-Blackwellization

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • projects/AsynCluster/trunk/asyncluster/master/control.py

    r128 r175  
    343343        return d 
    344344 
     345    def remote_wall(self, message): 
     346        """ 
     347        """ 
     348        return self.ctl.allRemote('message', message) 
     349 
    345350    def remote_registerClasses(self, *args): 
    346351        """ 
  • projects/AsynCluster/trunk/asyncluster/ndm/client.py

    r127 r175  
    114114    def remote_message(self, message): 
    115115        """ 
    116         Displays a pop-up message for the current user
    117         """ 
    118         pass 
     116        Displays a pop-up message on the session window, if one is present
     117        """ 
     118        self.main.message(message) 
    119119 
    120120    @checkTrust 
  • projects/AsynCluster/trunk/asyncluster/ndm/node.py

    r127 r175  
    123123        return defer.succeed(None) 
    124124 
     125    def message(self, msg): 
     126        """ 
     127        If there is a session underway, displays the message on it. 
     128        """ 
     129        if hasattr(self, 'sessionWindow'): 
     130            self.sessionWindow.status(msg) 
     131 
    125132 
    126133def run(): 
  • projects/AsynCluster/trunk/console

    r127 r175  
    108108        if cmd == 'user': 
    109109            cmd = 'userAction' 
     110        elif cmd == 'wall': 
     111            args = (" ".join(args),) 
    110112        elif cmd == 'resetup': 
    111113            srcDir = args[0] 
  • projects/AsynCluster/trunk/doc/svpmc/example/svpmc.conf

    r174 r175  
    2727Jumps 
    2828------------------------------------------------------------------------------- 
    29 0.5, 0.1, 0.02, 0.004 
     290.25, 0.05, 0.01, 0.002 
    3030 
    3131 
  • projects/AsynCluster/trunk/doc/svpmc/example/sv_pmc.py

    r171 r175  
    3939    p = OptionParser(usage=__doc__) 
    4040    p.add_option( 
    41         "-s", "--sigma", 
    42         dest="sigma", action="store", type="float",  
    43         help="Jump deviation for the log-volatility simulations") 
    44     p.add_option( 
    4541        "-i", "--N_iter", 
    4642        dest="N_iter", action="store", type="int", 
     
    6258        dest="socket", action="store", 
    6359        help="Path of UNIX-domain socket for AsynCluster master server") 
    64     p.set_defaults( 
    65         sigma=0.5, N_iter=100, N_members=10000, 
     60    p.add_option( 
     61        "-p", "--profile", 
     62        dest="profile", action="store_true", 
     63        help="Run with profiling") 
     64 
     65    p.set_defaults(N_iter=100, N_members=10000, 
    6666        ncFileName="svpmc.nc", socket="/tmp/.ndm") 
    6767    return p.parse_args() 
     
    8080 
    8181 
    82 def run(pmcObj, N_iter, V=None): 
     82def run(pmcObj, N_iter, profile=False): 
    8383    """ 
    8484    Have this called when the reactor starts. 
     
    8888        print "\n%s\n" % ("-"*79,) 
    8989        reactor.stop() 
    90      
    91     d = pmcObj.run(N_iter, V) 
    92     d.addCallbacks(lambda _: reactor.stop(), oops) 
    93     return d 
     90 
     91    def reallyRun(): 
     92        d = pmcObj.run(N_iter) 
     93        d.addCallbacks(lambda _: reactor.stop(), oops) 
     94 
     95    if profile: 
     96        print "Running with profiler..." 
     97        import pstats, cProfile as profile 
     98        prof = profile.Profile() 
     99        try: 
     100            prof.runcall(reallyRun) 
     101            prof.dump_stats("profile.data") 
     102        except SystemExit: 
     103            pass 
     104        stats = pstats.Stats("profile.data") 
     105        stats.sort_stats("cumulative").print_stats() 
     106    else: 
     107        reallyRun() 
    94108 
    95109 
     
    106120        specFile, opts.ncFileName, opts.N_members) 
    107121    pmcObj = pmc.PMC(projectManager, socket) 
    108     reactor.callWhenRunning(run, pmcObj, opts.N_iter
     122    reactor.callWhenRunning(run, pmcObj, opts.N_iter, profile=opts.profile
    109123    reactor.run() 
    110124 
  • projects/AsynCluster/trunk/svpmc/model.py

    r173 r175  
    123123                # An error from the remote likelihood method call is treated as 
    124124                # infinitely low likelihood 
    125                 result = [-s.inf, [], []] 
     125                result = (-s.inf, [], [], 0) 
    126126            elif isinstance(result, str): 
    127127                # Unpack string result from remote call 
    128128                result = list(pack.Unpacker(result)) 
    129             for k, name in enumerate(('Lx', 'h', 'z')): 
     129            for k, name in enumerate(('Lx', 'h', 'z', 'acceptanceRate')): 
    130130                setattr(paramContainer, name, result[k]) 
    131131            return paramContainer 
     
    184184    _logU_index = -1 
    185185 
    186     keyAttrs = {'y':None, 'Mv':20, 'Mz':30} 
     186    keyAttrs = {'y':None, 'Mv':40, 'Mz':30} 
    187187 
    188188    #--- Properties ----------------------------------------------------------- 
     
    305305        return L0, L, h[:,1:] 
    306306 
    307     def hybridGibbs(self, z, x, rv, sigma, tol=1E-4): 
     307    def hybridGibbs(self, z, x, rv, sigma, tol=1E-3): 
    308308        """ 
    309309        Does one iteration of a hybrid Gibbs sampler for the log-volatilities, 
     
    312312        Updates the IID normal variates in place. Returns the likelihood of the 
    313313        innovations in I{x}, given the simulated log-volatilities, along with 
    314         the last sample's multivariate log-volatility value. 
     314        the last sample's multivariate log-volatility value and the fractional 
     315        acceptance rate of the MCMC steps. 
    315316 
    316317        The method will account for the effect of log-volatility proposals on 
     
    320321        """ 
    321322        L_total = 0 
     323        acceptances = 0 
    322324        N = self.decaySamples(tol) 
    323325        # Initialize volatility shocks from cross-correlation of the IID 
     
    345347                z[:,k] = zp[:,k] 
    346348                v[:,k] = vp[:,k] 
     349                acceptances += 1 
    347350            # Update stuff for the next sample 
    348351            h0 = LV[2][:,0] 
     
    350353            # If the likelihood at this point is so bad that the parameter is 
    351354            # guaranteed not to be resampled, just bail out now and save time 
    352             if L_total < -1E20
    353                 return -s.inf, s.zeros_like(h0) 
    354         return L_total, h0 
     355            if L_total < -1E6
     356                return -s.inf, s.zeros_like(h0), 0.0 
     357        return L_total, h0, float(acceptances)/self.n 
    355358     
    356359 
     
    383386        If a L{linalg.LinAlgError} is raised due to an invalid correlation 
    384387        matrix parameter, the method returns with no result. Otherwise, it 
    385         returns a list containing the following values reached at the end of 
     388        returns a tuple containing the following values reached at the end of 
    386389        the log-volatility simulation: 
    387390         
     
    391394 
    392395            3. The IID normal variates underlying the log-volatilities. 
     396 
     397            4. The mean acceptance rate of the Metropolis-Hastings proposals. 
    393398         
    394399        The returned likelihood does not consider the prior probability of the 
     
    414419        # one along with the state of the IID variate vector at that point, 
    415420        # bailing out with no result if invalid parameter raises exception 
     421        acceptRates = [] 
    416422        try: 
    417423            for k in xrange(self.Mv-1): 
    418                 self.hybridGibbs(z, x, rv, sigma
     424                acceptRates.append(self.hybridGibbs(z, x, rv, sigma)[2]
    419425        except linalg.LinAlgError: 
    420426            return 
    421         return list(self.hybridGibbs(z, x, rv, sigma)) + [z] 
    422      
     427        L, h0, thisRate = self.hybridGibbs(z, x, rv, sigma) 
     428        return L, h0, z, sum(acceptRates + [thisRate])/self.Mv 
     429     
  • projects/AsynCluster/trunk/svpmc/pmc.py

    r174 r175  
    140140 
    141141    """ 
    142     chunkSize = 100 
    143     initialSigma = 0.0
     142    chunkSize = 500 
     143    initialSigma = 0.
    144144     
    145145    def __init__(self, projectManager, socket=None): 
     
    179179                paramContainer, vIndex, self.allocator.W) 
    180180        return XP 
    181  
     181     
    182182    @defer.deferredGenerator 
    183183    def weightedProposals(self, X, vIndex): 
     
    200200            if s.isfinite(paramContainer.Lx): 
    201201                L = paramContainer.Lx + paramContainer.Lp - paramContainer.Lj 
    202                 print "-+"[int(L>-1000)], 
     202                info = " ".join([ 
     203                    "%+12.2f" % (getattr(paramContainer, x),) 
     204                    for x in ("Lx", "Lp", "Lj")]) 
     205                info += "\t\t%02d%%" % (100*paramContainer.acceptanceRate,) 
    203206            else: 
    204                 print "|", 
     207                info = "" 
    205208                L = -s.inf 
    206             sys.stdout.flush(
     209            print "%6.4f\t%s" % (self.pm.V[vIndex], info
    207210            return L 
    208211         
     
    253256              % (N_iter, N_members) 
    254257        for i in xrange(N_iter): 
    255             print "\n%03d:" % (i+1,), 
    256             self.allocator.setAllocations(self.R) 
     258            print "\n%03d\n%s" % (i+1, "-"*79) 
    257259            dList, resultList = [], [] 
    258260            for vIndex, I, d in self.allocator.assembler(resultList): 
     
    273275                I1 = self.resampler(W[I0], N_members) 
    274276                X = XP[I0][I1] 
    275                 self.allocator.updateAllocations(I
     277                self.allocator.updateAllocations(I0[I1]
    276278            else: 
    277279                # Nothing in the proposed population had any plausibility 
  • projects/AsynCluster/trunk/svpmc/test/test_model.py

    r168 r175  
    4747        h = s.zeros(self.p) 
    4848        z = s.zeros(self.n) 
    49         return [likelihoodFunc(paramContainer, self.drift), h, z] 
     49        return likelihoodFunc(paramContainer, self.drift), h, z, 0.44 
    5050 
    5151 
     
    8282        self.JobClient = model.jobs.JobClient 
    8383        model.jobs.JobClient = Mock_Client 
     84        # TODO: Need mock project manager 
    8485        self.mgr = model.ModelManager( 
    8586            util.PARAM_NAMES, s.zeros((self.model.p, self.model.n))) 
  • projects/AsynCluster/trunk/svpmc/test/test_pmc.py

    r174 r175  
    3737        self.N = 100 
    3838        self.V = [0.1, 0.01, 0.001] 
    39         self.allocator = pmc.Allocator(self.N, len(self.V)) 
     39        self.D = len(self.V) 
     40        self.allocator = pmc.Allocator(self.N, self.D) 
    4041 
    4142    def test_init(self): 
     
    7273            dList.append(d) 
    7374        return defer.DeferredList(dList).addCallback(check) 
     75 
     76    @defer.deferredGenerator 
     77    def test_updateAllocations_lopsided(self): 
     78        for favoredBin in xrange(self.D): 
     79            dList, resultList = [], [] 
     80            for k, I, d in self.allocator.assembler(resultList): 
     81                if k == favoredBin: 
     82                    magic_I = I[0] 
     83                d.addCallback(lambda _: (s.zeros_like(I),)) 
     84                dList.append(d) 
     85            wfd = defer.waitForDeferred(defer.DeferredList(dList)) 
     86            yield wfd 
     87            wfd.getResult() 
     88            # Check that the favored bin is favored in the new allocations 
     89            self.allocator.updateAllocations(magic_I * s.ones(self.D)) 
     90            self.failUnlessEqual(self.allocator.R[favoredBin], 96) 
    7491 
    7592 
  • projects/AsynCluster/trunk/svpmc/test/test_weave.py

    r164 r175  
    5656 
    5757    def __call__(self, x): 
    58         return self.inline('x')[0] 
     58        self.inline('x') 
     59        return x[0] 
    5960     
    6061    def foo(self, x): 
    61         return self.inline('x', 'y', x=2*s.array([x]))[0] 
     62        x = 2*s.array([x]) 
     63        self.inline('x', 'y') 
     64        return x[0] 
    6265 
    6366 
  • projects/AsynCluster/trunk/svpmc/weave.py

    r171 r175  
    9090        the variable I{return_val}, is returned. 
    9191        """ 
     92        local_dict = kw 
    9293        frame = inspect.currentframe() 
    9394        methodName = frame.f_back.f_code.co_name 
     
    9697            for varName in args: 
    9798                if varName in kw: 
    98                     value = kw[varName] 
    99                 elif varName in callerVarNames: 
    100                     value = frame.f_back.f_locals[varName] 
     99                    continue 
     100                if varName in callerVarNames: 
     101                    local_dict[varName] = frame.f_back.f_locals[varName] 
    101102                elif hasattr(self, varName): 
    102                     value = getattr(self, varName) 
     103                    local_dict[varName] = getattr(self, varName) 
    103104                else: 
    104105                    raise AttributeError( 
    105106                        "Variable '%s' not defined " % varName +\ 
    106107                        "in keyword, caller, or instance namespace") 
    107                 exec "%s = value" % varName 
    108108        finally: 
    109109            # Avoid cycle problems, per Python Library Reference 3.11.4 
    110110            del frame 
    111111        return inline( 
    112             self.code[methodName], 
    113             args, extra_compile_args=['-w'], support_code=self.code['support']) 
     112            self.code[methodName], args, local_dict, 
     113            extra_compile_args=['-w'], support_code=self.code['support']) 
    114114 
    115115