Exemplo n.º 1
0
class MC_class():
    """
    Private class for solving Monte-Carlo evolution from mcsolve
    
    """
    def __init__(self):
        
        #-----------------------------------#
        # INIT MC CLASS
        #-----------------------------------#
    
        #----MAIN OBJECT PROPERTIES--------------------#
        ##holds instance of the ProgressBar class
        self.bar=None
        ##holds instance of the Pthread class
        self.thread=None
        #Number of completed trajectories
        self.count=0
        ##step-size for count attribute
        self.step=1
        ##Percent of trajectories completed
        self.percent=0.0
        ##used in implimenting the command line progress ouput
        self.level=0.1
        ##times at which to output state vectors or expectation values
        ##number of time steps in tlist
        self.num_times=len(odeconfig.tlist)
        #holds seed for random number generator
        self.seed=None
        #holds expected time to completion
        self.st=None
        #number of cpus to be used 
        self.cpus=odeconfig.options.num_cpus
        #set output variables, even if they are not used to simplify output code.
        self.psi_out=None
        self.expect_out=None
        self.collapse_times_out=None
        self.which_op_out=None
        
        #FOR EVOLUTION FOR NO COLLAPSE OPERATORS
        if odeconfig.c_num==0:
            if odeconfig.e_num==0:
                ##Output array of state vectors calculated at times in tlist
                self.psi_out=array([Qobj()]*self.num_times)#preallocate array of Qobjs
            elif odeconfig.e_num!=0:#no collpase expectation values
                ##List of output expectation values calculated at times in tlist
                self.expect_out=[]
                for i in range(odeconfig.e_num):
                    if odeconfig.e_ops_isherm[i]:#preallocate real array of zeros
                        self.expect_out.append(zeros(self.num_times))
                    else:#preallocate complex array of zeros
                        self.expect_out.append(zeros(self.num_times,dtype=complex))
                    self.expect_out[i][0]=mc_expect(odeconfig.e_ops_data[i],odeconfig.e_ops_ind[i],odeconfig.e_ops_ptr[i],odeconfig.e_ops_isherm[i],odeconfig.psi0)
        
        #FOR EVOLUTION WITH COLLAPSE OPERATORS
        elif odeconfig.c_num!=0:
            #preallocate #ntraj arrays for state vectors, collapse times, and which operator
            self.collapse_times_out=zeros((odeconfig.ntraj),dtype=ndarray)
            self.which_op_out=zeros((odeconfig.ntraj),dtype=ndarray)
            if odeconfig.e_num==0:# if no expectation operators, preallocate #ntraj arrays for state vectors
                self.psi_out=array([zeros((self.num_times),dtype=object) for q in range(odeconfig.ntraj)])#preallocate array of Qobjs
            else: #preallocate array of lists for expectation values
                self.expect_out=[[] for x in range(odeconfig.ntraj)]
    
    
    #-------------------------------------------------#
    # CLASS METHODS
    #-------------------------------------------------#
    def callback(self,results):
        r=results[0]
        if odeconfig.e_num==0:#output state-vector
            self.psi_out[r]=results[1]
        else:#output expectation values
            self.expect_out[r]=results[1]
        self.collapse_times_out[r]=results[2]
        self.which_op_out[r]=results[3]
        self.count+=self.step
        if (not odeconfig.options.gui): #do not use GUI
            self.percent=self.count/(1.0*odeconfig.ntraj)
            if self.count/float(odeconfig.ntraj)>=self.level:
                #calls function to determine simulation time remaining
                self.level=_time_remaining(self.st,odeconfig.ntraj,self.count,self.level)
    #-----
    def parallel(self,args,top=None):  
        self.st=datetime.datetime.now() #set simulation starting time
        pl=Pool(processes=self.cpus)
        [pl.apply_async(mc_alg_evolve,args=(nt,args),callback=top.callback) for nt in range(0,odeconfig.ntraj)]
        pl.close()
        try:
            pl.join()
        except KeyboardInterrupt:
            print("Cancel all MC threads on keyboard interrupt")
            pl.terminate()
            pl.join()
        return
    #-----
    def run(self):
        if odeconfig.c_num==0:
            if odeconfig.ntraj!=1:#check if ntraj!=1 which is pointless for no collapse operators
                odeconfig.ntraj=1
                print('No collapse operators specified.\nRunning a single trajectory only.\n')
            if odeconfig.e_num==0:# return psi Qobj at each requested time 
                self.psi_out=no_collapse_psi_out(self.num_times,self.psi_out)
            else:# return expectation values of requested operators
                self.expect_out=no_collapse_expect_out(self.num_times,self.expect_out)
        elif odeconfig.c_num!=0:
            self.seed=array([int(ceil(random.rand()*1e4)) for ll in range(odeconfig.ntraj)])
            if odeconfig.e_num==0:
                mc_alg_out=zeros((self.num_times),dtype=ndarray)
                mc_alg_out[0]=odeconfig.psi0
            else:
                #PRE-GENERATE LIST OF EXPECTATION VALUES
                mc_alg_out=[]
                for i in range(odeconfig.e_num):
                    if odeconfig.e_ops_isherm[i]:#preallocate real array of zeros
                        mc_alg_out.append(zeros(self.num_times))
                    else:#preallocate complex array of zeros
                        mc_alg_out.append(zeros(self.num_times,dtype=complex))
                    mc_alg_out[i][0]=mc_expect(odeconfig.e_ops_data[i],odeconfig.e_ops_ind[i],odeconfig.e_ops_ptr[i],odeconfig.e_ops_isherm[i],odeconfig.psi0)
            
            #set arguments for input to monte-carlo
            args=(mc_alg_out,odeconfig.options,odeconfig.tlist,self.num_times,self.seed)
            if not odeconfig.options.gui:
                self.parallel(args,self)
            else:
                if qutip.settings.qutip_gui=="PYSIDE":
                    from PySide import QtGui,QtCore
                elif qutip.settings.qutip_gui=="PYQT4":
                    from PyQt4 import QtGui,QtCore
                from gui.ProgressBar import ProgressBar,Pthread
                app=QtGui.QApplication.instance()#checks if QApplication already exists (needed for iPython)
                if not app:#create QApplication if it doesnt exist
                    app = QtGui.QApplication(sys.argv)
                thread=Pthread(target=self.parallel,args=args,top=self)
                self.bar=ProgressBar(self,thread,odeconfig.ntraj,self.cpus)
                QtCore.QTimer.singleShot(0,self.bar.run)
                self.bar.show()
                self.bar.activateWindow()
                self.bar.raise_()
                app.exec_()
                return
