示例#1
0
def run(neq=10, ntraj=100, solver='both', ncpus=1):
    # sparse initial state
    # psi0 = basis(neq,neq-1)
    # dense initial state
    psi0 = qt.Qobj(np.ones((neq, 1))).unit()
    a = qt.destroy(neq)
    ad = a.dag()
    H = ad * a
    # c_ops = [gamma*a]
    c_ops = [qt.qeye(neq)]
    e_ops = [ad * a]

    # Times
    T = 10.0
    dt = 0.1
    nstep = int(T / dt)
    tlist = np.linspace(0, T, nstep)

    # set options
    opts = qt.Options()
    opts.num_cpus = ncpus
    opts.gui = False

    mcf90_time = 0.
    mc_time = 0.
    if (solver == 'mcf90' or solver == 'both'):
        start_time = time.time()
        mcf90.mcsolve_f90(H,
                          psi0,
                          tlist,
                          c_ops,
                          e_ops,
                          ntraj=ntraj,
                          options=opts)

        mcf90_time = time.time() - start_time
        print("mcsolve_f90 solutiton took", mcf90_time, "s")

    if (solver == 'mc' or solver == 'both'):
        start_time = time.time()
        qt.mcsolve(H,
                   psi0,
                   tlist,
                   c_ops,
                   e_ops,
                   ntraj=ntraj,
                   options=opts,
                   progress_bar=False)
        mc_time = time.time() - start_time
        print("mcsolve solutiton took", mc_time, "s")

    return mcf90_time, mc_time
示例#2
0
def run():
    wa  = 1.0 * 2 * pi   # frequency of system a
    wb  = 1.0 * 2 * pi   # frequency of system a
    wab = 0.2 * 2 * pi   # coupling frequency
    ga = 0.2 * 2 * pi    # dissipation rate of system a
    gb = 0.1 * 2 * pi    # dissipation rate of system b
    Na = 10              # number of states in system a
    Nb = 10              # number of states in system b
    E = 1.0 * 2 * pi     # Oscillator A driving strength 

    a = tensor(destroy(Na), qeye(Nb))
    b = tensor(qeye(Na), destroy(Nb))
    na = a.dag() * a
    nb = b.dag() * b
    H = wa*na + wb*nb + wab*(a.dag()*b+a*b.dag()) + E*(a.dag()+a)

    # start with both oscillators in ground state
    psi0 = tensor(basis(Na), basis(Nb))

    c_op_list = []
    c_op_list.append(sqrt(ga) * a)
    c_op_list.append(sqrt(gb) * b)

    tlist = linspace(0, 5, 101)

    #run simulation
    data = mcf90.mcsolve_f90(H,psi0,tlist,c_op_list,[na,nb])
    #data = mcsolve(H,psi0,tlist,c_op_list,[na,nb])

    #plot results
    plot(tlist,data.expect[0],'b',tlist,data.expect[1],'r',lw=2)
    xlabel('Time',fontsize=14)
    ylabel('Excitations',fontsize=14)
    legend(('Oscillator A', 'Oscillator B'))
    show()
