def prepareMPx(lam):
	thetain = -0/180*pl.pi
	nIn = 1.0
	nMaterial = 2.
	nOut = 1.
	pol = 'Ey'

	Mres = model(lx=320,lz=320,nelx=nelx)
	Pres = physics(Mres,lam,nIn,nOut,thetaIn=thetain,pol=pol)
	materialRes = Pres.newMaterial(nMaterial)
	xres = Mres.generateEmptyDesign()
	#Try vary the radius between 20 and 140
	makeCircle(xres,Mres,160,100,materialRes)
	if 1:	#Show design
		pl.imshow(xres.T,interpolation='none')
		pl.savefig('padeuc.png')
		exit()
	return Mres,Pres,xres
Пример #2
0
def calcdp(rep_no, thetainput):
    rep_no = rep_no
    wav = 505
    lam = 400
    thetain = thetainput / 180 * pl.pi
    nAir = 1.0
    nBac = 1.38
    nMed = 1.34
    pol = 'Ey'
    nelx = 40
    z_uc = 2.0 * math.sqrt(3)

    ##Reference model
    FE_start_time = time.time()
    Mres = model(lx=2 * lam, lz=(1 + rep_no) * (z_uc) * lam, nelx=nelx)
    Pres = physics(Mres, wav, nAir, nBac, thetaIn=thetain, pol=pol)
    if 1:  #Put to zero to avoid re-simulation and use last saved results
        materialResAir = Pres.newMaterial(nAir)
        materialResBac = Pres.newMaterial(nBac)
        materialResMed = Pres.newMaterial(nMed)

        xres = Mres.generateEmptyDesign()
        makeSlab(xres, Mres, (rep_no) * (z_uc) * lam,
                 (1 + rep_no) * (z_uc) * lam, materialResAir)
        makeSlab(xres, Mres, 0 * (z_uc) * lam, (rep_no) * (z_uc) * lam,
                 materialResMed)

        for x in range(0, rep_no):
            makeCircle(xres, Mres, lam, x * (z_uc) * lam, lam, materialResBac)
            makeCircle(xres, Mres, 0, (x + 1 / 2) * (z_uc) * lam, lam,
                       materialResBac)
            makeCircle(xres, Mres, 2 * lam, (x + 1 / 2) * (z_uc) * lam, lam,
                       materialResBac)
        makeCircle(xres, Mres, lam, (rep_no) * (z_uc) * lam, lam,
                   materialResBac)

        if 0:  #Show design
            pl.imshow(xres.T, interpolation='none', vmin=0, vmax=4)
            pl.colorbar()
            pl.savefig("full_structure.png", bbox_inches='tight')
            pl.show()
            exit()

        res = FE(Mres, Pres, xres)
        #saveDicts("SmatrixRIInternalReference.h5",res,'a')
    #else:
    #res = loadDicts("SmatrixRIInternalReference.h5")[0]
    mR, thetaR, R, mT, thetaT, T = calcRT(Mres, Pres, res["r"], res["t"])
    Rres = R
    Tres = T
    FE_time = time.time() - FE_start_time

    CSM_start_time = time.time()

    ##Scattering matrix model air-material boundary
    M = model(lx=2.0 * lam, lz=1 * (z_uc) * lam, nelx=nelx)
    P = physics(M, wav, nAir, nBac, thetaIn=thetain, pol=pol)
    materialAir = P.newMaterial(nAir)
    materialBac = P.newMaterial(nBac)
    materialMed = P.newMaterial(nMed)
    x = M.generateEmptyDesign()
    makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialAir)
    makeCircle(x, M, lam, 0, lam, materialBac)
    if 0:  #Show design
        pl.imshow(x.T, interpolation='none', vmin=0, vmax=4)
        pl.colorbar()
        pl.savefig("upper_half.png", bbox_inches='tight')
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)

    S1 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])
    matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(pl.sqrt(P.chiOut))]])
    matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(1 / pl.sqrt(P.chiOut))]])
    S1real = matL * S1 * matR

    Stot = S1
    Stotreal = S1real
    thetainNew = thetain

    ##Scattering matrix model unit cell
    M = model(lx=2.0 * lam, lz=(z_uc) * lam, nelx=nelx)
    thetainNew = pl.arcsin(P.nIn / P.nOut * pl.sin(thetainNew))
    P = physics(M, wav, nBac, nBac, thetaIn=thetainNew, pol=pol)  #
    materialAir = P.newMaterial(nAir)
    materialBac = P.newMaterial(nBac)
    materialMed = P.newMaterial(nMed)
    x = M.generateEmptyDesign()
    makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialMed)
    makeCircle(x, M, lam, 0, lam, materialBac)
    makeCircle(x, M, lam, 1.0 * (z_uc) * lam, lam, materialBac)
    makeCircle(x, M, 0, (1 / 2) * (z_uc) * lam, lam, materialBac)
    makeCircle(x, M, 2 * lam, (1 / 2) * (z_uc) * lam, lam, materialBac)
    if 0:  #Show design
        pl.imshow(x.T, interpolation='none', vmin=0, vmax=4)
        pl.colorbar()
        pl.savefig("lower_half.png", bbox_inches='tight')
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)
    S2 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])
    matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(pl.sqrt(P.chiOut))]])
    matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(1 / pl.sqrt(P.chiOut))]])
    S2real = matL * S2 * matR
    for x in range(1, rep_no + 1):
        Stot = stackElements(Stot, S2)
        Stotreal = stackElements(Stotreal, S2real)
    CSM_time = time.time() - CSM_start_time

    #Stack the two scattering elements
    #Stot = stackElements(S1,S2)

    RIn, TIn, TOut, ROut = StoRT(Stot)
    results = {}
    results["RIn"] = RIn
    results["TIn"] = TIn
    results["ROut"] = ROut
    results["TOut"] = TOut
    results.update(M.getParameters())
    results.update(P.getParameters())
    #saveDicts("SmatrixRICalculations.h5",results,'a')

    #Define incident wave as a plane wave
    einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
    einc[M.NM // 2, 0] = 1.
    tmp = Stot * einc
    rnew = tmp[:M.NM].view(pl.ndarray).flatten()
    tnew = tmp[M.NM:].view(pl.ndarray).flatten()
    mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(Mres, Pres, rnew, tnew)
    title = "speed_wrt_rep_no_FE.csv"
    txtdata = open(title, "a")
    txtdata.write("{:f}, {:.8f}\n".format(rep_no, FE_time))
    title = "speed_wrt_rep_no_CSM.csv"
    txtdata = open(title, "a")
    txtdata.write("{:f}, {:.8f}\n".format(rep_no, CSM_time))
    print("rep_no={:f}, FE_time={:.8f}, CSM_time={:.8f}".format(
        rep_no, FE_time, CSM_time))
    txtdata.close()

    #Define incident wave as a plane wave
    einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
    einc[M.NM // 2, 0] = 1.
    #Stotreal = S1real
    if 0:
        pl.imshow(abs(S1real), interpolation='none', vmin=0, vmax=1)
        print abs(S1real).max()
        pl.colorbar()
        pl.show()
        pl.imshow(abs(S2real), interpolation='none', vmin=0, vmax=1)
        print abs(S2real).max()
        pl.colorbar()
        pl.show()

    tmp = Stotreal * einc
    r = tmp[:M.NM].view(pl.ndarray).flatten()
    t = tmp[M.NM:].view(pl.ndarray).flatten()

    idx = Pres.propModesIn
    R = abs(r[idx])**2

    idx = Pres.propModesOut
    T = abs(t[idx])**2

    return
Пример #3
0
def calcdp(wavinput, thetainput):
    rep_no = 50
    wav = wavinput
    lam = 400
    thetain = thetainput / 180 * pl.pi
    nAir = 1.0
    nBac = 1.38
    nMed = 1.34
    #nMaterial2 = nIn	#When nMaterial2 == nIn, the methods works
    #nOut = nMaterial2
    pol = 'Ey'
    nelx = 40
    z_uc = 2.0 * math.sqrt(3)

    ##Scattering matrix model air-material boundary
    Mres = model(lx=2 * lam, lz=(1 + rep_no) * (z_uc) * lam, nelx=nelx)
    Pres = physics(Mres, wav, nAir, nBac, thetaIn=thetain, pol=pol)
    if 1:  #Put to zero to avoid re-simulation and use last saved results
        materialResAir = Pres.newMaterial(nAir)
        materialResBac = Pres.newMaterial(nBac)
        materialResMed = Pres.newMaterial(nMed)

        xres = Mres.generateEmptyDesign()
        makeSlab(xres, Mres, (rep_no) * (z_uc) * lam,
                 (1 + rep_no) * (z_uc) * lam, materialResAir)
        makeSlab(xres, Mres, 0 * (z_uc) * lam, (rep_no) * (z_uc) * lam,
                 materialResMed)

        for x in range(0, rep_no):
            makeCircle(xres, Mres, lam, x * (z_uc) * lam, lam, materialResBac)
            makeCircle(xres, Mres, 0, (x + 1 / 2) * (z_uc) * lam, lam,
                       materialResBac)
            makeCircle(xres, Mres, 2 * lam, (x + 1 / 2) * (z_uc) * lam, lam,
                       materialResBac)
        makeCircle(xres, Mres, lam, (rep_no) * (z_uc) * lam, lam,
                   materialResBac)

        if 0:  #Show design
            pl.imshow(xres.T, interpolation='none', vmin=0, vmax=4)
            pl.colorbar()
            pl.savefig("full_structure.png", bbox_inches='tight')
            pl.show()
            exit()

    ##Scattering matrix model air-material boundary
    M = model(lx=2.0 * lam, lz=1 * (z_uc) * lam, nelx=nelx)
    #Notice how nOut here is nMaterial2
    P = physics(M, wav, nAir, nBac, thetaIn=thetain, pol=pol)
    materialAir = P.newMaterial(nAir)
    materialBac = P.newMaterial(nBac)
    materialMed = P.newMaterial(nMed)
    x = M.generateEmptyDesign()
    makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialAir)
    makeCircle(x, M, lam, 0, lam, materialBac)
    if 0:  #Show design
        pl.imshow(x.T, interpolation='none', vmin=0, vmax=4)
        pl.colorbar()
        pl.savefig("upper_half.png", bbox_inches='tight')
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)

    S1 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])
    matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(pl.sqrt(P.chiOut))]])
    matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(1 / pl.sqrt(P.chiOut))]])
    S1real = matL * S1 * matR

    Stot = S1
    Stotreal = S1real
    thetainNew = thetain

    ##Scattering matrix model unit cell
    M = model(lx=2.0 * lam, lz=(z_uc) * lam, nelx=nelx)
    thetainNew = pl.arcsin(P.nIn / P.nOut * pl.sin(thetainNew))
    P = physics(M, wav, nBac, nBac, thetaIn=thetainNew, pol=pol)  #
    materialAir = P.newMaterial(nAir)
    materialBac = P.newMaterial(nBac)
    materialMed = P.newMaterial(nMed)
    x = M.generateEmptyDesign()
    makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialMed)
    makeCircle(x, M, lam, 0, lam, materialBac)
    makeCircle(x, M, lam, 1.0 * (z_uc) * lam, lam, materialBac)
    makeCircle(x, M, 0, (1 / 2) * (z_uc) * lam, lam, materialBac)
    makeCircle(x, M, 2 * lam, (1 / 2) * (z_uc) * lam, lam, materialBac)
    if 0:
        pl.imshow(x.T, interpolation='none', vmin=0, vmax=4)
        pl.colorbar()
        pl.savefig("lower_half.png", bbox_inches='tight')
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)
    S2 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])
    matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(pl.sqrt(P.chiOut))]])
    matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(1 / pl.sqrt(P.chiOut))]])
    S2real = matL * S2 * matR
    for x in range(1, rep_no + 1):
        Stot = stackElements(Stot, S2)
        Stotreal = stackElements(Stotreal, S2real)

    RIn, TIn, TOut, ROut = StoRT(Stot)
    results = {}
    results["RIn"] = RIn
    results["TIn"] = TIn
    results["ROut"] = ROut
    results["TOut"] = TOut
    results.update(M.getParameters())
    results.update(P.getParameters())
    #saveDicts("SmatrixRICalculations.h5",results,'a')

    #Define incident wave as a plane wave
    einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
    einc[M.NM // 2, 0] = 1.
    tmp = Stot * einc
    rnew = tmp[:M.NM].view(pl.ndarray).flatten()
    tnew = tmp[M.NM:].view(pl.ndarray).flatten()
    mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(Mres, Pres, rnew, tnew)
    for i in range(len(mR)):
        title = "reflect_mode_n_equals_{:d}_50.csv".format(mR[i])
        txtdata = open(title, "a")
        txtdata.write("{:d}, {:f}, {:.8f}\n".format(wavinput, thetainput,
                                                    Rnew[i]))
        #print("m={:d}, theta={:f}, mode={:d}, R={:.8f}".format(wavinput,thetainput,mR[i],Rnew[i]))
        txtdata.close()
    for i in range(len(mT)):
        title = "trans_mode_n_equals_{:d}_50.csv".format(mT[i])
        txtdata = open(title, "a")
        txtdata.write("{:d}, {:f}, {:.8f}\n".format(wavinput, thetainput,
                                                    Tnew[i]))
        #print("m={:d}, theta={:f}, mode={:d}, T={:.8f}".format(wavinput,thetainput,mT[i],Tnew[i]))
        txtdata.close()

    #Define incident wave as a plane wave
    einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
    einc[M.NM // 2, 0] = 1.
    #Stotreal = S1real
    if 0:
        pl.imshow(abs(S1real), interpolation='none', vmin=0, vmax=1)
        print abs(S1real).max()
        pl.colorbar()
        pl.show()
        pl.imshow(abs(S2real), interpolation='none', vmin=0, vmax=1)
        print abs(S2real).max()
        pl.colorbar()
        pl.show()

    tmp = Stotreal * einc
    r = tmp[:M.NM].view(pl.ndarray).flatten()
    t = tmp[M.NM:].view(pl.ndarray).flatten()

    idx = Pres.propModesIn
    R = abs(r[idx])**2

    idx = Pres.propModesOut
    T = abs(t[idx])**2
    return
Пример #4
0
def main():
    lam = 505
    thetain = -30 / 180 * pl.pi
    nIn = 1.0
    nMaterial = 12.
    nOut = 2.
    pol = 'Ey'

    ##Reference model (one circle + one burried circle)
    Mres = model(lx=lam, lz=2 * lam, nelx=40)
    Pres = physics(Mres, lam, nIn, nOut, thetaIn=thetain, pol=pol)
    if 1:  #Put to zero to avoid re-simulation and use last saved results
        materialRes = Pres.newMaterial(nMaterial)
        materialOut = Pres.newMaterial(nOut)

        xres = Mres.generateEmptyDesign()
        makeSlab(xres, Mres, 0, 0.5 * lam,
                 materialOut)  #make bottom part of domain nOut
        makeCircle(xres, Mres, 250, 200, materialRes)
        makeCircle(xres, Mres, 250 + lam, 200, materialRes)

        if 1:  #Show design
            pl.imshow(xres.T, interpolation='none')
            pl.colorbar()
            pl.show()
            exit()

        res = FE(Mres, Pres, xres)
        saveDicts("SmatrixRIReference.h5", res, 'w')
    else:
        res = loadDicts("SmatrixRIReference.h5")[0]
    mR, thetaR, R, mT, thetaT, T = calcRT(Mres, Pres, res["r"], res["t"])
    Rres = R
    Tres = T

    ##Scattering matrix model 1 (one circle)
    M = model(lx=lam, lz=lam, nelx=40)
    #Notice how nOut here is the same as nIn
    P = physics(M, lam, nIn, nIn, thetaIn=thetain, pol=pol)
    material = P.newMaterial(nMaterial)
    x = M.generateEmptyDesign()
    makeCircle(x, M, 250, 200, material)
    if 0:  #Show design
        pl.imshow(x.T, interpolation='none')
        pl.colorbar()
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)
    S1 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])

    ##Scattering matrix model 2 (one burried circle)
    M = model(lx=lam, lz=lam, nelx=40)
    P = physics(M, lam, nIn, nOut, thetaIn=thetain, pol=pol)
    material = P.newMaterial(nMaterial)
    materialOut = P.newMaterial(nOut)
    x = M.generateEmptyDesign()
    makeSlab(x, M, 0, 0.5 * lam, materialOut)
    makeCircle(x, M, 250, 200, material)
    if 0:  #Show design
        pl.imshow(x.T, interpolation='none')
        pl.colorbar()
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)
    S2 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])

    #Stack the two scattering elements
    Stot = stackElements(S1, S2)

    #Define incident wave as a plane wave
    einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
    einc[M.NM // 2, 0] = 1.
    tmp = Stot * einc
    rnew = tmp[:M.NM].view(pl.ndarray).flatten()
    tnew = tmp[M.NM:].view(pl.ndarray).flatten()
    mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(Mres, Pres, rnew, tnew)
    print("-" * 32)
    print("Error in reflection  : {:.2e}".format(abs(Rnew - Rres).max()))
    print("Error in transmission: {:.2e}".format(abs(Tnew - Tres).max()))
Пример #5
0
def main():
    lam = 505
    thetain = -30 / 180 * pl.pi
    nIn = 2.8
    nMaterial1 = 5.9
    nMaterial2 = 4.2
    #nMaterial2 = nIn	#When nMaterial2 == nIn, the methods works
    nOut = 4.3  #If nOut<nIn, we can have values in the S matrix exceeding 1
    nOut = 2.1
    #nOut = nMaterial2
    pol = 'Ey'
    nelx = 80

    ##Reference model (one circle + one burried circle)
    Mres = model(lx=lam, lz=2 * lam, nelx=nelx)
    Pres = physics(Mres, lam, nIn, nOut, thetaIn=thetain, pol=pol)
    if 1:  #Put to zero to avoid re-simulation and use last saved results
        materialRes1 = Pres.newMaterial(nMaterial1)
        materialRes2 = Pres.newMaterial(nMaterial2)
        materialResOut = Pres.newMaterial(nOut)

        xres = Mres.generateEmptyDesign()
        makeSlab(xres, Mres, 0, 0.5 * lam, materialResOut)
        makeSlab(xres, Mres, 0.5 * lam, 1.5 * lam, materialRes2)
        makeCircle(xres, Mres, 250, 200, materialRes1)
        makeCircle(xres, Mres, 250 + lam, 200, materialRes1)

        if 0:  #Show design
            pl.imshow(xres.T, interpolation='none', vmin=0, vmax=4)
            pl.colorbar()
            pl.savefig("full_structure.png", bbox_inches='tight')
            pl.show()
            exit()

        res = FE(Mres, Pres, xres)
        saveDicts("SmatrixRIInternalReference.h5", res, 'w')
    else:
        res = loadDicts("SmatrixRIInternalReference.h5")[0]
    mR, thetaR, R, mT, thetaT, T = calcRT(Mres, Pres, res["r"], res["t"])
    Rres = R
    Tres = T

    ##Scattering matrix model 1 (one burried circle)
    M = model(lx=lam, lz=lam, nelx=nelx)
    #Notice how nOut here is nMaterial2
    P = physics(M, lam, nIn, nMaterial2, thetaIn=thetain, pol=pol)
    material1 = P.newMaterial(nMaterial1)
    material2 = P.newMaterial(nMaterial2)
    x = M.generateEmptyDesign()
    makeSlab(x, M, 0, .5 * lam, material2)
    makeCircle(x, M, 250, 200, material1)
    if 0:  #Show design
        pl.imshow(x.T, interpolation='none', vmin=0, vmax=4)
        pl.colorbar()
        pl.savefig("upper_half.png", bbox_inches='tight')
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)

    S1 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])
    matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(pl.sqrt(P.chiOut))]])
    matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(1 / pl.sqrt(P.chiOut))]])
    S1real = matL * S1 * matR

    ##Scattering matrix model 2 (one burried circle)
    M = model(lx=lam, lz=lam, nelx=nelx)
    thetainNew = pl.arcsin(P.nIn / P.nOut * pl.sin(thetain))
    P = physics(M, lam, nMaterial2, nOut, thetaIn=thetainNew, pol=pol)
    material1 = P.newMaterial(nMaterial1)
    material2 = P.newMaterial(nMaterial2)
    materialOut = P.newMaterial(nOut)
    x = M.generateEmptyDesign()
    makeSlab(x, M, .5 * lam, lam, material2)
    makeSlab(x, M, 0, .5 * lam, materialOut)
    makeCircle(x, M, 250, 200, material1)
    if 0:  #Show design
        pl.imshow(x.T, interpolation='none', vmin=0, vmax=4)
        pl.colorbar()
        pl.savefig("lower_half.png", bbox_inches='tight')
        pl.show()
        exit()
    res = calcScatteringMatrix(M, P, x)
    S2 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"])
    matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(pl.sqrt(P.chiOut))]])
    matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)),
                     pl.zeros((M.NM, M.NM))],
                    [pl.zeros((M.NM, M.NM)),
                     pl.diag(1 / pl.sqrt(P.chiOut))]])
    S2real = matL * S2 * matR

    if 0:
        #Define incident wave as a plane wave
        einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
        einc[M.NM // 2, 0] = 1.

        tmp = S2 * einc
        rnew = tmp[:M.NM].view(pl.ndarray).flatten()
        tnew = tmp[M.NM:].view(pl.ndarray).flatten()
        mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(M, P, rnew, tnew)

        tmp = S2real * einc
        r = tmp[:M.NM].view(pl.ndarray).flatten()
        t = tmp[M.NM:].view(pl.ndarray).flatten()
        idx = P.propModesIn
        R = abs(r[idx])**2
        idx = P.propModesOut
        T = abs(t[idx])**2
        print "-" * 50
        print R
        print Rnew
        print T
        print Tnew
        print abs(R - Rnew).max()
        print abs(T - Tnew).max()
        exit()

    #Stack the two scattering elements
    Stot = stackElements(S1, S2)

    #Define incident wave as a plane wave
    einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
    einc[M.NM // 2, 0] = 1.
    tmp = Stot * einc
    rnew = tmp[:M.NM].view(pl.ndarray).flatten()
    tnew = tmp[M.NM:].view(pl.ndarray).flatten()
    mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(Mres, Pres, rnew, tnew)
    print("-" * 32)
    print(Rres)
    print(Rnew)
    print("-" * 10)
    print(Tres)
    print(Tnew)
    print("-" * 32)
    print("Error in reflection  : {:.2e}".format(abs(Rnew - Rres).max()))
    print("Error in transmission: {:.2e}".format(abs(Tnew - Tres).max()))
    #print("(note: since the significant numbers are in general between 0.01 and 1")
    #print(" we required a much lower error (1e-6 or better) to confirm that it works)")

    #Define incident wave as a plane wave
    einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix)
    einc[M.NM // 2, 0] = 1.

    Stotreal = stackElements(S1real, S2real)
    #Stotreal = S1real
    if 1:
        pl.imshow(abs(S1real), interpolation='none', vmin=0, vmax=1)
        print abs(S1real).max()
        pl.colorbar()
        pl.show()
        pl.imshow(abs(S2real), interpolation='none', vmin=0, vmax=1)
        print abs(S2real).max()
        pl.colorbar()
        pl.show()

    tmp = Stotreal * einc
    r = tmp[:M.NM].view(pl.ndarray).flatten()
    t = tmp[M.NM:].view(pl.ndarray).flatten()

    idx = Pres.propModesIn
    R = abs(r[idx])**2

    idx = Pres.propModesOut
    T = abs(t[idx])**2

    print "-" * 50
    print Rres
    print Rnew
    print R
    print("Error in reflection  : {:.2e}".format(abs(R - Rres).max()))
    print("Error in transmission: {:.2e}".format(abs(T - Tres).max()))