Exemplo n.º 2
0
class MC_class():
    """
    Private class for solving Monte-Carlo evolution from mcsolve
    
    """
    def __init__(self):

        #-----------------------------------#
        # INIT MC CLASS
        #-----------------------------------#

        #----MAIN OBJECT PROPERTIES--------------------#
        ##holds instance of the ProgressBar class
        self.bar = None
        ##holds instance of the Pthread class
        self.thread = None
        #Number of completed trajectories
        self.count = 0
        ##step-size for count attribute
        self.step = 1
        ##Percent of trajectories completed
        self.percent = 0.0
        ##used in implimenting the command line progress ouput
        self.level = 0.1
        ##times at which to output state vectors or expectation values
        ##number of time steps in tlist
        self.num_times = len(odeconfig.tlist)
        #holds seed for random number generator
        self.seed = None
        #holds expected time to completion
        self.st = None
        #number of cpus to be used
        self.cpus = odeconfig.options.num_cpus
        #set output variables, even if they are not used to simplify output code.
        self.psi_out = None
        self.expect_out = None
        self.collapse_times_out = None
        self.which_op_out = None

        #FOR EVOLUTION FOR NO COLLAPSE OPERATORS
        if odeconfig.c_num == 0:
            if odeconfig.e_num == 0:
                ##Output array of state vectors calculated at times in tlist
                self.psi_out = array(
                    [Qobj()] * self.num_times)  #preallocate array of Qobjs
            elif odeconfig.e_num != 0:  #no collpase expectation values
                ##List of output expectation values calculated at times in tlist
                self.expect_out = []
                for i in range(odeconfig.e_num):
                    if odeconfig.e_ops_isherm[
                            i]:  #preallocate real array of zeros
                        self.expect_out.append(zeros(self.num_times))
                    else:  #preallocate complex array of zeros
                        self.expect_out.append(
                            zeros(self.num_times, dtype=complex))
                    self.expect_out[i][0] = mc_expect(
                        odeconfig.e_ops_data[i], odeconfig.e_ops_ind[i],
                        odeconfig.e_ops_ptr[i], odeconfig.e_ops_isherm[i],
                        odeconfig.psi0)

        #FOR EVOLUTION WITH COLLAPSE OPERATORS
        elif odeconfig.c_num != 0:
            #preallocate #ntraj arrays for state vectors, collapse times, and which operator
            self.collapse_times_out = zeros((odeconfig.ntraj), dtype=ndarray)
            self.which_op_out = zeros((odeconfig.ntraj), dtype=ndarray)
            if odeconfig.e_num == 0:  # if no expectation operators, preallocate #ntraj arrays for state vectors
                self.psi_out = array([
                    zeros((self.num_times), dtype=object)
                    for q in range(odeconfig.ntraj)
                ])  #preallocate array of Qobjs
            else:  #preallocate array of lists for expectation values
                self.expect_out = [[] for x in range(odeconfig.ntraj)]

    #-------------------------------------------------#
    # CLASS METHODS
    #-------------------------------------------------#
    def callback(self, results):
        r = results[0]
        if odeconfig.e_num == 0:  #output state-vector
            self.psi_out[r] = results[1]
        else:  #output expectation values
            self.expect_out[r] = results[1]
        self.collapse_times_out[r] = results[2]
        self.which_op_out[r] = results[3]
        self.count += self.step
        if (not odeconfig.options.gui):  #do not use GUI
            self.percent = self.count / (1.0 * odeconfig.ntraj)
            if self.count / float(odeconfig.ntraj) >= self.level:
                #calls function to determine simulation time remaining
                self.level = _time_remaining(self.st, odeconfig.ntraj,
                                             self.count, self.level)

    #-----
    def parallel(self, args, top=None):
        self.st = datetime.datetime.now()  #set simulation starting time
        pl = Pool(processes=self.cpus)
        [
            pl.apply_async(mc_alg_evolve,
                           args=(nt, args),
                           callback=top.callback)
            for nt in range(0, odeconfig.ntraj)
        ]
        pl.close()
        try:
            pl.join()
        except KeyboardInterrupt:
            print("Cancel all MC threads on keyboard interrupt")
            pl.terminate()
            pl.join()
        return

    #-----
    def run(self):
        if odeconfig.c_num == 0:
            if odeconfig.ntraj != 1:  #check if ntraj!=1 which is pointless for no collapse operators
                odeconfig.ntraj = 1
                print(
                    'No collapse operators specified.\nRunning a single trajectory only.\n'
                )
            if odeconfig.e_num == 0:  # return psi Qobj at each requested time
                self.psi_out = no_collapse_psi_out(self.num_times,
                                                   self.psi_out)
            else:  # return expectation values of requested operators
                self.expect_out = no_collapse_expect_out(
                    self.num_times, self.expect_out)
        elif odeconfig.c_num != 0:
            self.seed = array([
                int(ceil(random.rand() * 1e4)) for ll in range(odeconfig.ntraj)
            ])
            if odeconfig.e_num == 0:
                mc_alg_out = zeros((self.num_times), dtype=ndarray)
                mc_alg_out[0] = odeconfig.psi0
            else:
                #PRE-GENERATE LIST OF EXPECTATION VALUES
                mc_alg_out = []
                for i in range(odeconfig.e_num):
                    if odeconfig.e_ops_isherm[
                            i]:  #preallocate real array of zeros
                        mc_alg_out.append(zeros(self.num_times))
                    else:  #preallocate complex array of zeros
                        mc_alg_out.append(zeros(self.num_times, dtype=complex))
                    mc_alg_out[i][0] = mc_expect(odeconfig.e_ops_data[i],
                                                 odeconfig.e_ops_ind[i],
                                                 odeconfig.e_ops_ptr[i],
                                                 odeconfig.e_ops_isherm[i],
                                                 odeconfig.psi0)

            #set arguments for input to monte-carlo
            args = (mc_alg_out, odeconfig.options, odeconfig.tlist,
                    self.num_times, self.seed)
            if not odeconfig.options.gui:
                self.parallel(args, self)
            else:
                if qutip.settings.qutip_gui == "PYSIDE":
                    from PySide import QtGui, QtCore
                elif qutip.settings.qutip_gui == "PYQT4":
                    from PyQt4 import QtGui, QtCore
                from gui.ProgressBar import ProgressBar, Pthread
                app = QtGui.QApplication.instance(
                )  #checks if QApplication already exists (needed for iPython)
                if not app:  #create QApplication if it doesnt exist
                    app = QtGui.QApplication(sys.argv)
                thread = Pthread(target=self.parallel, args=args, top=self)
                self.bar = ProgressBar(self, thread, odeconfig.ntraj,
                                       self.cpus)
                QtCore.QTimer.singleShot(0, self.bar.run)
                self.bar.show()
                self.bar.activateWindow()
                self.bar.raise_()
                app.exec_()
                return