示例#3
0
def integrate(N, h, Jx, Jy, Jz, psi0, tlist, gamma, solver):

    #
    # Hamiltonian
    #
    # H = - 0.5 sum_n^N h_n sigma_z(n)  
    #     - 0.5 sum_n^(N-1) [ Jx_n sigma_x(n) sigma_x(n+1) + 
    #                         Jy_n sigma_y(n) sigma_y(n+1) + 
    #                         Jz_n sigma_z(n) sigma_z(n+1)]
    #
    si = qeye(2)
    sx = sigmax()
    sy = sigmay()
    sz = sigmaz()

    sx_list = []
    sy_list = []
    sz_list = []
    for n in range(N):
        op_list = []
        for m in range(N):
            op_list.append(si)
        op_list[n] = sx
        sx_list.append(tensor(op_list))
        op_list[n] = sy
        sy_list.append(tensor(op_list))
        op_list[n] = sz
        sz_list.append(tensor(op_list))
        
    # construct the hamiltonian
    H = 0    
    
    # energy splitting terms
    for n in range(N):
        H += - 0.5 * h[n] * sz_list[n]
        
    # interaction terms
    for n in range(N-1):
        H += - 0.5 * Jx[n] * sx_list[n] * sx_list[n+1]
        H += - 0.5 * Jy[n] * sy_list[n] * sy_list[n+1]
        H += - 0.5 * Jz[n] * sz_list[n] * sz_list[n+1] 

    # collapse operators
    c_op_list = []

    # spin dephasing
    for n in range(N):
        if gamma[n] > 0.0:
            c_op_list.append(sqrt(gamma[n]) * sz_list[n])
            
    # evolve and calculate expectation values
    if solver == "me":
        output = mesolve(H, psi0, tlist, c_op_list, sz_list)
    elif solver == "mc":
        output = mcsolve(H, psi0, tlist, c_op_list, sz_list)
    elif solver == "mcf90":
        output = mcf90.mcsolve_f90(H, psi0, tlist, c_op_list, sz_list)

    return output.expect
示例#4
0
def run():
    #number of states for each mode
    N0=15
    N1=15
    N2=15

    #define operators
    a0=tensor(destroy(N0),qeye(N1),qeye(N2))
    a1=tensor(qeye(N0),destroy(N1),qeye(N2))
    a2=tensor(qeye(N0),qeye(N1),destroy(N2))

    #number operators for each mode
    num0=a0.dag()*a0
    num1=a1.dag()*a1
    num2=a2.dag()*a2

    #initial state: coherent mode 0 & vacuum for modes #1 & #2
    alpha=sqrt(7)#initial coherent state param for mode 0
    psi0=tensor(coherent(N0,alpha),basis(N1,0),basis(N2,0))

    #trilinear Hamiltonian
    H=1.0j*(a0*a1.dag()*a2.dag()-a0.dag()*a1*a2)

    #run Monte-Carlo
    tlist=linspace(0,2.5,50)
    output=mcf90.mcsolve_f90(H,psi0,tlist,[],[],ntraj=1)
    #output=mcsolve(H,psi0,tlist,[],[],ntraj=1)

    #extrace mode 1 using ptrace
    mode1=[psi.ptrace(1) for psi in output.states]
    #get diagonal elements
    diags1=[k.diag() for k in mode1]
    #calculate num of particles in mode 1
    num1=[expect(num1,k) for k in output.states]
    #generate thermal state with same # of particles
    thermal=[thermal_dm(N1,k).diag() for k in num1]

    #plot results
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    colors=['m', 'g','orange','b', 'y','pink']
    x=arange(N1)
    params = {'axes.labelsize': 14,'text.fontsize': 14,'legend.fontsize': 12,'xtick.labelsize': 14,'ytick.labelsize': 14}
    rcParams.update(params)
    fig = plt.figure()
    ax = Axes3D(fig)
    for j in range(5):
        ax.bar(x, diags1[10*j], zs=tlist[10*j], zdir='y',color=colors[j],linewidth=1.0,alpha=0.6,align='center')
        ax.plot(x,thermal[10*j],zs=tlist[10*j],zdir='y',color='r',linewidth=3,alpha=1)
    ax.set_zlabel(r'Probability')
    ax.set_xlabel(r'Number State')
    ax.set_ylabel(r'Time')
    ax.set_zlim3d(0,1)
    show()
