def main_routine (wd="./",cfg="./python/parameter.cfg",delayCnt=11,delay=27.725,phaseCnt=11,sType=1,p3d=0,AMap="Blues",RMap="Reds",IMap="Greens"):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

#  FuncInfo      = sp.zeros([3,delayCnt,phaseCnt])
#  FuncInfoPhase = sp.zeros([3,delayCnt,phaseCnt])
#  FuncShiftRead = sp.zeros([3,delayCnt,phaseCnt,functime.size],complex)
  FuncShiftRead = sp.zeros([delayCnt,phaseCnt,functime.size],complex)
  FuncInfoOlap  = sp.zeros([3,delayCnt,phaseCnt])
  FuncInfoArea  = sp.zeros([3,delayCnt,phaseCnt])

  for i in sp.arange(0.0,delayCnt):
    myDelay = i/(delayCnt-1.0)*delay

    shift=sp.absolute(time['read'][:]-(functime[0]-myDelay)).argmin()-1
    
    for j in sp.arange(0.0,phaseCnt):
      phi = j*2.0*sp.pi/(phaseCnt-1.0)
      
      FuncShiftRead[i,j,:]  = sp.exp(-1j*phi)*Reg2Down[shift:shift+functime.size] + Reg2Read[shift:shift+functime.size]
      FuncShiftRead[i,j,:] += Reg2UpRead  [ti:tf] # ????? why ??????


      FuncInfoIntegrand     = sp.absolute(FuncShiftRead[i,j,:])*sp.absolute(Reg2UpRead[ti:tf])
      FuncInfoOlap [0,i,j]  = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]

      FuncInfoIntegrand     = FuncShiftRead[i,j,:].conj() * Reg2UpRead[ti:tf]
      FuncInfoOlap [1,i,j]  = cumtrapz( FuncInfoIntegrand.real, x=None, dx=dt )[-1]
      FuncInfoOlap [2,i,j]  = cumtrapz( FuncInfoIntegrand.imag, x=None, dx=dt )[-1]


      FuncInfoArea [0,i,j]  = cumtrapz( sp.absolute(FuncShiftRead[i,j,:])**2, x=None, dx=dt )[-1]
      FuncInfoArea [1,i,j]  = cumtrapz( sp.real    (FuncShiftRead[i,j,:])   , x=None, dx=dt )[-1]
      FuncInfoArea [2,i,j]  = cumtrapz( sp.imag    (FuncShiftRead[i,j,:])   , x=None, dx=dt )[-1]



  xx, yy = sp.meshgrid(sp.linspace(0.0,2.0*sp.pi,phaseCnt),sp.linspace(0.0,delay,delayCnt))

  zzOlap2 = FuncInfoOlap[0,:,:]#/(sp.absolute(FuncInfoOlap[0,:,:]).max())
  zzOlapR = FuncInfoOlap[1,:,:]#/(sp.absolute(FuncInfoOlap[1,:,:]).max())
  zzOlapI = FuncInfoOlap[2,:,:]#/(sp.absolute(FuncInfoOlap[2,:,:]).max())

  zzArea2 = FuncInfoArea[0,:,:]#/(sp.absolute(FuncInfoArea[0,:,:]).max())
  zzAreaR = FuncInfoArea[1,:,:]#/(sp.absolute(FuncInfoArea[1,:,:]).max())
  zzAreaI = FuncInfoArea[2,:,:]#/(sp.absolute(FuncInfoArea[2,:,:]).max())

  zmin   = 0.0
  zmax   = +1.0
  fs     = 20

  fig  = plt.figure()

  fig1 = fig.add_subplot(231, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapR, rstride=5, cstride=5, cmap=RMap, alpha=0.5,zorder=11.0,vmin=zzOlapR.min(), vmax=zzOlapR.max())
#  fig1.contourf(xx, yy, zzOlapR, zdir='z', offset=zmin, cmap=RMap, vmin=-1, vmax=1,zorder=1.0)
  fig1.set_zlim(zzOlapR.min(),zzOlap2.max())
  fig1.set_title("a) Re$(O_{\mathbb{C}}(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t);A_1(t)))$",fontsize=fs)
  fig1.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig1.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig2 = fig.add_subplot(232, projection='3d')
  fig2.plot_surface(xx, yy, zzOlapI, rstride=5, cstride=5, cmap=IMap, alpha=0.5,zorder=11.0,vmin=zzOlapI.min(), vmax=zzOlapI.max())
#  fig2.contourf(xx, yy, zzOlapI, zdir='z', offset=zmin, cmap=IMap, vmin=-1, vmax=1,zorder=1.0)
  fig2.set_zlim(zzOlapI.min(),zzOlapI.max())
  fig2.set_title("b) Im$(O_{\mathbb{C}}(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t);A_1(t)))$",fontsize=fs)
  fig2.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig2.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig0 = fig.add_subplot(233, projection='3d')
  fig0.plot_surface(xx, yy, zzOlap2, rstride=5, cstride=5, cmap=AMap, alpha=0.5,zorder=11.0,vmin=zzOlap2.min(), vmax=zzOlap2.max())
#  fig0.contourf(xx, yy, zzOlap2, zdir='z', offset=zmin, cmap=AMap, vmin=0, vmax=1,zorder=1.0)
  fig0.set_zlim(zzOlap2.min(),zzOlap2.max())
  fig0.set_title("c) $O_{\mathbb{R}}(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t);A_1(t))$",fontsize=fs)
  fig0.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig0.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig4 = fig.add_subplot(234, projection='3d')
  fig4.plot_surface(xx, yy, zzAreaR, rstride=5, cstride=5, cmap=RMap, alpha=0.5,zorder=11.0,vmin=zzAreaR.min(), vmax=zzAreaR.max())
#  fig4.contourf(xx, yy, zzAreaR, zdir='z', offset=zmin, cmap=RMap, vmin=-1, vmax=1,zorder=1.0)
  fig4.set_zlim(zzAreaR.min(),zzAreaR.max())
  fig4.set_title("d) Area under Re$(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t))$",fontsize=fs)
  fig4.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig4.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig5 = fig.add_subplot(235, projection='3d')
  fig5.plot_surface(xx, yy, zzAreaI, rstride=5, cstride=5, cmap=IMap, alpha=0.5,zorder=11.0,vmin=zzAreaI.min(), vmax=zzAreaI.max())
 # fig5.contourf(xx, yy, zzAreaI, zdir='z', offset=zmin, cmap=IMap, vmin=-1, vmax=1,zorder=1.0)
  fig5.set_zlim(zzAreaI.min(),zzAreaI.max())
  fig5.set_title("e) Area under Im$(e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t))$",fontsize=fs)
  fig5.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig5.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  fig3 = fig.add_subplot(236, projection='3d')
  fig3.plot_surface(xx, yy, zzArea2, rstride=5, cstride=5, cmap=AMap, alpha=0.5,zorder=11.0,vmin=zzArea2.min(), vmax=zzArea2.max())
#  fig3.contourf(xx, yy, zzArea2, zdir='z', offset=zmin, cmap=AMap, vmin=0, vmax=1,zorder=1.0)
  fig3.set_zlim(zzArea2.min(),zzArea2.max())
  fig3.set_title("f) Area under $|e^{-i\Phi_0}A_0(t-\Delta t)+A_1(t)|^2$",fontsize=fs)
  fig3.set_ylabel("$\Delta t$ in ns",fontsize=fs)
  fig3.set_xlabel("$\Phi_0/\pi$",fontsize=fs)

  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",thetaCnt=11,phiCnt=11,bloch=0,myMap="jet",minOlap=0,fortranCheck=0,gridR=5,gridC=5):

  ### read config file ###
  print ("load from config file: " + cfg)
  cfg=IOHelper.loadCfg(wd,cfg)

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  spos          = sp.zeros([2,thetaCnt,phiCnt],complex)
  FuncInfoOlap  = sp.zeros([2,thetaCnt,phiCnt],complex)
  gamma         = sp.zeros([thetaCnt,phiCnt],complex)
  delta         = sp.zeros([thetaCnt,phiCnt],complex)

