Changeset 2942


Ignore:
Timestamp:
Jul 25, 2017 3:06:04 PM (6 years ago)
Author:
vondreele
Message:

cleanup anneal MC/SA routine; remove extraneous parameters
add timing & counting to anneal

Location:
branch/2frame
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • branch/2frame/GSASIIdataGUI.py

    r2940 r2942  
    39943994           
    39953995    def ExitMain(self, event):
    3996         '''Called if the main window is closed'''
     3996        '''Called if exit selected or the main window is closed
     3997        rescord last position of data & plot windows; saved to config.py file
     3998        NB: not called if console window closed
     3999        '''
    39974000        FramePos = {'Main_Pos':tuple(self.GetPosition()),'Plot_Pos':tuple(self.plotFrame.GetPosition())}
    39984001        GSASIIpath.SetConfigValue(FramePos)
    3999         print FramePos
    40004002        config = G2G.GetConfigValsDocs()
    40014003        G2G.SaveConfigVars(config)
     
    40064008        sys.exit()
    40074009       
    4008 #    def OnFileExit(self, event):
    4009 #        '''Called in response to the File/Quit menu button'''
    4010 #        if self.G2plotNB:
    4011 #            self.G2plotNB.Destroy()
    4012 #        self.Close()
    4013 #       
    40144010    def OnExportPeakList(self,event):
    40154011        nptand = lambda x: np.tan(x*math.pi/180.)
  • branch/2frame/GSASIImath.py

    r2940 r2942  
    39713971        pass
    39723972
    3973 #  A schedule due to Lester Ingber modified to use bounds - OK
    39743973class fast_sa(base_schedule):
    39753974    def init(self, **options):
     
    40304029    return Tsched[1:]
    40314030   
    4032 def anneal(func, x0, args=(), schedule='fast', full_output=0,
     4031def anneal(func, x0, args=(), schedule='fast',
    40334032           T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400,
    40344033           feps=1e-6, quench=1.0, c=1.0,
     
    40484047    :param base_schedule schedule:
    40494048        Annealing schedule to use (a class).
    4050     :param bool full_output:
    4051         Whether to return optional outputs.
    40524049    :param float T0:
    40534050        Initial Temperature (estimated as 1.2 times the largest
     
    40614058    :param int maxiter:
    40624059        Maximum cooling iterations.
    4063     :param float learn_rate:
    4064         Scale constant for adjusting guesses.
    40654060    :param float feps:
    40664061        Stopping relative error tolerance for the function value in
     
    42124207            if abs(af[-1]-best_state.cost) > feps*10:
    42134208                retval = 5
    4214                 print " Warning: Cooled to %.4f > selected Tmin %.4f"%(squeeze(last_state.cost),Tf)
     4209                print " Warning: Cooled to %.4f > selected Tmin %.4f in %d steps"%(squeeze(last_state.cost),Tf,iters-1)
    42154210            break
    42164211        if (Tf is not None) and (schedule.T < Tf):
    4217             print ' Minimum T reached'
     4212#            print ' Minimum T reached in %d steps'%(iters-1)
    42184213            retval = 1
    42194214            break
     
    42294224            break
    42304225
    4231     if full_output:
    4232         return best_state.x, best_state.cost, schedule.T, \
    4233                schedule.feval, iters, schedule.accepted, retval
    4234     else:
    4235         return best_state.x, retval
    4236 
    4237 def worker(iCyc,data,RBdata,reflType,reflData,covData,out_q,nprocess=-1):
     4226    return best_state.x, best_state.cost, schedule.T, \
     4227           schedule.feval, iters, schedule.accepted, retval
     4228
     4229def worker(iCyc,data,RBdata,reflType,reflData,covData,out_q,out_t,out_n,nprocess=-1):
    42384230    outlist = []
     4231    timelist = []
     4232    nsflist = []
    42394233    random.seed(int(time.time())%100000+nprocess)   #make sure each process has a different random start
    42404234    for n in range(iCyc):
    4241         result = mcsaSearch(data,RBdata,reflType,reflData,covData,None)
     4235        result = mcsaSearch(data,RBdata,reflType,reflData,covData,None,False)         #mcsa result,time,rcov
    42424236        outlist.append(result[0])
    4243         print ' MC/SA residual: %.3f%% structure factor time: %.3f'%(100*result[0][2],result[1])
     4237        timelist.append(result[1])
     4238        nsflist.append(result[2])
     4239        print ' MC/SA final fit: %.3f%% structure factor time: %.3f'%(100*result[0][2],result[1])
    42444240    out_q.put(outlist)
     4241    out_t.put(timelist)
     4242    out_n.put(nsflist)
    42454243
    42464244def MPmcsaSearch(nCyc,data,RBdata,reflType,reflData,covData):
    42474245    import multiprocessing as mp
    42484246   
    4249     nprocs = mp.cpu_count()
     4247    nprocs = max(1,mp.cpu_count()-1)       #leave one processor available for other work
    42504248    out_q = mp.Queue()
     4249    out_t = mp.Queue()
     4250    out_n = mp.Queue()
    42514251    procs = []
     4252    totsftime = 0.
     4253    totnsf = 0
    42524254    iCyc = np.zeros(nprocs)
    42534255    for i in range(nCyc):
    42544256        iCyc[i%nprocs] += 1
    42554257    for i in range(nprocs):
    4256         p = mp.Process(target=worker,args=(int(iCyc[i]),data,RBdata,reflType,reflData,covData,out_q,i))
     4258        p = mp.Process(target=worker,args=(int(iCyc[i]),data,RBdata,reflType,reflData,covData,out_q,out_t,out_n,i))
    42574259        procs.append(p)
    42584260        p.start()
     
    42604262    for i in range(nprocs):
    42614263        resultlist += out_q.get()
     4264        totsftime += np.sum(out_t.get())
     4265        totnsf += np.sum(out_n.get())
    42624266    for p in procs:
    42634267        p.join()
    4264     return resultlist
    4265 
    4266 def mcsaSearch(data,RBdata,reflType,reflData,covData,pgbar):
     4268    return resultlist,totsftime,totnsf
     4269
     4270def mcsaSearch(data,RBdata,reflType,reflData,covData,pgbar,start=True):
    42674271    '''default doc string
    42684272   
     
    42894293            return xnew
    42904294   
    4291     global tsum
     4295    global tsum,nsum
    42924296    tsum = 0.
     4297    nsum = 0
    42934298   
    42944299    def getMDparms(item,pfx,parmDict,varyList):
     
    44864491        '''   
    44874492           
    4488         global tsum
     4493        global tsum,nsum
    44894494        t0 = time.time()
    44904495        parmDict.update(dict(zip(varyList,values)))             #update parameter tables
     
    45054510        M = np.inner(refList[6],np.inner(rcov,refList[6]))
    45064511        tsum += (time.time()-t0)
     4512        nsum += 1
    45074513        return np.sqrt(M/np.sum(refList[4]**2))
    45084514   
     
    46374643    allFF = np.array(allFF).T
    46384644    refs = np.array(refs).T
    4639     print ' Minimum d-spacing used: %.2f No. reflections used: %d'%(MCSA['dmin'],nRef)
    4640     print ' Number of parameters varied: %d'%(len(varyList))
     4645    if start:
     4646        print ' Minimum d-spacing used: %.2f No. reflections used: %d'%(MCSA['dmin'],nRef)
     4647        print ' Number of parameters varied: %d'%(len(varyList))
     4648        start = False
    46414649    parmDict['sumFosq'] = sumFosq
    46424650    x0 = [parmDict[val] for val in varyList]
     
    46544662            T0 = None
    46554663        results = anneal(mcsaCalc,x0,args=(refs,rcov,cosTable,ifInv,allFF,RBdata,varyList,parmDict),
    4656             schedule=MCSA['Algorithm'], full_output=True,dwell=MCSA['Annealing'][2],maxiter=10000,
     4664            schedule=MCSA['Algorithm'], dwell=MCSA['Annealing'][2],maxiter=10000,
    46574665            T0=T0, Tf=MCSA['Annealing'][1],
    46584666            quench=MCSA['fast parms'][0], c=MCSA['fast parms'][1],
    46594667            lower=lower, upper=upper, slope=MCSA['log slope'],ranStart=MCSA.get('ranStart',False),
    46604668            ranRange=MCSA.get('ranRange',10.)/100.,autoRan=MCSA.get('autoRan',False),dlg=pgbar)
     4669        print ' Acceptance rate: %.2f%% MCSA residual: %.2f%%'%(100.*results[5]/results[3],100.*results[1])
    46614670        results = so.minimize(mcsaCalc,results[0],method='L-BFGS-B',args=(refs,rcov,cosTable,ifInv,allFF,RBdata,varyList,parmDict),
    46624671            bounds=bounds,)
    46634672    mcsaCalc(results['x'],refs,rcov,cosTable,ifInv,allFF,RBdata,varyList,parmDict)
    46644673    Result = [False,False,results['fun'],0.0,]+list(results['x'])
    4665 #        Result = [False,False,results[1],results[2],]+list(results[0])
    46664674    Result.append(varyList)
    4667     return Result,tsum,rcov
     4675    return Result,tsum,nsum,rcov
    46684676
    46694677       
  • branch/2frame/GSASIIphsGUI.py

    r2940 r2942  
    20712071            line2Sizer = wx.BoxSizer(wx.HORIZONTAL)
    20722072            line2Sizer.Add(wx.StaticText(General,label=' MC/SA runs: '),0,WACV)
    2073             Cchoice = ['1','2','4','8','16','32','64','128','256']
     2073            Cchoice = [str(2**i) for i in range(13)]
    20742074            cycles = wx.ComboBox(General,-1,value=str(MCSAdata.get('Cycles',1)),choices=Cchoice,
    20752075                style=wx.CB_READONLY|wx.CB_DROPDOWN)
     
    77827782                for i in range(nCyc):
    77837783                    pgbar.SetTitle('MC/SA run '+str(i+1)+' of '+str(nCyc))
    7784                     Result,tsum,rcov = G2mth.mcsaSearch(data,RBdata,reflType,reflData,covData,pgbar)
     7784                    Result,tsum,nsum,rcov = G2mth.mcsaSearch(data,RBdata,reflType,reflData,covData,pgbar)
    77857785                    MCSAdata['Results'].append(Result)
    7786                     print ' MC/SA run completed: %d residual: %.3f%% SFcalc time: %.2fs'%(i,100*Result[2],tsum)
     7786                    print ' MC/SA run completed: %d residual: %.3f%% SFcalc time: %.2fs Nsfcalc: %d'%(i,100*Result[2],tsum,nsum)
    77877787                    tsf += tsum
    77887788                print ' Structure factor time: %.2f'%(tsf)
     
    77907790                G2plt.PlotXYZ(G2frame,XY,rcov,labelX='ref No.',labelY='ref No.',newPlot=False,Title='Reflection covariance matrix')
    77917791            else:
    7792                 MCSAdata['Results'] += G2mth.MPmcsaSearch(nCyc,data,RBdata,reflType,reflData,covData)   #+= to  any saved ones
    7793             print ' MC/SA run time: %.2f'%(time.time()-time1)
     7792                Results,sftime,numsf = G2mth.MPmcsaSearch(nCyc,data,RBdata,reflType,reflData,covData)
     7793                MCSAdata['Results'] += Results   #+= to  any saved ones
     7794            print ' Total SF time: %.2f MC/SA run time: %.2f Nsfcalc: %d'%(sftime,time.time()-time1,numsf)
    77947795        finally:
    77957796            if process == 'single':
Note: See TracChangeset for help on using the changeset viewer.