示例#5
0
def run(neq=10, ntraj=100, solver='both', ncpus=1):
    # sparse initial state
    # psi0 = basis(neq,neq-1)
    # dense initial state
    psi0 = qt.Qobj(np.ones((neq, 1))).unit()
    a = qt.destroy(neq)
    ad = a.dag()
    H = ad*a
    # c_ops = [gamma*a]
    c_ops = [qt.qeye(neq)]
    e_ops = [ad*a]

    # Times
    T = 10.0
    dt = 0.1
    nstep = int(T/dt)
    tlist = np.linspace(0, T, nstep)

    # set options
    opts = qt.Options()
    opts.num_cpus = ncpus
    opts.gui = False

    mcf90_time = 0.
    mc_time = 0.
    if (solver == 'mcf90' or solver == 'both'):
        start_time = time.time()
        mcf90.mcsolve_f90(H, psi0, tlist, c_ops, e_ops,
                          ntraj=ntraj, options=opts)

        mcf90_time = time.time()-start_time
        print("mcsolve_f90 solutiton took", mcf90_time, "s")

    if (solver == 'mc' or solver == 'both'):
        start_time = time.time()
        qt.mcsolve(H, psi0, tlist, c_ops, e_ops, ntraj=ntraj,
                   options=opts, progress_bar=False)
        mc_time = time.time()-start_time
        print("mcsolve solutiton took", mc_time, "s")

    return mcf90_time, mc_time
示例#6
0
def run():
    #number of states for each mode
    N0=6
    N1=6
    N2=6
    #damping rates
    gamma0=0.1
    gamma1=0.4
    gamma2=0.1
    alpha=sqrt(2)#initial coherent state param for mode 0
    tlist=linspace(0,4,200)
    ntraj=500#number of trajectories

    #define operators
    a0=tensor(destroy(N0),qeye(N1),qeye(N2))
    a1=tensor(qeye(N0),destroy(N1),qeye(N2))
    a2=tensor(qeye(N0),qeye(N1),destroy(N2))

    #number operators for each mode
    num0=a0.dag()*a0
    num1=a1.dag()*a1
    num2=a2.dag()*a2

    #dissipative operators for zero-temp. baths
    C0=sqrt(2.0*gamma0)*a0
    C1=sqrt(2.0*gamma1)*a1
    C2=sqrt(2.0*gamma2)*a2

    #initial state: coherent mode 0 & vacuum for modes #1 & #2
    psi0=tensor(coherent(N0,alpha),basis(N1,0),basis(N2,0))

    #trilinear Hamiltonian
    H=1j*(a0*a1.dag()*a2.dag()-a0.dag()*a1*a2)

    #run Monte-Carlo
    data=mcf90.mcsolve_f90(H,psi0,tlist,[C0,C1,C2],[num0,num1,num2])
    #data=mcsolve(H,psi0,tlist,[C0,C1,C2],[num0,num1,num2])

    #plot results
    fig = figure()
    ax = fig.add_subplot(111)
    cs=['b','r','g'] #set three colors, one for each operator
    for k in range(ntraj):
        if len(data.col_times[k])>0:#just in case no collapse
            colors=[cs[j] for j in data.col_which[k]]#set color
            xdat=[k for x in range(len(data.col_times[k]))]
            ax.scatter(xdat,data.col_times[k],marker='o',c=colors)
    ax.set_xlim([-1,ntraj+1])
    ax.set_ylim([0,tlist[-1]])
    ax.set_xlabel('Trajectory',fontsize=14)
    ax.set_ylabel('Collpase Time',fontsize=14)
    ax.set_title('Blue = C0, Red = C1, Green= C2')
    show()
def test_MCSimpleConst():
    "Monte-carlo: Constant H with constant collapse"
    N=10 #number of basis states to consider
    a=destroy(N)
    H=a.dag()*a
    psi0=basis(N,9) #initial state
    kappa=0.2 #coupling to oscillator
    c_op_list=[sqrt(kappa)*a]
    tlist=linspace(0,10,100)
    mcdata=mcsolve_f90(H,psi0,tlist,c_op_list,[a.dag()*a],options=Odeoptions(gui=False))
    expt=mcdata.expect[0]
    actual_answer=9.0*exp(-kappa*tlist)
    avg_diff=mean(abs(actual_answer-expt)/actual_answer)
    assert_equal(avg_diff<mc_error,True)