#  I00  = 1j*cumtrapz( (Reg2Down[ti:tf].conj() * Reg2Down[ti:tf]).imag, x=None, dx=dt )[-1]
  I00  =    cumtrapz( (Reg2Down[ti:tf] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]
  I01  = 1j*cumtrapz( (Reg2Up  [ti:tf] * Reg2Down[ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I01 +=    cumtrapz( (Reg2Up  [ti:tf] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]
  I0R  = 1j*cumtrapz( (Reg2Read[ti:tf] * Reg2Down[ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I0R +=    cumtrapz( (Reg2Read[ti:tf] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]

#  I11  = 1j*cumtrapz( (Reg2Up  [ti:tf].conj() * Reg2Up  [ti:tf]).imag, x=None, dx=dt )[-1]
  I11  =    cumtrapz( (Reg2Up  [ti:tf] * Reg2Up  [ti:tf].conj()).real, x=None, dx=dt )[-1]
  I10  = 1j*cumtrapz( (Reg2Down[ti:tf] * Reg2Up  [ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I10 +=    cumtrapz( (Reg2Down[ti:tf] * Reg2Up  [ti:tf].conj()).real, x=None, dx=dt )[-1]
  I1R  = 1j*cumtrapz( (Reg2Read[ti:tf] * Reg2Up  [ti:tf].conj()).imag, x=None, dx=dt )[-1]
  I1R +=    cumtrapz( (Reg2Read[ti:tf] * Reg2Up  [ti:tf].conj()).real, x=None, dx=dt )[-1]

  for i in sp.arange(0.0,thetaCnt):
    theta = i/(thetaCnt-1.0)   # from 0 to 1 * pi
    
    for j in sp.arange(0.0,phiCnt):
      phi = j/(phiCnt-1.0)*2.0 # from 0 to 2 * pi
      
      spos[0,i,j]    = sp.cos(theta*sp.pi/2.0) 
      spos[1,i,j]    = sp.sin(theta*sp.pi/2.0)*sp.exp(1j*phi*sp.pi)

  if fortranCheck == 1:
    cmd = "./scripts/ifort-checkBloch.sh " + wd
    print ("compile fortran routines: "+cmd)
    call(cmd.split())

    print ("### call checkBloch")
    cmd=wd+"checkBloch"
    generateSuperposition = Popen(cmd.split(), stdin=PIPE)                     # run fortran program with piped standard input
    cmd = "echo {:}".format(thetaCnt)                                          # communication with fortran-routine: chose superposition parameter
    generateInput     = Popen(cmd.split(), stdout=generateSuperposition.stdin) # send action to fortran program
    cmd = "echo {:}".format(phiCnt)                                            # communication with fortran-routine: chose superposition parameter
    generateInput     = Popen(cmd.split(), stdout=generateSuperposition.stdin) # send action to fortran program
    output            = generateSuperposition.communicate()[0]
    generateInput.wait()

    FuncInfoOlap [0,:,:],FuncInfoOlap [1,:,:]=IOHelper.read_MtrxProjection(thetaCnt,phiCnt,**cfg['FILES'])

  else:
    for i in sp.arange(0.0,thetaCnt):     
      for j in sp.arange(0.0,phiCnt):
        FuncCavity     = spos[0,i,j]*Reg2Down[ti:tf] + spos[1,i,j]*Reg2Up[ti:tf]
        FuncCavity[:] += Reg2Read  [ti:tf]

        FuncInfoOlap [0,i,j]  =    cumtrapz( (FuncCavity[:] * Reg2Down[ti:tf].conj()).real, x=None, dx=dt )[-1]
        FuncInfoOlap [0,i,j] += 1j*cumtrapz( (FuncCavity[:] * Reg2Down[ti:tf].conj()).imag, x=None, dx=dt )[-1]

        FuncInfoOlap [1,i,j]  =    cumtrapz( (FuncCavity[:] * Reg2Up[ti:tf].conj()).real, x=None, dx=dt )[-1]
        FuncInfoOlap [1,i,j] += 1j*cumtrapz( (FuncCavity[:] * Reg2Up[ti:tf].conj()).imag, x=None, dx=dt )[-1]

  if minOlap==0:
    gamma[:,:]=((FuncInfoOlap [0,:,:]-I0R)*I11+(I1R-FuncInfoOlap [1,:,:])*I01)/(I11*I00-I01*I10)
    delta[:,:]=((FuncInfoOlap [1,:,:]-I1R)*I00+(I0R-FuncInfoOlap [0,:,:])*I10)/(I11*I00-I01*I10)
  else :
    gamma[:,:]= (FuncInfoOlap [0,:,:]-I0R)/I00
    delta[:,:]= (FuncInfoOlap [1,:,:]-I1R)/I11

  fs   = 22
  label_size = 12
  plt.rcParams['xtick.labelsize'] = label_size 
  plt.rcParams['ytick.labelsize'] = label_size 
  plt.rcParams['xtick.major.pad']='20'
  plt.rcParams['ytick.major.pad']='20'
  fig  = plt.figure()

  if bloch == 0:
    xx, yy = sp.meshgrid(sp.linspace(0.0,2.0,phiCnt),sp.linspace(0.0,1.0,thetaCnt))

    zmin   =  0.0
    zmax   = +1.0

    zzOlapR0 = gamma [:,:].real
    zzOlapI0 = gamma [:,:].imag
    zzErr0   = sp.absolute(gamma[:,:]-spos[0,:,:])

    zzOlapR1 = delta [:,:].real
    zzOlapI1 = delta [:,:].imag
    zzErr1   = sp.absolute(delta[:,:]-spos[1,:,:])    

    fig1 = fig.add_subplot(321, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapR0, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR0.min(), vmax=zzOlapR0.max())
    fig1.set_zlim(0,1)
#    fig1.set_title("Re$[\,\gamma_R\,]\\approx\cos(\\theta/2)$",fontsize=fs)
    fig1.set_title("Re$[\,\gamma_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)

    fig1 = fig.add_subplot(323, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapI0, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI0.min(), vmax=zzOlapI0.max())
#    fig1.set_zlim(-0.01,0.01)
#    fig1.set_title("Im$[\,\gamma_R\,]\\approx\cos(\\theta/2)$",fontsize=fs)
    fig1.set_title("Im$[\,\gamma_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W/\pi$",fontsize=fs)

    fig1 = fig.add_subplot(322, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapR1, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR1.min(), vmax=zzOlapR1.max())
    fig1.set_zlim(-1,1)
#    fig1.set_title("Re$[\,\delta_R\,]\\approx\sin(\\theta/2)\cos(\phi)$",fontsize=fs)
    fig1.set_title("Re$[\,\delta_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)

    fig1 = fig.add_subplot(324, projection='3d')
    fig1.plot_surface(xx, yy, zzOlapI1, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI1.min(), vmax=zzOlapI1.max())
    fig1.set_zlim(-1,1)
#    fig1.set_title("Im$[\,\delta_R\,]\\approx\sin(\\theta/2)\sin(\phi)$",fontsize=fs)
    fig1.set_title("Im$[\,\delta_R\,]$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W/\pi$",fontsize=fs)

    fig1 = fig.add_subplot(325, projection='3d')
    fig1.plot_surface(xx, yy, zzErr0, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzErr0.min(), vmax=zzErr0.max())
#    fig1.set_zlim(-1,1)
#    fig1.set_title("Re$[\,\delta_R\,]\\approx\sin(\\theta/2)\cos(\phi)$",fontsize=fs)
    fig1.set_title("$\epsilon_\gamma$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)


    fig1 = fig.add_subplot(326, projection='3d')
    fig1.plot_surface(xx, yy, zzErr1, rstride=gridR, cstride=gridC, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzErr1.min(), vmax=zzErr1.max())
#    fig1.set_zlim(-1,1)
#    fig1.set_title("Re$[\,\delta_R\,]\\approx\sin(\\theta/2)\cos(\phi)$",fontsize=fs)
    fig1.set_title("$\epsilon_\delta$",fontsize=fs)
    fig1.set_ylabel("$\\theta_W/\pi$",fontsize=fs)
    fig1.set_xlabel("$\phi_W / \pi$",fontsize=fs)

  else:
  
#    x_expect = 2e0*sp.real(FuncInfoOlap [0,:,:]*FuncInfoOlap [1,:,:])
#  

    x      = 2e0*sp.real(spos[0,:,:].conj()*spos [1,:,:])
    y      = 2e0*sp.real(spos[0,:,:].conj()*spos [1,:,:]/1.0j)
    z      = sp.absolute(spos[0,:,:])**2   -sp.absolute(spos [1,:,:])**2

    xprime = 2e0*sp.real(gamma [:,:].conj()*delta [:,:])
    yprime = 2e0*sp.real(gamma [:,:].conj()*delta [:,:]/1.0j)
    zprime = sp.absolute(gamma [:,:])**2   -sp.absolute(delta [:,:])**2
    
    myDensity = sp.sqrt(sp.absolute(x-xprime)**2 + sp.absolute(y-yprime)**2 + sp.absolute(z-zprime)**2)
#    myDensity = 1.0 -  (x*xprime + y*yprime + z*zprime) 
    
    cm       = plt.cm.get_cmap(myMap) 
    myMin    = myDensity.min()
    myMax    = max(sp.absolute(myDensity.max()),sp.absolute(myDensity.min()))
    myColors = cm(myDensity/myMax)
    m        = plt.cm.ScalarMappable(cmap=myMap)

    fig3D = fig.add_subplot(1, 1, 1, projection='3d')

    surf  = fig3D.plot_surface(xprime, yprime, zprime, rstride=1, cstride=1, linewidth=1, color="black", 
                               facecolors=myColors,shade=False,antialiased=True,
                               vmin=myMin, vmax=myMax)
#    fig3D.plot_wireframe(x*1.01, y*1.01, z*1.01, rstride=1, cstride=1,alpha=1,linewidth=1,color="black")
    tick2=(myMin+myMax)/2.0
    tick1=round_sig(myMin+(myMax-myMin)*0.1,2)
    tick3=round_sig(myMax-(myMax-myMin)*0.1,2)
    tick2=round_sig(tick2,2)
    print "### error boundaries:", tick1,tick2,tick3

    m.set_array(myDensity)
    cb= plt.colorbar(m,shrink=0.5,aspect=7,ticks=([tick1,tick2,tick3]))    
    cb.formatter.set_scientific(True) 
    cb.formatter.set_powerlimits((0, 0))
    cb.update_ticks()
    
    fig3D.set_xlabel("$\langle \sigma_x(\gamma^\prime,\delta^\prime) \\rangle$", fontsize=fs)
    fig3D.set_ylabel("$\langle \sigma_y(\gamma^\prime,\delta^\prime) \\rangle$", fontsize=fs)
    fig3D.set_zlabel("$\langle \sigma_z(\gamma^\prime,\delta^\prime) \\rangle$", fontsize=fs)
    
    fig3D.set_xticks([-1,0,1])
    fig3D.set_xlim([-1.01,1.01])
    fig3D.xaxis._axinfo['label']['space_factor'] = 2.0

    fig3D.set_yticks([-1,0,1])
    fig3D.set_ylim([-1.01,1.01])
    fig3D.yaxis._axinfo['label']['space_factor'] = 2.0

    fig3D.set_zticks([-1,0,1])
    fig3D.set_zlim([-1.01,1.01])
    fig3D.zaxis._axinfo['label']['space_factor'] = 2.0

    
  plt.show()
def main_routine (writeBase=8.0,writeCnt=1,readBase=2.0,readCnt=1,datPath="dat/",prefix="pa",destPath="../parallel/",gentype="c",funcCfg=0):
  """
     Parameters:
       -----------
       --writeBase: maximum value of writing time interval in multiples of Pi/{base_rabi}.
                    (float)
       --wirteCnt:  number of different writing intervals from 1.0 to writeBase times Pi/{base_rabi}
                    (int)
       --readBase:  maximum value of reading time interval in multiples of Pi/{base_rabi}.
                    (float)
       --readCnt:   number of different reading intervals from 1.0 to readBase times Pi/{base_rabi}
                    (int)
       --destPath:  directory where output files are generated (for every parameter setting of
                    writeBase/writeCnt, readBase/readCnt a corresponding subdirectory is created)
                    (string)
       --gentype :  type of data generation -->
                    g : generate data with modNv
                    r : read data with modNv and 
                    c : collect  data and produce 3d plot of reading area
  """
  dWrite   = sp.array(range(0,writeCnt))
  dRead    = sp.array(range(0,readCnt))

  if (writeCnt == 1):
    write_base = sp.ones([readCnt])*writeBase
  else:
    write_base = (1.0+(writeBase-1.0)/float(writeCnt-1)*dWrite[:])

  if (readCnt == 1):
    read_base = sp.ones([writeCnt])*readBase
  else:
    read_base  = (1.0+(readBase-1.0)/float(readCnt-1)*dRead[:])

  print read_base

#  print (write_base)
#  print (read_base)

  if (gentype=="g" or gentype=="r"): # generate
    pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())

    results = [ pool.apply_async(run_single_job, args=(wb,rb,datPath,prefix,destPath,gentype,funcCfg))
                 for wb,rb in zip(write_base, read_base) ]

    results = [ p.get() for p in results ]
    pool.terminate()

  elif (gentype=="c"): # collect

    configPath="./python/parameter.cfg"
    print ("load from config file: " + configPath)
    configParser = cp.ConfigParser()
    configParser.read(configPath)
    cfg=configParser.__dict__['_sections'].copy()
   
    nRead =int(cfg['OCFourier']['{read_harmonic}'])
    nWrite=int(cfg['OCFourier']['{write_harmonic}'])

    timeCntWrite = int(cfg['OCTime']['{write_timecnt}'])
    timeCntRead  = int(cfg['OCTime']['{read_timecnt}'])
    timeCnt      = timeCntRead+timeCntWrite

    omega_c=float(cfg['NVSETUP']['{omega_c}'])*2.0*sp.pi
    omega_r=float(cfg['OCFourier']['{base_rabi}'])/1e6
    tUnit  =sp.pi/(2.0*sp.pi*1e3*omega_r)

    filelist=[]
    div     =10.0
#    readCnt = 17
    cavity=sp.zeros((2,readCnt,timeCntRead))
    time    =sp.zeros(timeCnt)
    wb=write_base[-1]  # choose last element
    errCnt=[]

    name_optimized=cfg['FILES']['{name_optimized}']
    name_readwrite=IOHelper.getNameReadWrite(**cfg) 


    for rb in range(readCnt):
      newDir=dest(destPath,wb,read_base[rb])
      cfg['FILES']['{prefix}'] = newDir+datPath+prefix+name_readwrite+name_optimized

      try:
        filename=cfg['FILES']['{prefix}']+"cavityMode_read_down"+cfg['FILES']['{postfix}']
        print filename
        time,real,imag = sp.loadtxt(filename).T
        cavity[0,rb,:] = real[timeCntWrite:timeCntWrite+timeCntRead]**2+imag[timeCntWrite:timeCntWrite+timeCntRead]**2
      except:
        errCnt.append("down: {:8.4f}\n".format(read_base[rb]))

      try:
        filename=cfg['FILES']['{prefix}']+"cavityMode_read_up"+cfg['FILES']['{postfix}']
        time,real,imag = sp.loadtxt(filename).T
        cavity[1,rb,:] = real[timeCntWrite:timeCntWrite+timeCntRead]**2+imag[timeCntWrite:timeCntWrite+timeCntRead]**2
      except:
        errCnt.append("up: {:8.4f}\n".format(read_base[rb]))

    if (len(errCnt) != 0):
      print ("can't read some files:\n" + str(errCnt))

    print ("generating color map")

    # read funtional times t2, t3
    newDir=dest(destPath,wb,read_base.max())
    cfg['FILES']['{prefix}']=newDir+datPath+prefix
    functime                =IOHelper.functionaltimes_readwrite(**cfg)

    ti=float(functime['ti'])/omega_c/tUnit  # in nano seconds
    ti_i = int(functime['idx_ti'])-1

    tf=float(functime['tf'])/omega_c/tUnit  # in nano seconds
    tf_i = int(functime['idx_tf'])

    functimeX   =sp.array([1.0,readBase])
    functimeY   =sp.array([(tf+ti)/2.0,tf])
    cutShortX   =sp.array([1.0,1.0])
    cutLargeX   =sp.array([readBase,readBase])
    cutShortY   =sp.array([writeBase,writeBase+readBase/2.0])
    cutLargeY   =sp.array([writeBase,writeBase+readBase])
    functimeZ   =sp.array([-1.5,-1.5])
    functimeYMid=sp.array([ti + (tf-ti)/4.0,ti+ (tf-ti)/2.0])
    # read funtional times t2, t3

    # define the grid over which the function should be plotted (xx and yy are matrices)
    xx, yy = sp.meshgrid(sp.linspace(1.0,readBase,readCnt),
                         sp.linspace(ti,tf,tf_i-ti_i))
    zz0     = cavity[0,:,ti_i:tf_i].T/cavity[:,:,ti_i:tf_i].max()
    zz1     = cavity[1,:,ti_i:tf_i].T/cavity[:,:,ti_i:tf_i].max()

#    xx, yy = sp.meshgrid(sp.linspace(1.0,readBase,readCnt),
#                         sp.linspace(time[timeCntRead/div]/tUnit,time[-1]/tUnit,timeCntRead/div))
#    zz1     = cavity[0,:,:].T/cavity[:,:,:].max()
#    zz1     = cavity[1,:,:].T/cavity[:,:,:].max()

    font = {
    'fontsize'            : 26,
    'verticalalignment'   : 'top',
    'horizontalalignment' : 'center'
    }

#    cm('font', **font)
#    rc('text', usetex=True)


    fig = plt.figure()
#    ax = fig.gca(projection='3d')
    fig0 = fig.add_subplot(121, projection='3d')
    fig0.plot_surface(xx, yy, zz0, rstride=10, cstride=5, cmap=cm.Blues, alpha=0.5,zorder=11.0,vmin=-0.25, vmax=1)
    fig0.contourf(xx, yy, zz0, zdir='z', offset=-1.5, cmap=cm.Blues,vmin=-0.25, vmax=1)
    fig0.plot(functimeX, functimeY, functimeZ,'k--',zorder=10.0) 
    fig0.plot(functimeX, functimeYMid, functimeZ,'k--',zorder=10.0) 
    fig0.plot(cutShortX, cutShortY, functimeZ,'m-',linewidth=2.5,zorder=10.0) 
    fig0.plot(cutLargeX, cutLargeY, functimeZ,'g-',linewidth=2.5,zorder=10.0) 
    fig0.set_title("a) state \"0\"", **font)
    fig0.set_xlabel("$\Delta T_{\cal F} \, / \, \\frac{T_R}{2}$", **font)
    fig0.set_ylabel("$t \, / \, \\frac{T_R}{2}$", **font)
    fig0.set_zlabel("$\left|A(t)\\right|^2 \, / \, \left|A_{max}(t)\\right|^2$", **font)
    fig0.set_zlim(-1.5, 1.0)

    fig1 = fig.add_subplot(122, projection='3d')
    fig1.plot_surface(xx, yy, zz1, rstride=10, cstride=5, cmap=cm.Reds, alpha=0.5,zorder=11.0,vmin=-0.25, vmax=1)
    fig1.contourf(xx, yy, zz1, zdir='z', offset=-1.5, cmap=cm.Reds,vmin=-0.25, vmax=1)
    fig1.plot(functimeX, functimeY, functimeZ,'k--',zorder=10.0) 
    fig1.plot(functimeX, functimeYMid, functimeZ,'k--',zorder=10.0) 
    fig1.plot(cutShortX, cutShortY, functimeZ,'m-',linewidth=2.5,zorder=10.0) 
    fig1.plot(cutLargeX, cutLargeY, functimeZ,'g-',linewidth=2.5,zorder=10.0) 
    fig1.set_title("b) state \"1\"", **font)
    fig1.set_xlabel("$\Delta T_{\cal F} \, / \, \\frac{T_R}{2}$", **font)
    fig1.set_ylabel("$t \, / \, \\frac{T_R}{2}$", **font)
    fig1.set_zlabel("$\left|A(t)\\right|^2 \, / \, \left|A_{max}(t)\\right|^2$", **font)
    fig1.set_zlim(-1.5, 1.0)


#    plt.subplot(1, 2, 1)
#    plt.pcolor(xx,yy,zz0)
#    plt.axis([xx.min(),xx.max(),yy.min(),yy.max()])
#    plt.plot(functimeX,functimeY, 'w', linewidth=2)
#    plt.plot(functimeX,functimeYMid, 'w-', linewidth=2)
#    plt.title("time bin state \"0\"")
#    plt.xlabel("$T_{functional} \, / \, \\frac{\pi}{\Omega_R[MHz]}$", **font)
#    plt.ylabel("$t \, / \, \\frac{\pi}{\Omega_R[MHz]}$", **font)

#    plt.subplot(1, 2, 2)
#    plt.pcolor(xx,yy,zz1)
#    plt.axis([xx.min(),xx.max(),ti,tf])
#    plt.plot(functimeX,functimeY, 'w', linewidth=2)
#    plt.plot(functimeX,functimeYMid, 'w-', linewidth=2)
#    plt.title("time bin sstate \"1\"")
#    plt.xlabel("$T_{functional} \, / \, \\frac{\pi}{\Omega_R[MHz]}$", **font)

#    plt.colorbar(label="$\left|A_{0,/1}(t)\\right|^2 \, / \, max(\left|A(t))\\right|^2$")

    plt.show()

  else:
    print ("option unkown: gentype="+gentype)
def main_routine (baseDir="./",configPath="./python/parameter.cfg",generationType="r"):
  print "#################################################################"
  print "#################################################################"
  print "### optimal control #############################################"
  print "### preparation of smallest overlap functional ##################"
  print "#################################################################"
  print "#################################################################"

  ### globals for functional variation
  global time, cavityRead, cavityMemo, \
         nRead, nDown, nUp, nWrite, dimH, \
         cfg, \
         h0, hc_up, hc_down, hs_up, hs_down, hsep, \
         weight_up, weight_down, sepZeroWeight, \
         normUp, normDown, normRead, \
         hole, \
         iteration

  tmpDir=baseDir+"tmp/"
  #  parser.add_argument("--cfg" ,  help="config path")
  ### check for arguments, g: generate data, r: read data ###

  ### read config file ###
  print ("load from config file: " + configPath)

  configParser = cp.ConfigParser()
  configParser.read(configPath)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)

  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  nTimeRead =int(cfg['OCTime']['{read_timecnt}'])
  dimH      =nRead + 2*nWrite

  normRead =float(cfg['OCConstraints']['{amplitude_read}']) 
  normDown =float(cfg['OCConstraints']['{amplitude_down}']) 
  normUp   =float(cfg['OCConstraints']['{amplitude_up}']) 

  name_readwrite = IOHelper.getNameReadWrite(**cfg)
  name_vector    = IOHelper.getVectorOverlap(**cfg)
  ### read config file ###


  ### prepare data with fortran ###
  cmd = "mkdir -p " + tmpDir
  print (tmpDir)
  call(cmd.split())
  replace_in_file('./python/py.parNvCenter.F95'       , tmpDir +'parNvCenter.F95',        **cfg['NVSETUP'])
  replace_in_file('./python/py.parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95', **cfg['OCFourier'])
  replace_in_file(tmpDir +'parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95',     **cfg['OCConstraints'])
  replace_in_file(tmpDir +'parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95',     **cfg['OCTime'])
  replace_in_file(tmpDir +'parSmallestOverlap.F95', tmpDir +'parSmallestOverlap.F95',     **cfg['FILES'])

  #write config file
  with open(cfg['FILES']['{prefix}']+"parameter.cfg", 'wb') as configfile:
    configParser.write(configfile)

  cmd = "mv "+tmpDir+"parSmallestOverlap.F95 "+baseDir+"srcOptCntrl/parSmallestOverlap.F95"
  call(cmd.split())
  cmd = "mv "+tmpDir+"parNvCenter.F95 "+baseDir+"srcNv/parNvCenter.F95"
  call(cmd.split())

  print ("compile fortran routines")
  cmd = "./scripts/ifort-generateHarmonics.sh " + baseDir
  call(cmd.split())

  print ("invoke " +baseDir +"generateHarmonics")

  cmd = baseDir+"generateHarmonics"
  generateHarmonics = Popen(cmd.split(), stdin=PIPE)
  cmd = "echo " + generationType
  generateInput     = Popen(cmd.split(), stdout=generateHarmonics.stdin)
  output            = generateHarmonics.communicate()[0]
  generateInput.wait()
  ### prepare data with fortran ###


  ### read data for functional variation ###
  __,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                     =IOHelper.functionaltimes_readwrite(**cfg)

  h0,hs_down,hs_up,hc_down,hc_up,hsep=IOHelper.read_MtrxOverlap(**cfg['FILES']) 
  hole                               =IOHelper.read_HoleData(**cfg['FILES']) 
  ### read data for functional variation ###


  ### functional variation ###
  print ("\nstart minimization: ")

  varMax = 20
  varStep = 1
  success = False

  #constraints for constraintWeightDown and constraintWeightUp
  funcTime  =float(time['tfunc'])
  weight_down=float(cfg ['OCConstraints']['{temporal_weight_down}'])*funcTime/2.0
  weight_up  =float(cfg ['OCConstraints']['{temporal_weight_up}'])*funcTime/2.0

  minContraints= ( {'type' : 'ineq', 'fun'  : constraintNormRead },
                   {'type' : 'eq', 'fun'  : constraintNormDown },
                   {'type' : 'eq', 'fun'  : constraintNormUp },
                   {'type' : 'eq', 'fun'  : constraintWeightDown },
                   {'type' : 'eq', 'fun'  : constraintWeightUp },
#                   {'type' : 'eq', 'fun'  : constraintRealMaxCoefficient },
                   {'type' : 'ineq', 'fun'  : constraintZeroStartDown },
                   {'type' : 'ineq', 'fun'  : constraintZeroStartUp },
                   {'type' : 'ineq', 'fun'  : constraintPartialOverlap },
                   {'type' : 'ineq', 'fun'  : constraintStoreUp },
                   {'type' : 'ineq', 'fun'  : constraintStoreDownIneq },
#
  #                 {'type' : 'ineq', 'fun'  : constraintSeperateZero },
#                   {'type' : 'eq', 'fun'  : constraintStoreDown },
#                   {'type' : 'eq', 'fun'  : constraintHoleValue },
#                   {'type' : 'eq', 'fun'  : constraintHoleSlope },
#                   {'type' : 'eq', 'fun'  : constraintHoleCurv },
                 )


  while varStep < varMax and not success :
    gamma0=initGamma0()
    x,x0  =initx(gamma0)

  #    print (" calculate sepzero to initialize vector x (method=SLSQP):")
  #    iteration=1
  #    res=minimize(seperateZeroStore, #seperateZero, # smallestAbsoluteOverlap,
  #                 x0, #res.x, 
  #                 method='SLSQP',
  #                 constraints=sepzeroContraints,
  #                 tol=cfg['OCConstraints']['{tol_sepzero}'],
  #                 options={'maxiter' : 25000, 'disp' : True},
  #                 callback=monitor
  #               )

  #    x0=res.x
  #    sepZeroWeight = res.fun

  #    funcTime  =float(time['tfunc'])
  #    weight=float(cfg ['OCConstraints']['{temporal_weight_limit}'])
  #    sepZeroWeight=weight*funcTime/2e0

    print (" calculate smallest overlap of absolute values (method=SLSQP):")
    iteration=1
    res=minimize(seperateZero, #smallestOverlapSeperateZero, # smallestOverlapSeperatePeaks, #smallestComplxOverlap, # smallestAbsoluteOverlap, # smallestOverlapSeperateZeroPartial, #
                 x0, 
                 method='SLSQP',
                 constraints=minContraints,
                 tol=cfg['OCConstraints']['{tol_classic}'],
                 options={'maxiter' : 25000, 'disp' : True},
                 callback=monitor
               )

    success=res.success
    gamma=getGamma(res.x)

    print ("")    
    print (" current norm(aplhaR) = " +str(sp.linalg.norm(gamma[     :nRead])))
    print (" current norm(aplhaD) = " +str(sp.linalg.norm(gamma[nRead:nDown])))
    print (" current norm(aplhaU) = " +str(sp.linalg.norm(gamma[nDown:nUp  ])))
    print (" current partial Olap = " +str(partialOverlap(res.x)))
#    print (" current hole(value)  = " +str(constraintHoleValue(res.x)))
#    print (" current hole(slope)  = " +str(constraintHoleSlope(res.x)))
#    print (" current hole(value)  = " +str(constraintHoleCurv(res.x)))

   
    varStep+=1

  if (success):
    print ("\ndone with minimization, succeeded:")
  else:
    print ("\ndone with minimization, no success:")

  sp.savetxt(name_vector,sp.array([gamma.real,gamma.conj().imag]).T) 
                             # [real(gamma), imag(gamma)].conj()

  cmd=baseDir+"generateOptimized"
  call(cmd.split())
def main_routine (wd="./",cfg="./python/parameter.cfg",cnt=11,delay=27.725,sptype=0,phase=0.0):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  FuncInfo      = sp.zeros([3,cnt])
  FuncInfoPhase = sp.zeros([3,cnt])
  FuncShiftRead = sp.zeros([3,cnt,functime.size],complex)

  denom    = sp.zeros([3])
#  denom[0] = cumtrapz( sp.absolute(Reg2DownRead[ti:tf])**2, x=None, dx=dt )[-1] 
#  denom[1] = cumtrapz( sp.absolute(Reg2UpRead[ti:tf])**2, x=None, dx=dt )[-1] 

  denom[0] = cumtrapz( sp.absolute(Reg2UpRead[ti:tf]+Reg2DownRead[ti:tf])**2, x=None, dx=dt )[-1] 
  denom[1] = cumtrapz( sp.real(Reg2UpRead[ti:tf]+Reg2DownRead[ti:tf]), x=None, dx=dt )[-1] 
  denom[2] = cumtrapz( sp.imag(Reg2UpRead[ti:tf]+Reg2DownRead[ti:tf]), x=None, dx=dt )[-1] 

#  denom[0] = sp.absolute[denom[0]]
#  denom[1] = sp.absolute[denom[1]]
#  denom[2] = sp.absolute[denom[2]]

  for i in sp.arange(0.0,cnt):
    myDelay = i/(cnt-1.0)*delay
    

    shift=sp.absolute(time['read'][:]-(functime[0]-myDelay)).argmin()-1
    print myDelay,functime[0],functime[0]-myDelay,shift,time['read'][shift]

    
#    FuncShiftRead[0,i,:] = Reg2DownRead[shift:shift+functime.size]
    FuncShiftRead[0,i,:] = sp.exp(-1j*phase*sp.pi)*Reg2Down[shift:shift+functime.size] + Reg2Read[shift:shift+functime.size]
    FuncShiftRead[1,i,:] = Reg2UpRead  [ti:tf]
    FuncShiftRead[2,i,:] = FuncShiftRead[0,i,:] + FuncShiftRead[1,i,:]


    FuncInfo[0,i]        = cumtrapz( sp.absolute(FuncShiftRead[2,i,:])**2, x=None, dx=dt )[-1]
    FuncInfo[0,i]       /= sp.absolute(denom[0])

    FuncInfo[1,i]        = cumtrapz( sp.real(FuncShiftRead[2,i,:]), x=None, dx=dt )[-1]
    FuncInfo[1,i]       /= sp.absolute(denom[1])

    FuncInfo[2,i]        = cumtrapz( sp.imag(FuncShiftRead[2,i,:]), x=None, dx=dt )[-1]
    FuncInfo[2,i]       /= sp.absolute(denom[2])

#    FuncInfoIntegrand    = sp.absolute(FuncSuperRead[i,:]) * sp.absolute(Reg2UpRead[ti:tf])
#    FuncInfo[i,1]        = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]/denom[1]

#    FuncInfoIntegrand    = FuncSuperRead[i,:].conj() * Reg2UpRead[ti:tf]
#    FuncInfoPhase[i,0]   = cumtrapz( FuncInfoIntegrand.real, x=None, dx=dt )[-1]/denom[1]
#    FuncInfoPhase[i,1]   = cumtrapz( FuncInfoIntegrand.imag, x=None, dx=dt )[-1]/denom[1]


  xx, yy = sp.meshgrid(functime,sp.linspace(0.0,delay,cnt))
  xx0    = sp.linspace(0.0,delay,cnt)

#  zzR    = FuncSuperRead.real/FuncSuperRead.real.max()
#  zzI    = FuncSuperRead.imag/FuncSuperRead.imag.max()
  zz0A    = sp.absolute(FuncShiftRead[0,:,:])**2/((sp.absolute(FuncShiftRead[0:1,:,:])**2).max())
  zz1A    = sp.absolute(FuncShiftRead[1,:,:])**2/((sp.absolute(FuncShiftRead[0:1,:,:])**2).max())
  zzDA    = sp.absolute(FuncShiftRead[2,:,:])**2/((sp.absolute(FuncShiftRead[0:1,:,:])**2).max())

  zmin   = -1.5
  zmax   = +1.0
  fs     = 20

  fig  = plt.figure()

  if sptype==0: # 3d plotting
    fig0 = fig.add_subplot(231, projection='3d')
    fig0.plot_surface(xx, yy, zz0A, rstride=1, cstride=5, cmap="Blues", alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
    fig0.contourf(xx, yy, zz0A, zdir='z', offset=zmin, cmap="Blues", vmin=-1, vmax=1,zorder=1.0)
    fig0.set_zlim(zmin,zmax)
    fig0.set_title("a) normalized $|A_0(t-\Delta t)|^2$",fontsize=fs)
    fig0.set_xlabel("$t$ in ns",fontsize=fs)
    fig0.set_ylabel("$\Delta t$ in ns.",fontsize=fs)

    fig1 = fig.add_subplot(232, projection='3d')
    fig1.plot_surface(xx, yy, zz1A, rstride=1, cstride=5, cmap="Reds", alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
    fig1.contourf(xx, yy, zz1A, zdir='z', offset=zmin, cmap="Reds", vmin=-1, vmax=1,zorder=1.0)
    fig1.set_zlim(zmin,zmax)
    fig1.set_title("b) normalized $|A_1(t)|^2$",fontsize=fs)
    fig1.set_xlabel("$t$ in ns",fontsize=fs)
    fig1.set_ylabel("$\Delta t$ in ns.",fontsize=fs)

    fig2 = fig.add_subplot(233, projection='3d')
    fig2.plot_surface(xx, yy, zzDA, rstride=1, cstride=5, cmap="Greens", alpha=0.5,zorder=11.0,vmin=-1, vmax=4)
    fig2.contourf(xx, yy, zzDA, zdir='z', offset=zmin, cmap="Greens", vmin=-1, vmax=4,zorder=1.0)
    fig2.set_zlim(zmin,4*zmax)
    fig2.set_title("c) normalized $|A_0(t-\Delta t)-A_1(t)|^2$",fontsize=fs)
    fig2.set_xlabel("$t$ in ns",fontsize=fs)
    fig2.set_ylabel("$\Delta t$ in ns.",fontsize=fs)
  else :
    pltId=(cnt-1)/2
    yMax = round(max(max(zzDA[0,:]),max(zzDA[pltId,:]),max(zzDA[-1,:]))) + 0.5
    yMin = min(min(zzDA[0,:]),min(zzDA[pltId,:]),min(zzDA[-1,:]))

    plt.subplot2grid((2,3),(0,0))
    plt.title("a) no delay, $\Delta t=0$",fontsize=fs)
    plt.plot(functime,zzDA[0,:],linewidth="2",color="black")
    plt.xlabel("$t$ in ns",fontsize=fs)
    plt.ylabel("$|A_0(t-\Delta t) + A_1(t)|^2$ in a.u.",fontsize=fs)
    plt.xlim(min(functime),max(functime))
    plt.ylim(yMin,yMax)
   

    plt.subplot2grid((2,3),(0,1))
    plt.title("b) medium delay, $\Delta t=\Delta t_{max}/2=$"+"{:}ns".format(pltId/(cnt-1.0)*delay),fontsize=fs)
    plt.plot(functime,zzDA[pltId,:],linewidth="2",color="black")
    plt.xlabel("$t$ in ns",fontsize=fs)
    plt.xlim(min(functime),max(functime))
    plt.ylim(yMin,yMax)
    
    plt.subplot2grid((2,3),(0,2))
    plt.title("c) maximal delay, $\Delta t=\Delta t_{max}=$"+"{:}ns".format(delay),fontsize=fs)
    plt.plot(functime,zzDA[-1,:],linewidth="2",color="black")
    plt.xlabel("$t$ in ns",fontsize=fs)
    plt.xlim(min(functime),max(functime))
    plt.ylim(yMin,yMax)


  plt.subplot2grid((2,3),(1,0))
  plt.plot(xx0,FuncInfo[1,:],linewidth="2",color="red")
  plt.title("d) area under $Re[A_0(t-\Delta t)+A_1(t)]$",fontsize=fs)
  plt.xlabel("$\Delta t$ in ns",fontsize=fs)
  plt.xlim(min(xx0),max(xx0))

  plt.subplot2grid((2,3),(1,1))
  plt.plot(xx0,FuncInfo[2,:],linewidth="2",color="magenta")
  plt.title("e) area under $Im[A_0(t-\Delta t)+A_1(t)]$",fontsize=fs)
  plt.xlabel("$\Delta t$ in ns",fontsize=fs)
  plt.xlim(min(xx0),max(xx0))

  plt.subplot2grid((2,3),(1,2))
  plt.plot(xx0,FuncInfo[0,:],linewidth="2",color="green")
  plt.title("f) area under $|A_0(t-\Delta t)+A_1(t)|^2$",fontsize=fs)
  plt.xlabel("$\Delta t$ in ns",fontsize=fs)
  plt.xlim(min(xx0),max(xx0))

#  FuncInfoPhase[:,0]-=min(FuncInfoPhase[:,0])
#  FuncInfoPhase[:,0]/=0.5*max(sp.absolute(FuncInfoPhase[:,0]))
#  FuncInfoPhase[:,0]-=1.0

#  FuncInfoPhase[:,1]-=min(FuncInfoPhase[:,1])
#  FuncInfoPhase[:,1]/=0.5*max(sp.absolute(FuncInfoPhase[:,1]))
#  FuncInfoPhase[:,1]-=1.0

#  plt.subplot2grid((2,3),(1,2),colspan=1,rowspan=1)
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,0],linewidth="2",color="red")
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,1],linewidth="2",color="magenta")
#  plt.title("f) $O_{\mathbb{C}}$ scaled & translated, $(O_{\mathbb{C}}($'$1$'$)-I_R)/I_0$",fontsize=fs)
##  plt.title("$\\frac{1}{N}\int_{T_{{\cal F}1}}^{T_{{\cal F}2}}dt\,A_0(t;\phi_0)^*\cdot A_1(t)$ scaled & translated",fontsize=fs)
#  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
#  plt.ylim(-1,1)

##  myPhase  = sp.zeros([cnt,2])
##  for i in sp.arange(0,cnt):
##    myPhase[i,0]=acos(FuncInfoPhase[i,0])/sp.pi
##    myPhase[i,1]=acos(FuncInfoPhase[i,1])/sp.pi

##  plt.subplot2grid((2,3),(1,2),colspan=1,rowspan=1)
##  plt.plot(sp.linspace(0.0,2.0,cnt),myPhase[:,0])
##  plt.plot(sp.linspace(0.0,2.0,cnt),myPhase[:,1])
#  

##  fig0.plot(memo_times[:], fitness[:,conf[pltId]], zs=tmax, zdir='y',lw=1.5, color="green")

  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",gammaCnt=11,bloch=0,myMap="custom",project=0):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  myDensity     = sp.zeros([functime.size,gammaCnt])
  FuncCavity    = sp.zeros([functime.size,gammaCnt],complex)
  spos          = sp.zeros([2,gammaCnt])
  FuncInfoOlap  = sp.zeros([2,gammaCnt],complex)

  I00  =    cumtrapz( sp.real(Reg2DownRead[ti:tf] * Reg2DownRead[ti:tf].conj()), x=None, dx=dt )[-1]
  I11  =    cumtrapz( sp.real(Reg2UpRead[ti:tf]   * Reg2UpRead[ti:tf].conj()),   x=None, dx=dt )[-1]

  for g in sp.arange(0.0,gammaCnt):
    gamma = g/(gammaCnt-1.0)   

    myDensity[:,g]=1.0-gamma
            
    spos[0,g]        = gamma
    spos[1,g]        = 1.0-gamma
    FuncCavity[:,g]  = spos[0,g]*Reg2Down[ti:tf] + spos[1,g]*Reg2Up[ti:tf]
    FuncCavity[:,g] += Reg2Read  [ti:tf]

    FuncInfoOlap [0,g]  =    cumtrapz( (FuncCavity[:,g] * Reg2DownRead[ti:tf].conj()).real, x=None, dx=dt )[-1]
    FuncInfoOlap [0,g] += 1j*cumtrapz( (FuncCavity[:,g] * Reg2DownRead[ti:tf].conj()).imag, x=None, dx=dt )[-1]
    FuncInfoOlap [0,g] /=    I00 
    FuncInfoOlap [0,g]  =    sp.absolute(FuncInfoOlap [0,g]) 

    FuncInfoOlap [1,g]  =    cumtrapz( (FuncCavity[:,g] * Reg2UpRead[ti:tf].conj()).real, x=None, dx=dt )[-1]
    FuncInfoOlap [1,g] += 1j*cumtrapz( (FuncCavity[:,g] * Reg2UpRead[ti:tf].conj()).imag, x=None, dx=dt )[-1]
    FuncInfoOlap [1,g] /=    I11       
    FuncInfoOlap [1,g]  =    sp.absolute(FuncInfoOlap [1,g]) 

#    FuncInfoOlap [0,g]  =    cumtrapz( sp.absolute(FuncCavity[:,g]) * sp.absolute(Reg2DownRead[ti:tf].conj()), x=None, dx=dt )[-1]
#    FuncInfoOlap [0,g] /=    I00 

#    FuncInfoOlap [1,g]  =    cumtrapz( sp.absolute(FuncCavity[:,g]) * sp.absolute(Reg2UpRead[ti:tf].conj()), x=None, dx=dt )[-1]
#    FuncInfoOlap [1,g] /=    I11       

  fig  = plt.figure()
  fs   = 22
  label_size = 20
  plt.rcParams['xtick.labelsize'] = label_size 
  plt.rcParams['ytick.labelsize'] = label_size 

  xx, yy = sp.meshgrid(sp.linspace(0.0,1.0,gammaCnt),functime)

  zmax      = (sp.absolute(FuncCavity)**2).max()

  c = mcolors.ColorConverter().to_rgb
  
  if myMap =="custom" :
    cm = make_colormap(
        [c('blue'), c('purple'), c('red')])
  else:
    cm       = plt.cm.get_cmap(myMap) 
    
  myColors = cm(myDensity)

  fig1 = fig.add_subplot(111, projection='3d')
  fig1.plot(spos[0,:], FuncInfoOlap [0,:].real, zs=functime[ project], zdir='y',lw=2.5, color="blue",label="$\gamma^{\prime}$",zorder=0.1)
  fig1.plot(spos[0,:], FuncInfoOlap [1,:].real, zs=functime[ project], zdir='y',lw=2.5, color="red" ,label="$\delta^{\prime}$",zorder=0.1)

  fig1.plot_surface(xx, yy, sp.absolute(FuncCavity)**2/zmax,rstride=1, cstride=1,alpha=1,facecolors=myColors, antialiased=False)
  fig1.plot_wireframe(xx, yy, sp.absolute(FuncCavity)**2/zmax, rstride=15, cstride=3,alpha=1,linewidth=1,color="black")


  fig1.legend(fontsize=fs)
  fig1.set_zlim(0,1.1)
  fig1.set_ylim(functime[0],functime[-1])
  fig1.set_xticks([0,0.5,1])
  fig1.set_yticks([55,75,95])
  fig1.set_zticks([0,0.5,1])
  fig1.set_xlim(0,1)
  fig1.set_zlabel("$|A(t)|^2$",fontsize=fs)
  fig1.set_ylabel("$t$ in ns",fontsize=fs)
  fig1.set_xlabel("$\gamma$",fontsize=fs)
  fig1.xaxis._axinfo['label']['space_factor'] = 2.0
  fig1.yaxis._axinfo['label']['space_factor'] = 2.0
  fig1.zaxis._axinfo['label']['space_factor'] = 2.0


#  m.set_array(myDensity)
#  plt.colorbar(m,shrink=0.5,aspect=7)    
    
  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",cnt=11,sptype=1,myCmap="RdYlBu"):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  FuncInfo      = sp.zeros([cnt,2])
  FuncInfoPhase = sp.zeros([cnt,2])
  FuncSuperRead = sp.zeros([cnt,functime.size],complex)

  denom    = sp.zeros([2])
  denom[0] = cumtrapz( sp.absolute(Reg2DownRead[ti:tf])**2, x=None, dx=dt )[-1] 
  denom[1] = cumtrapz( sp.absolute(Reg2UpRead[ti:tf])**2, x=None, dx=dt )[-1] 
  
  for i in sp.arange(0.0,cnt):
    phi = i*2.0/(cnt-1.0)

    Reg1Super       = superimpose(Reg1Down,Reg1Up,phi,sptype)
    Reg2Super       = superimpose(Reg2Down,Reg2Up,phi,sptype)
    Reg2SuperRead   = Reg2Super + Reg2Read

    FuncSuperRead[i,:]   = Reg2SuperRead[ti:tf]
 
    FuncInfoIntegrand    = sp.absolute(FuncSuperRead[i,:]) * sp.absolute(Reg2DownRead[ti:tf])
    FuncInfo[i,0]        = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]/denom[0]
   
    FuncInfoIntegrand    = sp.absolute(FuncSuperRead[i,:]) * sp.absolute(Reg2UpRead[ti:tf])
    FuncInfo[i,1]        = cumtrapz( FuncInfoIntegrand, x=None, dx=dt )[-1]/denom[1]

    FuncInfoIntegrand    = FuncSuperRead[i,:].conj() * Reg2UpRead[ti:tf]
    FuncInfoPhase[i,0]   = cumtrapz( FuncInfoIntegrand.real, x=None, dx=dt )[-1]/denom[1]
    FuncInfoPhase[i,1]   = cumtrapz( FuncInfoIntegrand.imag, x=None, dx=dt )[-1]/denom[1]


  xx, yy = sp.meshgrid(functime,sp.linspace(0.0,2.0,cnt))

  zzR    = FuncSuperRead.real/FuncSuperRead.real.max()
  zzI    = FuncSuperRead.imag/FuncSuperRead.imag.max()
  zzA    = sp.absolute(FuncSuperRead)**2/((sp.absolute(FuncSuperRead)**2).max())

  zmin   = -1.5
  zmax   = +1.0
  fs     = 20

  cm        = plt.cm.get_cmap(myCmap)
  myColors = cm(zzR)

  fig  = plt.figure()
  fig0 = fig.add_subplot(231, projection='3d')
  fig0.plot_surface(xx, yy, zzA, rstride=10, cstride=5, cmap=cm, alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
  fig0.contourf(xx, yy, zzA, zdir='z', offset=zmin, cmap=cm, vmin=-1, vmax=1,zorder=1.0)
  fig0.set_zlim(zmin,zmax)
  fig0.set_title("a) normalized $|A_0(t;\phi_0)|^2$",fontsize=fs)
  fig0.set_xlabel("$t$ in ns",fontsize=fs)
  fig0.set_ylabel("$\phi_0/\pi$",fontsize=fs)

  fig1 = fig.add_subplot(232, projection='3d')
  fig1.plot_surface(xx, yy, zzR, rstride=10, cstride=5, cmap=cm, alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
  fig1.contourf(xx, yy, zzR, zdir='z', offset=zmin, cmap=cm, vmin=-1, vmax=1,zorder=1.0)
  fig1.set_zlim(zmin,zmax)
  fig1.set_title("b) normalized $Re[\,A_0(t;\phi_0)\,]$",fontsize=fs)
  fig1.set_xlabel("$t$ in ns",fontsize=fs)
  fig1.set_ylabel("$\phi_0/\pi$",fontsize=fs)

  fig2 = fig.add_subplot(233, projection='3d')
  fig2.plot_surface(xx, yy, zzI, rstride=10, cstride=5, cmap=cm, alpha=0.5,zorder=11.0,vmin=-1, vmax=1)
  fig2.contourf(xx, yy, zzI, zdir='z', offset=zmin, cmap=cm, vmin=-1, vmax=1,zorder=1.0)
  fig2.set_zlim(zmin,zmax)
  fig2.set_title("c) normalized $Im[\,A_0(t;\phi_0)\,]$",fontsize=fs)
  fig2.set_xlabel("$t$ in ns",fontsize=fs)
  fig2.set_ylabel("$\phi_0/\pi$",fontsize=fs)

  plt.subplot2grid((2,3),(1,0),colspan=1,rowspan=1)
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfo[:,0],label="overlap with $i=$'$0$'",linewidth="2",color="blue")
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfo[:,1],label="overlap with $i=$'$1$'",linewidth="2",color="red")
  plt.ylim(0,1.1)
  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
  plt.legend(bbox_to_anchor=(0.52, 0.0), loc=3, borderaxespad=0.)
  plt.title("d) classical overlap, $O_{\mathbb{R}}(i)$",fontsize=fs)
#  plt.title("$\\frac{1}{N}\int_{T_{{\cal F}1}}^{T_{{\cal F}2}}dt\,|A_0(t;\phi_0)|\cdot|A_i(t)|$",fontsize=fs)

#  FuncInfoPhase[:,0]-=min(FuncInfoPhase[:,0])
#  FuncInfoPhase[:,0]/=0.5*max(sp.absolute(FuncInfoPhase[:,0]))
#  FuncInfoPhase[:,0]-=1.0

#  FuncInfoPhase[:,1]-=min(FuncInfoPhase[:,1])
#  FuncInfoPhase[:,1]/=0.5*max(sp.absolute(FuncInfoPhase[:,1]))
#  FuncInfoPhase[:,1]-=1.0

  plt.subplot2grid((2,3),(1,1),colspan=1,rowspan=1)
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,0],label="Re[ $O_{\mathbb{C}}($'$1$'$)$ ]",linewidth="2",color="red")
  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,1],label="Im[ $O_{\mathbb{C}}($'$1$'$)$ ]",linewidth="2",color="magenta")
  plt.title("e) complex overlap, $O_{\mathbb{C}}($'$1$'$)$",fontsize=fs)
#  plt.title("$\\frac{1}{N}\int_{T_{{\cal F}1}}^{T_{{\cal F}2}}dt\,A_0(t;\phi_0)^*\cdot A_1(t)$",fontsize=fs)
  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
  plt.legend(bbox_to_anchor=(0.66, 0.0), loc=3, borderaxespad=0.)
  plt.ylim(-1,1.1)

  FuncInfoPhase[:,0]-=min(FuncInfoPhase[:,0])
  FuncInfoPhase[:,0]/=0.5*max(sp.absolute(FuncInfoPhase[:,0]))
  FuncInfoPhase[:,0]-=1.0

  FuncInfoPhase[:,1]-=min(FuncInfoPhase[:,1])
  FuncInfoPhase[:,1]/=0.5*max(sp.absolute(FuncInfoPhase[:,1]))
  FuncInfoPhase[:,1]-=1.0

#  plt.subplot2grid((2,3),(1,2),colspan=1,rowspan=1)
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,0],linewidth="2",color="red")
#  plt.plot(sp.linspace(0.0,2.0,cnt),FuncInfoPhase[:,1],linewidth="2",color="magenta")
#  plt.title("f) $O_{\mathbb{C}}$ scaled & translated, $(O_{\mathbb{C}}($'$1$'$)-I_R)/I_0$",fontsize=fs)
#  plt.xlabel("$\phi_0/\pi$",fontsize=fs)
#  plt.ylim(-1,1)


  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",generationType="p",\
                  toMinimize =2,\
                  cavityMatch=1,\
                  silent=0,\
                  useBeta=0,\
                  cutoff=10000,dimGrid=11,id0=0,id1=1,id2=2,pltId='funval',pltLim=1000,pltBins=40,myCmap="brg"):
  print "#################################################################"
  print "#################################################################"
  print "### optimal control #############################################"
  print "### memory pulse evaluation #####################################"
  print "#################################################################"
  print "#################################################################"

  ### globals for functional variation
  global cons, fun, dim, conf

  conf['toMinimize'] =toMinimize
  conf['cavityMatch']=cavityMatch
  conf['silent']     =silent
  if (useBeta == 0):
    conf['useBeta']    = False
  else:
    conf['useBeta']    = True

  conf['id0']        =id0
  conf['id1']        =id1
  conf['id2']        =id2
  conf['cutoff']     =cutoff

  ### globals for functional variation

  ### generate working environment ###
  print ("### working directory: " + wd)
  tmpDir = wd+"tmp/"  
  cmd = "mkdir -p " + tmpDir
  call(cmd.split())
  ### generate working environment ###

  ### read config file ###
  print ("### load config file: " + cfg)
  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  conf['MEConstraints'] = cfg['MEConstraints'].copy()
  conf['FITNESS']=  cfg['FITNESS'].copy()
  conf['FITNESS']['{mutationrate}']=sp.zeros([conf['entries']])
  conf['FITNESS']['{mutationrate}'][conf['funval']]       =cfg['FITNESS']['{mut_functional}']
  conf['FITNESS']['{mutationrate}'][conf['fidelity_down']]=cfg['FITNESS']['{mut_fidelity_down}']
  conf['FITNESS']['{mutationrate}'][conf['fidelity_up']]  =cfg['FITNESS']['{mut_fidelity_up}']
  conf['FITNESS']['{mutationrate}'][conf['memolap']]      =cfg['FITNESS']['{mut_memolap}']
  conf['FITNESS']['{mutationrate}'][conf['alpha']]        =cfg['FITNESS']['{mut_alpha}']
  conf['FITNESS']['{mutationrate}'][conf['beta']]         =cfg['FITNESS']['{mut_beta}']
  conf['FITNESS']['{mutationrate}'][conf['success']]      =cfg['FITNESS']['{mut_success}']

  cons['alpha_norm']=float(cfg['MEConstraints']["{storage_amplitude}"])
  cons['beta_low']  =float(cfg['MEConstraints']["{limit_low_beta}"])
  cons['beta_top']  =float(cfg['MEConstraints']["{limit_top_beta}"])
  cons['chi2_Tol']  =float(cfg['MEConstraints']['{tol_chi2}'])

  dim['alpha']=int(cfg['MEFourier']['{storage_harmonic}'])
  dim['total']=dim['alpha']+3

  prefix        =cfg['FILES']['{prefix}']
  postfix       =cfg['FILES']['{postfix}']
  name_optimized=cfg['FILES']['{name_optimized}']

  name_spin     =cfg['FILES']['{name_spin}']
  name_cavity   =cfg['FILES']['{name_cavity}']

  cfg['dim_grid']    =dimGrid
  name_readwrite=IOHelper.getNameReadWrite(**cfg) 
  name_storage  =IOHelper.getNameStorage  (**cfg) 
  name_varinit  =IOHelper.getNameInitialVariation (**cfg)

  myTime        =IOHelper.functionaltimes_readwrite(**cfg) # reads time and updates cfg: 
                                                           #   cfg['METime']['{fidelity_ti}'] = myTime['idx_ti']
                                                           #   cfg['METime']['{fidelity_tf}'] = myTime['idx_tf']


  gridPhi    =sp.linspace(0.0, 2.0*sp.pi, num=2*dimGrid-1)
  gridTheta  =sp.linspace(0.0, sp.pi, num=dimGrid)
  minfun     =sp.zeros([len(gridPhi),len(gridTheta),conf['entries']+3])

  if (generationType == "p"):
    print "## read from file: " + name_varinit
    raw = sp.loadtxt(name_varinit)
    minfun  = raw.reshape(len(gridPhi),len(gridTheta),conf['entries']+3)
    for i in sp.arange(0,len(gridPhi),1):
      for j in sp.arange(0,len(gridTheta),1):
        minfun[i,j,conf['fitness']] = MemoryPulseFunctional.fitnessFunction(minfun[i,j,:])

  else:
    ### prepare and complie fortran routines ###
    print ("### prepare fortran routines")
    replace_in_file('./python/py.parNvCenter.F95'   , tmpDir +'parNvCenter.F95'   , **cfg['NVSETUP'])
    replace_in_file('./python/py.parMemoryPulse.F95', tmpDir +'parMemoryPulse.F95', **cfg['MEFourier'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['OCFourier'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['MESpin'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['MEConstraints'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['OCConstraints'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['METime'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['OCTime'])
    replace_in_file(tmpDir +'parMemoryPulse.F95'    , tmpDir +'parMemoryPulse.F95', **cfg['FILES'])

    #write config file
    with open(prefix+"parameter.cfg", 'wb') as configfile:
      configParser.write(configfile)
    ### read config file ###

    print ("### compile fortran routines")
    cmd = "mv "+tmpDir+"parMemoryPulse.F95 "+wd+"srcOptCntrl/parMemoryPulse.F95"
    call(cmd.split())
    cmd = "mv "+tmpDir+"parNvCenter.F95 "+wd+"srcNv/parNvCenter.F95"
    call(cmd.split())

    cmd = "./scripts/ifort-memoryHarmonics.sh " + wd
    call(cmd.split())

    print ("### invoke  fortran routines")
    print ("### generation Type: " + generationType)
    cmd = wd+"memoryHarmonics"                                             # location of executable fortran program
    generateHarmonics = Popen(cmd.split(), stdin=PIPE)                     # run fortran program with piped standard input
    cmd = "echo " + generationType                                         # communication with fortran-routine: chose action -> read or generate
    generateInput     = Popen(cmd.split(), stdout=generateHarmonics.stdin) # send action to fortran program
    output            = generateHarmonics.communicate()[0]
    generateInput.wait()
    ### prepare and complie fortran routines ###

    ### read data for functional variation ###
    cons['cavityT2_down'], \
    cons['cavityT2_up']    = IOHelper.read_CavityMemory (**cfg['FILES'])

    fun ['mtrxBeta_up'],   \
    cons['vecT2_up']   ,   \
    cons['fidelity_up'],   \
    cons['mtrxMemOlap']    = IOHelper.read_MtrxMemory("up",  **cfg['FILES']) 

    fun ['mtrxBeta_down'], \
    cons['vecT2_down']   , \
    cons['fidelity_down'], \
    __                     = IOHelper.read_MtrxMemory("down",  **cfg['FILES']) 
    ### read data for functional variation ###

    ### functional variation ###
    print ("\n### start minimization: ")
    print ("### on initial "+ str(sp.shape(minfun)[0])+"x"+str(sp.shape(minfun)[1])  + "-grid (phi,theta) on sphere")

    mincnt=0
    cntPhi  =0
    t0=0
    tcnt=len(gridTheta)

    for phi in gridPhi[0:len(gridPhi)-1]: 
      theta_i=0
      if(cntPhi > 0):
        t0=1
        tcnt=len(gridTheta)-1
        theta_i=1

      ### parallel evaluation with <cpu_count()> cores ###################################
      pool    = multiprocessing.Pool(processes=multiprocessing.cpu_count())

      results = [ pool.apply_async(evaluateSphericalVariation, args=(phi,theta,cntPhi,cntTheta))
                 for theta,cntTheta in zip(gridTheta[t0:tcnt],sp.arange(t0,tcnt,1)) ]

      for p in results:
        myResult,i,j =p.get()
        minfun[i,j,:]=myResult

      #kill multiprocessing pool !!!
      pool.terminate()
      ### parallel evaluation with <cpu_count()> cores ###################################


      ### sequentiell evaluateion 1 core #################################################
#      for theta in gridTheta[t0:tcnt]:
#        minfun[cntPhi,theta_i,:],__,__=MemoryPulseFunctional.evaluateSphericalVariation (phi,theta,cntPhi,theta_i)
#        theta_i+=1
      ### sequentiell evaluateion 1 core #################################################

      cntPhi=cntPhi+1
  #  end for phi

    minfun[ :, 0,:]=minfun[0, 0,:] # theta=0  : same vector on unit-sphere
    minfun[ :,-1,:]=minfun[0,-1,:] # theta=pi : same vector on unit-sphere
    minfun[-1, :,:]=minfun[0, :,:] # periodic

    print "\n### write to file: " + name_varinit
    sp.savetxt(name_varinit,minfun.reshape((len(gridPhi)*len(gridTheta),conf['entries']+3)),\
       header=' alpha0['+str(id0)+']; alpha0['+str(id1)+']; alpha0['+str(id2)+'];'\
             +' fitness; success; norm[alpha]; abs[beta]; memolap; fidelity_up; fidelity_down; minfun') 

  print "#################################################################"
  print "#################################################################"


  font = {
  'fontsize'            : 26,
  }

  mytitle=MemoryPulseFunctional.getName(pltId)

  ### prepare surface_plot ###############################################################
  x = outer(cos(gridPhi), sin(gridTheta))
  y = outer(sin(gridPhi), sin(gridTheta))
  z = outer(ones(size(gridPhi)), cos(gridTheta))

  myDensity=sp.zeros([len(gridPhi),len(gridTheta)])
  for i in sp.arange(0,len(gridPhi),1):
    for j in sp.arange(0,len(gridTheta),1):
      if (minfun[i,j,conf[pltId]] >= pltLim):
        myDensity[i,j] = pltLim+1
      else:
        myDensity[i,j] = minfun[i,j,conf[pltId]]

      
  # "afmhot", "hot", "terrain", "brg"
  cm       = plt.cm.get_cmap(myCmap) 
  myColors = cm(myDensity/pltLim)
  ### prepare surface_plot ###############################################################

  ### prepare colormap ###################################################################
  fig0_colors=sp.linspace(0,pltLim,pltBins)
  ### prepare colormap ###################################################################

  ### prepare histogram ##################################################################
  yHist,xHist = sp.histogram(myDensity.flatten(),pltBins)
#  xSpan = pltxHist.max()-xHist.min()
#  Color = [cm(((ix-xHist.min())/xSpan)) for ix in xHist]

  Color = [cm(((ix)/pltLim)) for ix in xHist]
  ### prepare histogram ##################################################################

  ### calculate fittest solutions ########################################################
  cntFit = 0

  for i in sp.arange(0,len(gridPhi),1):
    for j in sp.arange(0,len(gridTheta),1):

      if minfun[i,j,conf['fitness']] != 0.0 :
        cntFit+=1
      
      if (minfun[i,j,conf[pltId]] >= pltLim):
        myDensity[i,j] = pltLim
      else:
        myDensity[i,j] = minfun[i,j,conf[pltId]]
      
  if (cntFit > 0):
    fitAlpha =sp.zeros([cntFit,int(cfg['MEFourier']['{storage_harmonic}'])])  

    cntFit = 0
  
    for i in sp.arange(0,len(gridPhi),1):
      for j in sp.arange(0,len(gridTheta),1):
        if minfun[i,j,conf['fitness']] != 0.0 :
          print minfun[i,j,3:]
  
          fitAlpha[cntFit,conf['id0']]=minfun[i,j,0]
          fitAlpha[cntFit,conf['id1']]=minfun[i,j,1]
          fitAlpha[cntFit,conf['id2']]=minfun[i,j,2]

          cntFit+=1

    name_fittest=IOHelper.getNameInitialFittest(**cfg)
    print "\n### write fittest to file: " + name_fittest
    sp.savetxt(name_fittest,fitAlpha,\
       header='# alpha0[0] ... alpha0[n]') 

  print "### fitness counter: {0:} of {1:}".format(cntFit,sp.shape(minfun)[0]*sp.shape(minfun)[1])
  ### calculate fittest solutions ########################################################


  fig = plt.figure()


  ### plot surface_plot ##################################################################
  fig3D = fig.add_subplot(131, projection='3d')
  surf  = fig3D.plot_surface(x, y, z, rstride=1, cstride=1,facecolors=myColors)
  fig3D.plot(cos(gridPhi), sin(gridPhi), zs=0, zdir='z',lw=0.5, color="black")
  fig3D.plot(cos(gridPhi), sin(gridPhi), zs=0, zdir='x',lw=0.5, color="black")
  fig3D.set_xlabel("$\\alpha_{:}$".format(id0), **font)
  fig3D.set_ylabel("$\\alpha_{:}$".format(id1), **font)
  fig3D.set_zlabel("$\\alpha_{:}$".format(id2), **font)
  fig3D.set_title("a) 4d-plot of "+mytitle, fontsize = 20)
  ### plot surface_plot ##################################################################


  ### plot colormap ######################################################################
  fig0 = fig.add_subplot(132)
  fig0.invert_yaxis()
  cp0=fig0.contourf(gridPhi/sp.pi,gridTheta/sp.pi,minfun[:,:,conf[pltId]].T,fig0_colors,cmap=cm)
  plt.colorbar(cp0)
  fig0.set_xlabel("$\phi/\pi$", **font)
  fig0.set_ylabel("$\\theta/\pi$", **font)
  fig0.set_title("b) map of "+mytitle, fontsize = 20)
  ### plot colormap ######################################################################


  ### plot histogram #####################################################################
  figBar=fig.add_subplot(133)
  figBar.bar(xHist[:-1],yHist,color=Color,width=xHist[1]-xHist[0])
  figBar.set_xlim([0,pltLim])
  figBar.set_ylim([0,max(yHist[0:len(yHist)-1])])
  figBar.set_xlabel(mytitle, fontsize=20)
  figBar.set_ylabel("count", fontsize=20)
  figBar.set_title("c) histogram", fontsize = 20)
  ### plot histogram #####################################################################

  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",thetaCnt=11,phiCnt=11,p3d=0,myMap="rainbow"):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf] 
  dt                = float(time['delta_t'])

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]     # /float(cfg['OCConstraints']['{amplitude_up}'])
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown] # /float(cfg['OCConstraints']['{amplitude_down}'])
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]   # /float(cfg['OCConstraints']['{amplitude_read}'])
  ### read data ###

  ### plotting
  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)

  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  Reg2DownRead    = Reg2Down  + Reg2Read
  Reg2UpRead      = Reg2Up    + Reg2Read

  FuncInfoOlap  = sp.zeros([2,thetaCnt,phiCnt],complex)

  I00  =    cumtrapz( (Reg2Down[ti:tf].conj() * Reg2Down[ti:tf]).real, x=None, dx=dt )[-1]
  I0R  = 1j*cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Down[ti:tf]).imag, x=None, dx=dt )[-1]
  I0R +=    cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Down[ti:tf]).real, x=None, dx=dt )[-1]

  I11  =    cumtrapz( (Reg2Up  [ti:tf].conj() * Reg2Up  [ti:tf]).real, x=None, dx=dt )[-1]
  I1R  = 1j*cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Up  [ti:tf]).imag, x=None, dx=dt )[-1]
  I1R +=    cumtrapz( (Reg2Read[ti:tf].conj() * Reg2Up  [ti:tf]).real, x=None, dx=dt )[-1]

  fs     = 20

  for i in sp.arange(0.0,thetaCnt):
    theta = i/(thetaCnt-1.0)   # from 0 to 1 * pi
    
    for j in sp.arange(0.0,phiCnt):
      phi = j/(phiCnt-1.0)*2.0 # from 0 to 2 * pi
      
      FuncCavity     = sp.cos(theta*sp.pi)*Reg2Down[ti:tf] + sp.sin(theta*sp.pi)*sp.exp(-1j*phi*sp.pi)*Reg2Up[ti:tf]
      FuncCavity[:] += Reg2Read  [ti:tf]