def test_MCNoCollExpt():
    "Monte-carlo: Constant H with no collapse ops (expect)"
    error=1e-8
    N=10 #number of basis states to consider
    a=destroy(N)
    H=a.dag()*a
    psi0=basis(N,9) #initial state
    kappa=0.2 #coupling to oscillator
    c_op_list=[]
    tlist=linspace(0,10,100)
    mcdata=mcsolve_f90(H,psi0,tlist,c_op_list,[a.dag()*a],options=Odeoptions(gui=False))
    expt=mcdata.expect[0]
    actual_answer=9.0*ones(len(tlist))
    diff=mean(abs(actual_answer-expt)/actual_answer)
    assert_equal(diff<error,True)
示例#9
0
def ptracetest():
    gamma = 1.
    neq = 2
    psi0 = qt.basis(neq,neq-1)
    psi0 = qt.tensor(psi0,psi0)
    H = qt.tensor(qt.sigmax(),qt.sigmay())
    c1 = np.sqrt(gamma)*qt.sigmax()
    e1 = np.sqrt(gamma)*qt.sigmaz()
    c_ops = [qt.tensor(c1,c1)]
    e_ops = [qt.tensor(e1,e1),qt.tensor(c1,c1)]
    #e_ops = []
    tlist = np.linspace(0,10,100)
    ntraj = 2000
    ptrace_sel = [0]
    sol_f90 = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,
            ptrace_sel=ptrace_sel,calc_entropy=True)
示例#10
0
def run():
    from mpi4py import MPI
    comm = MPI.COMM_WORLD
    size = comm.Get_size()
    rank = comm.Get_rank()
    print "Process number", rank, "of", size, "total."

    neq = 2
    gamma = 1.0
    psi0 = qt.basis(neq,neq-1)
    H = qt.sigmax()
    c_ops = [np.sqrt(gamma)*qt.sigmax()]
    e_ops = [qt.sigmam()*qt.sigmap()]

    tlist = np.linspace(0,10,100)

    ntraj=100

    # One CPU per MPI process
    opts = qt.Odeoptions()
    opts.num_cpus = 1

    # Solve
    sols = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)
    #sols = qt.mcsolve(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)

    # Gather data
    sols = comm.gather(sols,root=0)
    if (rank==0):
        sol = sols[0]
        sol.expect = np.array(sols[0].expect)
        plt.figure()
        plt.plot(tlist,sols[0].expect[0],'r',label='proc '+str(0))
        for i in range(1,size):
            plt.plot(tlist,sols[i].expect[0],'r',label='proc '+str(i))
            sol.expect += np.array(sols[i].expect)
        sol.expect = sol.expect/size
        plt.plot(tlist,sol.expect[0],'b',label='average')
        plt.legend()
        plt.show()
示例#11
0
def run():
    # set system parameters
    kappa = 2.0  # mirror coupling
    gamma = 0.2  # spontaneous emission rate
    g = 1  # atom/cavity coupling strength
    wc = 0  # cavity frequency
    w0 = 0  # atom frequency
    wl = 0  # driving frequency
    E = 0.5  # driving amplitude
    N = 4  # number of cavity energy levels (0->3 Fock states)
    tlist = linspace(0, 10, 101)  # times for expectation values

    # construct Hamiltonian
    ida = qeye(N)
    idatom = qeye(2)
    a = tensor(destroy(N), idatom)
    sm = tensor(ida, sigmam())
    H = (w0 - wl) * sm.dag() * sm + (wc - wl) * a.dag() * a + 1j * g * (a.dag() * sm - sm.dag() * a) + E * (a.dag() + a)

    # collapse operators
    C1 = sqrt(2 * kappa) * a
    C2 = sqrt(gamma) * sm
    C1dC1 = C1.dag() * C1
    C2dC2 = C2.dag() * C2

    # intial state
    psi0 = tensor(basis(N, 0), basis(2, 1))

    # run monte-carlo solver with default 500 trajectories
    data = mcf90.mcsolve_f90(H, psi0, tlist, [C1, C2], [C1dC1, C2dC2])
    # data=mcsolve(H,psi0,tlist,[C1,C2],[C1dC1,C2dC2])
    # plot expectation values
    plot(tlist, data.expect[0], tlist, data.expect[1], lw=2)
    legend(("Transmitted Cavity Intensity", "Spontaneous Emission"))
    ylabel("Counts")
    xlabel("Time")
    show()
示例#12
0
def test():
    gamma = 1.
    neq = 2
    psi0 = qt.basis(neq,neq-1)
    #a = qt.destroy(neq)
    #ad = a.dag()
    #H = ad*a
    #c_ops = [gamma*a]
    #e_ops = [ad*a]
    H = qt.sigmax()
    c_ops = [np.sqrt(gamma)*qt.sigmax()]
    #c_ops = []
    e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()]
    #e_ops = []

    # Times
    T = 2.0
    dt = 0.1
    nstep = int(T/dt)
    tlist = np.linspace(0,T,nstep)

    ntraj=100

    # set options
    opts = qt.Odeoptions()
    opts.num_cpus=2
    #opts.mc_avg = True
    #opts.gui=False
    #opts.max_step=1000
    #opts.atol =
    #opts.rtol =

    sol_f90 = qt.Odedata()
    start_time = time.time()
    sol_f90 = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)
    print "mcsolve_f90 solutiton took", time.time()-start_time, "s"

    sol_me = qt.Odedata()
    start_time = time.time()
    sol_me = qt.mesolve(H,psi0,tlist,c_ops,e_ops,options=opts)
    print "mesolve solutiton took", time.time()-start_time, "s"

    sol_mc = qt.Odedata()
    start_time = time.time()
    sol_mc = qt.mcsolve(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)
    print "mcsolve solutiton took", time.time()-start_time, "s"

    if (e_ops == []):
        e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()]
        sol_f90expect = [np.array([0.+0.j]*nstep)]*len(e_ops)
        sol_mcexpect = [np.array([0.+0.j]*nstep)]*len(e_ops)
        sol_meexpect = [np.array([0.+0.j]*nstep)]*len(e_ops)
        for i in range(len(e_ops)):
            if (not opts.mc_avg):
                sol_f90expect[i] = sum([qt.expect(e_ops[i],
                    sol_f90.states[j]) for j in range(ntraj)])/ntraj
                sol_mcexpect[i] = sum([qt.expect(e_ops[i],
                    sol_mc.states[j]) for j in range(ntraj)])/ntraj
            else:
                sol_f90expect[i] = qt.expect(e_ops[i],sol_f90.states)
                sol_mcexpect[i] = qt.expect(e_ops[i],sol_mc.states)
            sol_meexpect[i] = qt.expect(e_ops[i],sol_me.states)
    elif (not opts.mc_avg):
        sol_f90expect = sum(sol_f90.expect,0)/ntraj
        sol_mcexpect = sum(sol_f90.expect,0)/ntraj
        sol_meexpect = sol_me.expect
    else:
        sol_f90expect = sol_f90.expect
        sol_mcexpect = sol_mc.expect
        sol_meexpect = sol_me.expect

    plt.figure()
    for i in range(len(e_ops)):
        plt.plot(tlist,sol_f90expect[i],'b')
        plt.plot(tlist,sol_mcexpect[i],'g')
        plt.plot(tlist,sol_meexpect[i],'k')

    return sol_f90, sol_mc