#      plt.title("state $\\theat={0:}$, $\\phi={1:}$".format(theta,phi),fontsize=fs)
#      plt.plot(time['read'][ti:tf],sp.absolute(FuncCavity)**2,color="green",linewidth=2)
#      plt.plot(time['read'][ti:tf],sp.absolute(Reg2DownRead[ti:tf])**2,color="blue",linewidth=2)
#      plt.plot(time['read'][ti:tf],sp.absolute(Reg2UpRead[ti:tf])**2,color="red",linewidth=2)
#      plt.ylabel("$A(t)$",fontsize=fs)
#      plt.xlim([time['read'][ti],time['read'][tf]])
#      plt.show()

      FuncInfoOlap [0,i,j]  =    cumtrapz( (FuncCavity[:].conj() * Reg2Down[ti:tf]).real, x=None, dx=dt )[-1]
      FuncInfoOlap [0,i,j] += 1j*cumtrapz( (FuncCavity[:].conj() * Reg2Down[ti:tf]).imag, x=None, dx=dt )[-1]
      FuncInfoOlap [0,i,j]  =    (FuncInfoOlap [0,i,j]-I0R)/I00

      FuncInfoOlap [1,i,j]  =    cumtrapz( (FuncCavity[:].conj() * Reg2Up[ti:tf]).real, x=None, dx=dt )[-1]
      FuncInfoOlap [1,i,j] += 1j*cumtrapz( (FuncCavity[:].conj() * Reg2Up[ti:tf]).imag, x=None, dx=dt )[-1]
      FuncInfoOlap [1,i,j]  =    (FuncInfoOlap [1,i,j]-I1R)/I11

  xx, yy = sp.meshgrid(sp.linspace(0.0,2.0,phiCnt),sp.linspace(0.0,1.0,thetaCnt))

  zmin   = 0.0
  zmax   = +1.0

  zzOlapR0 = FuncInfoOlap [0,:,:].real
  zzOlapI0 = FuncInfoOlap [0,:,:].imag
  print zzOlapI0  

  zzOlapR1 = FuncInfoOlap [1,:,:].real
  zzOlapI1 = FuncInfoOlap [1,:,:].imag

  fig  = plt.figure()

  fig1 = fig.add_subplot(221, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapR0, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR0.min(), vmax=zzOlapR0.max())
  fig1.set_zlim(-1,1)
  fig1.set_title("a) Re$[(\\tilde O($\"$0$\"$)-\\tilde {\cal I}_{0R})/\\tilde {\cal I}_{00}]\\approx\cos(\\theta)$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi / \pi$",fontsize=fs)

  fig1 = fig.add_subplot(223, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapI0, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI0.min(), vmax=zzOlapI0.max())
  fig1.set_zlim(-0.01,0.01)
  fig1.set_title("c) Im$[(\\tilde O($\"$0$\"$)-\\tilde {\cal I}_{0R})/\\tilde {\cal I}_{00}]\\approx0$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi/\pi$",fontsize=fs)

  fig1 = fig.add_subplot(222, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapR1, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapR1.min(), vmax=zzOlapR1.max())
  fig1.set_zlim(-1,1)
  fig1.set_title("b) Re$[(\\tilde O($\"$1$\"$)-\\tilde {\cal I}_{1R})/\\tilde {\cal I}_{11}]\\approx\sin(\\theta)\cdot\cos(\phi)$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi / \pi$",fontsize=fs)

  fig1 = fig.add_subplot(224, projection='3d')
  fig1.plot_surface(xx, yy, zzOlapI1, rstride=5, cstride=5, cmap=myMap, alpha=0.5,zorder=11.0,vmin=zzOlapI1.min(), vmax=zzOlapI1.max())
  fig1.set_zlim(-1,1)
#  fig1.set_title("a) Re$[(O_{\mathbb{C}}("0")-\\tilde {\¢al I}_{0R})/\\tilde {\¢al I}_{00}]$",fontsize=fs)
  fig1.set_title("d) Im$[(\\tilde O($\"$1$\"$)-\\tilde {\cal I}_{1R})/\\tilde {\cal I}_{11}]\\approx\sin(\\theta)\cdot\sin(\phi)$",fontsize=fs)
  fig1.set_ylabel("$\\theta/\pi$",fontsize=fs)
  fig1.set_xlabel("$\phi/\pi$",fontsize=fs)

  plt.show()
def main_routine (wd="./",cfg="./python/parameter.cfg",start=-1,cut1=1000.0,cut2=1000.0,cut3=1000.0,stop=-1,test=0,plotType=0,impose=0,par1=0.0,par2=0.0):

  ### read config file ###
  print ("load from config file: " + cfg)

  configParser = cp.ConfigParser()
  configParser.read(cfg)
  print (configParser.sections())
  cfg=configParser.__dict__['_sections'].copy() 

  #for src, target in cfg['NVSETUP'].items():
  #  print(src + " : " + target)
  omega_c     = float(cfg['NVSETUP']['{omega_c}'])

  nWrite=int(cfg['OCFourier']['{write_harmonic}'])
  nRead =int(cfg['OCFourier']['{read_harmonic}'])
  nStore=int(cfg['MEFourier']['{storage_harmonic}'])

  nDown =nRead+nWrite
  nUp   =nDown+nWrite
  ### read config file ###

  ### read data ###  
  cavityWrite,cavityMemo,cavityRead =IOHelper.harmonics_readwrite(**cfg)
  time                              =IOHelper.functionaltimes_readwrite(**cfg)

  time['write'][:] *= 1e9
  time['read'][:] *= 1e9
  ti                = int(time['idx_ti'])
  tf                = int(time['idx_tf'])
  functime          = time['read'][ti:tf]

  filename       =IOHelper.getVectorOverlap(**cfg)
  reGamma,imGamma=sp.loadtxt(filename).T 
  alphaR         =reGamma[0:nRead]    -1j*imGamma[0:nRead]
  alphaD         =reGamma[nRead:nDown]-1j*imGamma[nRead:nDown]
  alphaU         =reGamma[nDown:nUp]  -1j*imGamma[nDown:nUp]
  ### read data ###

  ### plotting
  Reg1Down        = sp.dot(alphaD.conj(),cavityWrite)
  Reg2Down        = sp.dot(alphaD.conj(),cavityMemo)
  Reg2DownRead    = Reg2Down + sp.dot(alphaR.conj(),cavityRead)

  Reg1Up          = sp.dot(alphaU.conj(),cavityWrite)
  Reg2Up          = sp.dot(alphaU.conj(),cavityMemo)
  Reg2UpRead      = Reg2Up + sp.dot(alphaR.conj(),cavityRead)

  Reg1Super       = superimpose(Reg1Down,Reg1Up,par1,par2)
  Reg2Super       = superimpose(Reg2Down,Reg2Up,par1,par2)
  Reg2SuperRead   = Reg2Super + sp.dot(alphaR.conj(),cavityRead)

  Reg2Read        = sp.dot(alphaR.conj(),cavityRead)

  minT = min(functime) # min(time['read'])
  maxT = max(functime) # min(time['read'])

  minYComplete = -0.6
  maxYComplete =  0.6

  minYInfo = -0.6
  maxYInfo =  0.4

  minYRead = -0.4
  maxYRead =  0.6

  fs = 25

  plt.subplot(5,3,1)
  plt.title("state '0'",fontsize=fs)
  plt.plot(time['read'],Reg2DownRead.real,color="blue",linewidth=2)
  plt.plot(time['read'],Reg2DownRead.imag,color="lightblue",linewidth=2)
  plt.ylabel("$A(t)$",fontsize=fs)
  plt.ylim([minYComplete,maxYComplete])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,2)
  plt.title("state '1'",fontsize=fs)
  plt.plot(time['read'],Reg2UpRead.real,color="red",linewidth=2)
  plt.plot(time['read'],Reg2UpRead.imag,color="orange",linewidth=2)
  plt.ylim([minYComplete,maxYComplete])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,3)
  plt.title("phaseshift $\phi_0=${:}$\pi$".format(par1),fontsize=fs)
  plt.plot(time['read'],Reg2SuperRead.real,color="green",linewidth=2)
  plt.plot(time['read'],Reg2SuperRead.imag,color="lightgreen",linewidth=2)
  plt.ylim([minYComplete,maxYComplete])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,4)
  plt.plot(time['read'],sp.absolute(Reg2DownRead)**2,color="blue",linewidth=2)
  plt.ylabel("$|A(t)|^2$",fontsize=fs)
  plt.ylim([0,(max(sp.absolute(minYComplete),sp.absolute(maxYComplete)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,5)
  plt.plot(time['read'],sp.absolute(Reg2UpRead)**2,color="red",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYComplete),sp.absolute(maxYComplete)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,6)
  plt.plot(time['read'],sp.absolute(Reg2SuperRead)**2,color="green",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYComplete),sp.absolute(maxYComplete)))])
  plt.xlim([minT,maxT])


  plt.subplot(5,3,7)
  plt.plot(time['read'],Reg2Down.real,color="blue",linewidth=2)
  plt.plot(time['read'],Reg2Down.imag,color="lightblue",linewidth=2)
  plt.ylabel("$\\tilde{A}(t)$",fontsize=fs)
  plt.ylim([minYInfo,maxYInfo])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,8)
  plt.plot(time['read'],Reg2Up.real,color="red",linewidth=2)
  plt.plot(time['read'],Reg2Up.imag,color="orange",linewidth=2)
  plt.ylim([minYInfo,maxYInfo])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,9)
  plt.plot(time['read'],Reg2Super.real,color="green",linewidth=2)
  plt.plot(time['read'],Reg2Super.imag,color="lightgreen",linewidth=2)
  plt.ylim([minYInfo,maxYInfo])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,10)
  plt.plot(time['read'],sp.absolute(Reg2Down)**2,color="blue",linewidth=2)
  plt.ylabel("$|\\tilde{A}(t)|^2$",fontsize=fs)
  plt.ylim([0,(max(sp.absolute(minYInfo),sp.absolute(maxYInfo)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,11)
  plt.plot(time['read'],sp.absolute(Reg2Up)**2,color="red",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYInfo),sp.absolute(maxYInfo)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,12)
  plt.plot(time['read'],sp.absolute(Reg2Super)**2,color="green",linewidth=2)
  plt.ylim([0,(max(sp.absolute(minYInfo),sp.absolute(maxYInfo)))])
  plt.xlim([minT,maxT])

  plt.subplot(5,3,13)
  plt.plot(time['read'],Reg2Read.real,linewidth=2,color="black")
  plt.plot(time['read'],Reg2Read.imag,linewidth=2,color="darkgray")
  plt.ylim([minYRead,maxYRead])
  plt.xlim([minT,maxT])
  plt.ylabel("$\\tilde{A}_R(t)$",fontsize=fs)
  plt.xlabel("$t$ in ns",fontsize=fs)

  plt.subplot(5,3,14)
  plt.plot(time['read'],Reg2Read.real,linewidth=2,color="black")
  plt.plot(time['read'],Reg2Read.imag,linewidth=2,color="darkgray")
  plt.ylim([minYRead,maxYRead])
  plt.xlim([minT,maxT])
  plt.xlabel("$t$ in ns",fontsize=fs)

  plt.subplot(5,3,15)
  plt.plot(time['read'],Reg2Read.real,linewidth=2,color="black")
  plt.plot(time['read'],Reg2Read.imag,linewidth=2,color="darkgray")
  plt.ylim([minYRead,maxYRead])
  plt.xlim([minT,maxT])
  plt.xlabel("$t$ in ns",fontsize=fs)

#  plt.subplot(4,3,5)
#  plt.plot(functime,ReadUpReg2[ti:tf].imag,color="darkgray",linewidth=2)
#  plt.plot(functime,cavityUpReg3[ti:tf].imag,color="red",linewidth=2)
#  plt.xlim([min(functime),max(functime)])

#  plt.subplot(4,3,3)
#  if (impose != 1):
#    plt.title("$\\alpha_{S}$")
#    plt.bar(sp.arange(1,nStore+1,1),alphaS.real,color="green")
#  else :
#    plt.title("superposition, $A(t)$")
#    plt.plot(functime,ReadSuperReg2[ti:tf].real,color="darkgray",linewidth=2)
#    plt.plot(functime,cavitySuperReg3[ti:tf].real,color="green",linewidth=2)
#    plt.xlim([min(functime),max(functime)])

#  plt.subplot(4,3,6)
#  if (impose != 1):
#    plt.bar(sp.arange(1,nStore+1,1),alphaS.imag,color="green")
#  else :
#    plt.plot(functime,ReadSuperReg2[ti:tf].imag,color="darkgray",linewidth=2)
#    plt.plot(functime,cavitySuperReg3[ti:tf].imag,color="green",linewidth=2)
#    plt.xlim([min(functime),max(functime)])


#  plt.subplot2grid((4,3),(2,0),colspan=3,rowspan=2)

#  cavityCheckReg1,cavityCheckReg2,cavityCheckReg3 = pltFunction(cavityCheckReg1,cavityCheckReg2,cavityCheckReg3,plotType)
#  cavitySuperReg1,cavitySuperReg2,cavitySuperReg3 = pltFunction(cavitySuperReg1,cavitySuperReg2,cavitySuperReg3,plotType)
#  cavityDownReg1, cavityDownReg2, cavityDownReg3  = pltFunction(cavityDownReg1, cavityDownReg2, cavityDownReg3, plotType)
#  cavityUpReg1,   cavityUpReg2,   cavityUpReg3    = pltFunction(cavityUpReg1,   cavityUpReg2,   cavityUpReg3,   plotType)

#  if (test==1):
#    print ("### compile fortran routines")
#    cmd = "./scripts/ifort-memoryHarmonics.sh " + wd
#    call(cmd.split())

#    print ("### call memoryOptimized")
#    cmd=wd+"memoryOptimized"
#    call(cmd.split())

#    print ("### call memorySuperimposed")
#    cmd=wd+"memorySuperimposed"
#    generateSuperposition = Popen(cmd.split(), stdin=PIPE)                     # run fortran program with piped standard input
#    cmd = "echo {:}".format(par1)                                              # communication with fortran-routine: chose superposition parameter
#    generateInput     = Popen(cmd.split(), stdout=generateSuperposition.stdin) # send action to fortran program
#    output            = generateSuperposition.communicate()[0]
#    generateInput.wait()

#    filename = cfg['FILES']['{prefix}']+cfg['FILES']['{name_readwrite}']+\
#               cfg['FILES']['{name_storage}']+cfg['FILES']['{name_optimized}']

#    mytimeU,__,A_Re_U,A_Im_U = sp.loadtxt(filename+"cavity_up_stored"   +cfg['FILES']['{postfix}']).T
#    mytimeD,__,A_Re_D,A_Im_D = sp.loadtxt(filename+"cavity_down_stored" +cfg['FILES']['{postfix}']).T
#    mytimeS,__,A_Re_S,A_Im_S = sp.loadtxt(filename+"cavity_super_stored"+cfg['FILES']['{postfix}']).T

#    cavityMode_U,cavityMode_D,cavityMode_S = pltFunction(A_Re_U+1j*A_Im_U, A_Re_D+1j*A_Im_D, A_Re_S+1j*A_Im_S,plotType)

#  cavityMaxDown = max(max(cavityDownReg1),max(cavityDownReg2),max(cavityDownReg3))
#  cavityMaxUp   = max(max(cavityUpReg1),max(cavityUpReg2),max(cavityUpReg3))
#  cavityMaxSuper= max(max(cavitySuperReg1),max(cavitySuperReg2),max(cavitySuperReg3))
#  cavityMax     = max(cavityMaxDown,cavityMaxUp,cavityMaxSuper)

#  cavityMinDown = min(min(cavityDownReg1),min(cavityDownReg2),min(cavityDownReg3))
#  cavityMinUp   = min(min(cavityUpReg1),min(cavityUpReg2),min(cavityUpReg3))
#  cavityMinSuper= max(min(cavitySuperReg1),min(cavitySuperReg2),min(cavitySuperReg3))
#  cavityMin     = min(cavityMinDown,cavityMinUp,cavityMinSuper)

#  plt.plot(time['write'],cavityDownReg1,color="blue",linewidth=2)
#  plt.plot(time['store'],cavityDownReg2,color="blue",linewidth=2)
#  plt.plot(time['read'] ,cavityDownReg3,color="blue",linewidth=2,label="state '0'")

#  plt.plot(time['write'],cavityUpReg1,color="red",linewidth=2)
#  plt.plot(time['store'],cavityUpReg2,color="red",linewidth=2)
#  plt.plot(time['read'] ,cavityUpReg3,color="red",linewidth=2,label="state '1'")

#  if (impose == 1):
#    plt.plot(time['write'],cavitySuperReg1,color="green",linewidth=2)
#    plt.plot(time['store'],cavitySuperReg2,color="green",linewidth=2)
#    plt.plot(time['read'] ,cavitySuperReg3,color="green",linewidth=2,label="super state")

#  if (test == 1):
#    plt.plot(mytimeD,cavityMode_D,label="state '0' test",color="cyan")
#    plt.plot(mytimeU,cavityMode_U,label="state '1' test",color="magenta")
#    if (impose == 1):
#      plt.plot(time['write'],cavityCheckReg1,color="orange")
#      plt.plot(time['store'],cavityCheckReg2,color="orange")
#      plt.plot(time['read'] ,cavityCheckReg3,color="orange",label="super state")
#      plt.plot(mytimeS,cavityMode_S,label="super state test",color="brown")

##  plt.legend()
#  plt.xlabel('time in ns')
#  plt.ylabel('$|A(t)|^2$')

#  
#  if start != -1 and stop != -1:
#    plt.xlim([start,stop])
#  else:
#    plt.xlim([min(time['write']),max(time['read'])])

#  plt.ylim([cavityMin*1.1,cavityMax*1.1])

#  plt.fill_between(functime, cavityMax*1.1, cavityMin*1.1, color='lightgray', facecolor='lightgray', alpha=0.5)
#  plt.plot([time['store'][0],time['store'][0]], [cavityMin*1.1,cavityMax*1.1], 'k--')
#  plt.plot([time['read'] [0],time['read'] [0]], [cavityMin*1.1,cavityMax*1.1], 'k--')

#  plt.plot([cut1,cut1],[0,cavityMax*1.1],linewidth=2.0)
#  plt.plot([cut2,cut2],[0,cavityMax*1.1],linewidth=2.0)
#  plt.plot([cut3,cut3],[0,cavityMax*1.1],linewidth=2.0)

  plt.show()