示例#13
0
def run():
    # define parameters
    N=4             # number of basis states to consider
    kappa=1.0/0.129 # coupling to heat bath
    nth= 0.063      # temperature with <n>=0.063

    # create operators and initial |1> state
    a=destroy(N)    # cavity destruction operator
    H=a.dag()*a     # harmonic oscillator Hamiltonian
    psi0=basis(N,1) # initial Fock state with one photon

    # collapse operators
    c_op_list = []
    # decay operator
    c_op_list.append(sqrt(kappa * (1 + nth)) * a)
    # excitation operator
    c_op_list.append(sqrt(kappa * nth) * a.dag())

    # run monte carlo simulation
    ntraj=[1,5,15,904] # list of number of trajectories to avg. over
    tlist=linspace(0,0.6,100)
    mc = mcf90.mcsolve_f90(H,psi0,tlist,c_op_list,[a.dag()*a],ntraj)
    #mc = mcsolve(H,psi0,tlist,c_op_list,[a.dag()*a],ntraj)
    # get expectation values from mc data (need extra index since ntraj is list)
    ex1=mc.expect[0][0]     #for ntraj=1
    ex5=mc.expect[1][0]     #for ntraj=5
    ex15=mc.expect[2][0]    #for ntraj=15
    ex904=mc.expect[3][0]   #for ntraj=904

    ## run master equation to get ensemble average expectation values ## 
    me = mesolve(H,psi0,tlist,c_op_list, [a.dag()*a])

    #  calulate final state using steadystate solver
    final_state=steadystate(H,c_op_list) # find steady-state
    fexpt=expect(a.dag()*a,final_state)  # find expectation value for particle number

    #
    # plot results using vertically stacked plots
    #
    
    # set legend fontsize
    import matplotlib.font_manager
    leg_prop = matplotlib.font_manager.FontProperties(size=10)
    
    f = figure(figsize=(6,9))
    subplots_adjust(hspace=0.001) #no space between plots
    
    # subplot 1 (top)
    ax1 = subplot(411)
    ax1.plot(tlist,ex1,'b',lw=2)
    ax1.axhline(y=fexpt,color='k',lw=1.5)
    yticks(linspace(0,2,5))
    ylim([-0.1,1.5])
    ylabel('$\left< N \\right>$',fontsize=14)
    title("Ensemble Averaging of Monte Carlo Trajectories")
    legend(('Single trajectory','steady state'),prop=leg_prop)
    
    # subplot 2
    ax2=subplot(412,sharex=ax1) #share x-axis of subplot 1
    ax2.plot(tlist,ex5,'b',lw=2)
    ax2.axhline(y=fexpt,color='k',lw=1.5)
    yticks(linspace(0,2,5))
    ylim([-0.1,1.5])
    ylabel('$\left< N \\right>$',fontsize=14)
    legend(('5 trajectories','steadystate'),prop=leg_prop)
    
    # subplot 3
    ax3=subplot(413,sharex=ax1) #share x-axis of subplot 1
    ax3.plot(tlist,ex15,'b',lw=2)
    ax3.plot(tlist,me.expect[0],'r--',lw=1.5)
    ax3.axhline(y=fexpt,color='k',lw=1.5)
    yticks(linspace(0,2,5))
    ylim([-0.1,1.5])
    ylabel('$\left< N \\right>$',fontsize=14)
    legend(('15 trajectories','master equation','steady state'),prop=leg_prop)
    
    # subplot 4 (bottom)
    ax4=subplot(414,sharex=ax1) #share x-axis of subplot 1
    ax4.plot(tlist,ex904,'b',lw=2)
    ax4.plot(tlist,me.expect[0],'r--',lw=1.5)
    ax4.axhline(y=fexpt,color='k',lw=1.5)
    yticks(linspace(0,2,5))
    ylim([-0.1,1.5])
    ylabel('$\left< N \\right>$',fontsize=14)
    legend(('904 trajectories','master equation','steady state'),prop=leg_prop)
    
    #remove x-axis tick marks from top 3 subplots
    xticklabels = ax1.get_xticklabels()+ax2.get_xticklabels()+ax3.get_xticklabels()
    setp(xticklabels, visible=False)
    
    ax1.xaxis.set_major_locator(MaxNLocator(4))
    xlabel('Time (sec)',fontsize=14)
    show()
    return mc