def genDemo():	
	
	#=============================	
	
	f=open("test2Dplot.py","w")

	f.write("import numpy as np\n")
	f.write("import matplotlib.pyplot as plt\n")
	f.write("\n")
	f.write("outname='test2D'\n")
	f.write("\n")
	f.write("scratch_path = 'foscat_data'\n")
	f.write("r1=np.load(scratch_path+'/%s_r1.npy'%(outname))\n")
	f.write("r2=np.load(scratch_path+'/%s_r2.npy'%(outname))\n")
	f.write("o1=np.load(scratch_path+'/%s_o1.npy'%(outname))\n")
	f.write("o2=np.load(scratch_path+'/%s_o2.npy'%(outname))\n")
	f.write("\n")
	f.write("plt.figure(figsize=(12,8))\n")
	f.write("plt.subplot(1,2,1)\n")
	f.write("plt.plot(r1.flatten(),color='blue',label='input')\n")
	f.write("plt.plot(o1.flatten(),color='red',label='synthesised')\n")
	f.write("plt.yscale('log')\n")
	f.write("plt.ylabel(r'$S_1$')\n")
	f.write("plt.legend()\n")
	f.write("plt.subplot(1,2,2)\n")
	f.write("plt.plot(r2.flatten(),color='blue',label='input')\n")
	f.write("plt.plot(o2.flatten(),color='red',label='synthesised')\n")
	f.write("plt.yscale('log')\n")
	f.write("plt.ylabel(r'$S_2$')\n")
	f.write("\n")
	f.write("ref =np.load(scratch_path+'/%s_ref.npy'%(outname))\n")
	f.write("omap=np.load(scratch_path+'/%s_result.npy'%(outname))\n")
	f.write("\n")
	f.write("amp=ref.max()\n")
	f.write("nx=ref.shape[0]\n")
	f.write("plt.figure(figsize=(12,8))\n")
	f.write("plt.subplot(1,2,1)\n")
	f.write("plt.imshow(ref[nx//2-nx//4:nx//2+nx//4,nx//2-nx//4:nx//2+nx//4],cmap='jet',origin='lower',vmin=-amp,vmax=amp)\n")
	f.write("plt.title('Input')\n")
	f.write("plt.subplot(1,2,2)\n")
	f.write("plt.imshow(omap[nx//2-nx//4:nx//2+nx//4,nx//2-nx//4:nx//2+nx//4],cmap='jet',origin='lower',vmin=-amp,vmax=amp)\n")
	f.write("plt.title('FoSCAT')\n")
	f.write("plt.show()\n")
	
	
	#=============================	
	
	f=open("test2D.py","w")

	f.write("import numpy as np\n")
	f.write("import os, sys\n")
	f.write("import matplotlib.pyplot as plt\n")
	f.write("import foscat.foscat as FOC\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# INITIALIZE foscat class\n")
	f.write("#=================================================================================\n")
	f.write("#  Change the temporary path\n")
	f.write("#=================================================================================\n")
	f.write("scratch_path = 'foscat_data'\n")
	f.write("outname='test2D'\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# This test could be run till XSIZE=512 but could last for Hours if not GPUs are\n")
	f.write("# available. XSIZE=128 takes few minutes with NVIDIA T4.\n")
	f.write("#=================================================================================\n")
	f.write("XSIZE=128\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("#==   Make the statistic invariant by rotation => Higher dimension reduction    ==\n")
	f.write("#==   avg_ang = True                                                            ==\n")
	f.write("#=================================================================================\n")
	f.write("avg_ang=False\n")
	f.write("\n")
	f.write("fc=FOC.foscat(NORIENT=8,KERNELSZ=5,OSTEP=0,TEMPLATE_PATH=scratch_path)\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("#  READ data and get data if necessary: \n")
	f.write("#=================================================================================\n")
	f.write("#  Here the input data is a vorticity map of 512x512:\n")
	f.write("# This image shows a simulated snapshot of ocean turbulence in the North Atlantic Ocean in March 2012,\n")
	f.write("# from a groundbreaking super-high-resolution global ocean simulation (approximately 1.2 miles, \n")
	f.write("#or 2 kilometers, horizontal resolution) developed at JPL.\n")
	f.write("# (http://wwwcvs.mitgcm.org/viewvc/MITgcm/MITgcm_contrib/llc_hires/llc_4320/). \n")
	f.write("#=================================================================================\n")
	f.write("try:\n")
	f.write("    d=np.load(scratch_path+'/Vorticity.npy')\n")
	f.write("except:\n")
	f.write("    import imageio as iio\n")
	f.write("\n")
	f.write("    os.system('wget -O '+scratch_path+'/PIA22256.tif https://photojournal.jpl.nasa.gov/tiff/PIA22256.tif')\n")
	f.write("    \n")
	f.write("    im=iio.imread(scratch_path+'/PIA22256.tif')\n")
	f.write("    im=im[1000:1512,2000:2512,0]/255.0-im[1000:1512,2000:2512,2]/255.0\n")
	f.write("    np.save(scratch_path+'/Vorticity.npy',im)\n")
	f.write("    os.system('rm '+scratch_path+'/PIA22256.tif')\n")
	f.write("    d=np.load(scratch_path+'/Vorticity.npy')\n")
	f.write("\n")
	f.write("\n")
	f.write("d=d[0:XSIZE,0:XSIZE]\n")
	f.write("nx=d.shape[0]\n")
	f.write("# define the level of noise of the simulation\n")
	f.write("ampnoise=1.0\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# Synthesise data with the same cross statistic than the input data\n")
	f.write("#=================================================================================\n")
	f.write("\n")
	f.write("# convert data in tensor for Foscat\n")
	f.write("idata = fc.convimage(d)\n")
	f.write("\n")
	f.write("# define the mask where the statistic are used\n")
	f.write("x=np.repeat((np.arange(XSIZE)-XSIZE/2)/XSIZE,XSIZE).reshape(XSIZE,XSIZE)\n")
	f.write("mask=np.exp(-32*(x**4+(x.T)**4))\n")
	f.write("fc.add_mask(mask.reshape(1,nx,nx))\n")
	f.write("\n")
	f.write("# Initialize the learning and initialize the tensor to be synthesized\n")
	f.write("randfield=np.random.randn(nx,nx)\n")
	f.write("ldata=fc.init_synthese(randfield)\n")
	f.write("\n")
	f.write("# Build the loss:\n")
	f.write("# here Loss += (d x d - s x s - tb[0]).tw[0]\n")
	f.write("fc.add_loss_2d(idata,idata,ldata,ldata,avg_ang=avg_ang)\n")
	f.write("\n")
	f.write("# initiliaze the synthesise process\n")
	f.write("loss=fc.init_optim()\n")
	f.write("\n")
	f.write("tw1={}\n")
	f.write("tw2={}\n")
	f.write("tb1={}\n")
	f.write("tb2={}\n")
	f.write("# compute the weights and the bias for each loss\n")
	f.write("modd=d.reshape(1,nx,nx)\n")
	f.write("r1,r2=fc.calc_stat(modd,modd,avg_ang=avg_ang)\n")
	f.write("\n")
	f.write("tw1[0]=1.0/r1[0]\n")
	f.write("tw2[0]=1.0/r2[0]\n")
	f.write("tb1[0]=0.0*r1[0]\n")
	f.write("tb2[0]=0.0*r2[0]\n")
	f.write("\n")
	f.write("#save the reference statistics\n")
	f.write("np.save(scratch_path+'/%s_r1.npy'%(outname), r1)\n")
	f.write("np.save(scratch_path+'/%s_r2.npy'%(outname), r2)\n")
	f.write("\n")
	f.write("# Run the learning\n")
	f.write("fc.learn(tw1,tw2,tb1,tb2,NUM_EPOCHS = 1000,DECAY_RATE=1.0)\n")
	f.write("\n")
	f.write("# get the output map\n")
	f.write("omap=fc.get_map()\n")
	f.write("\n")
	f.write("modd=omap.reshape(1,nx,nx)\n")
	f.write("o1,o2=fc.calc_stat(modd,modd,avg_ang=avg_ang)\n")
	f.write("#save the statistics on the synthesised data\n")
	f.write("np.save(scratch_path+'/%s_o1.npy'%(outname), o1)\n")
	f.write("np.save(scratch_path+'/%s_o2.npy'%(outname), o2)\n")
	f.write("\n")
	f.write("np.save(scratch_path+'/%s_ref.npy'%(outname), d)\n")
	f.write("np.save(scratch_path+'/%s_start.npy'%(outname), randfield)\n")
	f.write("np.save(scratch_path+'/%s_result.npy'%(outname),omap)\n")
	
	
	#=============================	
	
	f=open("testHealpix.py","w")

	f.write("import numpy as np\n")
	f.write("import os, sys\n")
	f.write("import matplotlib.pyplot as plt\n")
	f.write("import healpy as hp\n")
	f.write("import foscat as FOC\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# DEFINE A PATH FOR scratch data\n")
	f.write("# The data are storred using a default nside to minimize the needed storage\n")
	f.write("#=================================================================================\n")
	f.write("scratch_path = 'foscat_data'\n")
	f.write("outname='TEST'\n")
	f.write("Default_nside=512\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# INITIALIZE foscat class\n")
	f.write("#=================================================================================\n")
	f.write("fc=FOC.foscat(NORIENT=4,\n")
	f.write("             KERNELSZ=3,\n")
	f.write("             healpix=True,\n")
	f.write("             OSTEP=0,\n")
	f.write("             slope=1.0,\n")
	f.write("             TEMPLATE_PATH=scratch_path)\n")
	f.write("\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# DENOISE NSIDE=32 MAP\n")
	f.write("#=================================================================================\n")
	f.write("nout=32\n")
	f.write("#=================================================================================\n")
	f.write("# Function to reduce the data used in the foscat algorithm \n")
	f.write("#=================================================================================\n")
	f.write("def dodown(a,nout):\n")
	f.write("    nin=int(np.sqrt(a.shape[0]//12))\n")
	f.write("    if nin==nout:\n")
	f.write("        return(a)\n")
	f.write("    return(np.mean(a.reshape(12*nout*nout,(nin//nout)**2),1))\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# Get data from web for demo\n")
	f.write("#=================================================================================\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# Get dust simulated map from PySM2\n")
	f.write("#=================================================================================\n")
	f.write("try:\n")
	f.write("    d=dodown(np.load(scratch_path+'/dust_512.npy'),nout)\n")
	f.write("except:\n")
	f.write("    os.system('wget -O '+scratch_path+'/dust2comp_I1_ns512_545.fits https://portal.nersc.gov/project/cmb/pysm-data/pysm_2/dust2comp_I1_ns512_545.fits')\n")
	f.write("\n")
	f.write("    print('wget -O '+scratch_path+'/dust2comp_I1_ns512_545.fits https://portal.nersc.gov/project/cmb/pysm-data/pysm_2/dust2comp_I1_ns512_545.fits')\n")
	f.write("    im=hp.ud_grade(hp.read_map(scratch_path+'/dust2comp_I1_ns512_545.fits'),512)\n")
	f.write("    idx=hp.nest2ring(512,np.arange(12*512**2))\n")
	f.write("    im=10*im/im.std()\n")
	f.write("    np.save(scratch_path+'/dust_512.npy',im[idx])\n")
	f.write("    os.system('rm '+scratch_path+'/dust2comp_I1_ns512_545.fits')\n")
	f.write("    d=dodown(np.load(scratch_path+'/dust_512.npy'),nout)\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# Get HI experimetal map\n")
	f.write("#=================================================================================\n")
	f.write("try:\n")
	f.write("    td=dodown(np.load(scratch_path+'/TH1_512.npy'),nout)\n")
	f.write("except:\n")
	f.write("    os.system('wget -O '+scratch_path+'/haslam408_dsds_Remazeilles2014.fits http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=haslam408_dsds_Remazeilles2014.fits')\n")
	f.write("    h1=hp.ud_grade(hp.read_map(scratch_path+'/haslam408_dsds_Remazeilles2014.fits'),512)\n")
	f.write("    idx=hp.nest2ring(512,np.arange(12*512**2))\n")
	f.write("    h1=h1/h1.std()\n")
	f.write("    np.save(scratch_path+'/TH1_512.npy',h1[idx])\n")
	f.write("    os.system('rm '+scratch_path+'/haslam408_dsds_Remazeilles2014.fits')\n")
	f.write("    td=dodown(np.load(scratch_path+'/TH1_512.npy'),nout)\n")
	f.write("\n")
	f.write("# define the level of noise of the simulation\n")
	f.write("ampnoise=0.3\n")
	f.write("Alpha=0.8\n")
	f.write("nsim=100\n")
	f.write("avg_ang=False\n")
	f.write("\n")
	f.write("# Build to half mission by adding noise to the data on the first process\n")
	f.write("d1 = d+ampnoise*np.random.randn(12*nout**2)\n")
	f.write("d2 = d+ampnoise*np.random.randn(12*nout**2)\n")
	f.write("# simulate the noisy data\n")
	f.write("di = d+ampnoise*np.random.randn(12*nout**2)/np.sqrt(2)\n")
	f.write("np.save(scratch_path+'/test%sref.npy'%(outname), d)\n")
	f.write("np.save(scratch_path+'/test%sinput.npy'%(outname),di)\n")
	f.write("np.save(scratch_path+'/test%sinput1.npy'%(outname),d1)\n")
	f.write("np.save(scratch_path+'/test%sinput2.npy'%(outname),d2)\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# For real data:\n")
	f.write("# you have to give d1,d2 and d\n")
	f.write("# you have to define the value ampnoise\n")
	f.write("#=================================================================================\n")
	f.write("\n")
	f.write("\n")
	f.write("# All information of the map is used\n")
	f.write("nin=512\n")
	f.write("\n")
	f.write("tab=['MASK_GAL097_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL090_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL080_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL060_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL040_%d.npy'%(nin)]\n")
	f.write("\n")
	f.write("mask=np.ones([len(tab),12*nout**2])\n")
	f.write("for imask in range(len(tab)):\n")
	f.write("    try:\n")
	f.write("        mask[imask]=dodown(np.load(scratch_path+'/'+tab[imask]),nout)\n")
	f.write("    except:\n")
	f.write("        print('==========================================================')\n")
	f.write("        print('')\n")
	f.write("        print('Get offical Planck Galactic masks...may take few minutes..')\n")
	f.write("        print('')\n")
	f.write("        print('==========================================================')\n")
	f.write("\n")
	f.write("        os.system('wget -O '+scratch_path+'/HFI_Mask_GalPlane-apo5_2048_R2.00.fits https://irsa.ipac.caltech.edu/data/Planck/release_2/ancillary-data/masks/HFI_Mask_GalPlane-apo5_2048_R2.00.fits')\n")
	f.write("        tab_data=['GAL020','GAL040','GAL060','GAL070','GAL080','GAL090','GAL097','GAL099']\n")
	f.write("        \n")
	f.write("        idx=hp.nest2ring(512,np.arange(12*512**2))\n")
	f.write("        for i in range(10):\n")
	f.write("            mask=hp.ud_grade(hp.read_map(scratch_path+'/HFI_Mask_GalPlane-apo5_2048_R2.00.fits',i),512)\n")
	f.write("            np.save(scratch_path+'/MASK_%s_512.npy'%(tab_data[i]),mask[idx])\n")
	f.write("            print('Save '+scratch_path+'/MASK_%s_512.npy'%(tab_data[i]))\n")
	f.write("        os.system('rm '+scratch_path+'/HFI_Mask_GalPlane-apo5_2048_R2.00.fits')\n")
	f.write("        mask[imask]=dodown(np.load(scratch_path+'/'+tab[imask]),nout)\n")
	f.write("        \n")
	f.write("mask[0,:]=1.0\n")
	f.write("fc.add_mask(mask)\n")
	f.write("\n")
	f.write("# convert data in tensor for foscat (should be done internally)\n")
	f.write("data1 = fc.convimage(d1)\n")
	f.write("data2 = fc.convimage(d2)\n")
	f.write("data  = fc.convimage(di)\n")
	f.write("tdata = fc.convimage(td)\n")
	f.write("\n")
	f.write("# Initialize the learning and initialize the tensor to be synthesized\n")
	f.write("ldata=fc.init_synthese(di)\n")
	f.write("\n")
	f.write("# Add losss:\n")
	f.write("# here d1 x d2 = s x s\n")
	f.write("fc.add_loss_healpix(data1,data2,ldata,ldata,avg_ang=avg_ang)\n")
	f.write("# here d1 x d2 = d x s\n")
	f.write("fc.add_loss_healpix(data,ldata,ldata,ldata,avg_ang=avg_ang)\n")
	f.write("# here T x d = T x s\n")
	f.write("fc.add_loss_healpix(tdata,data,tdata,ldata,avg_ang=avg_ang,imaginary=True)\n")
	f.write("\n")
	f.write("# initiliaze the loss\n")
	f.write("loss=fc.init_optim()\n")
	f.write("\n")
	f.write("moddr=d.reshape(1,12*nout**2)\n")
	f.write("x1,x2=fc.calc_stat(moddr,moddr,avg_ang=avg_ang)\n")
	f.write("np.save(scratch_path+'/i%s1_%d.npy'%(outname,0), x1)\n")
	f.write("np.save(scratch_path+'/i%s2_%d.npy'%(outname,0), x2)\n")
	f.write("\n")
	f.write("c1,c2=fc.calc_stat(d1.reshape(1,12*nout**2),d2.reshape(1,12*nout**2),avg_ang=avg_ang)\n")
	f.write("np.save(scratch_path+'/c%s1_%d.npy'%(outname,0), c1)\n")
	f.write("np.save(scratch_path+'/c%s2_%d.npy'%(outname,0), c2)\n")
	f.write("lmap1=1*d1\n")
	f.write("lmap2=1*d2\n")
	f.write("\n")
	f.write("tw1={}\n")
	f.write("tw2={}\n")
	f.write("tb1={}\n")
	f.write("tb2={}\n")
	f.write("for i in range(3):\n")
	f.write("    tw1[i]=0.0\n")
	f.write("    tw2[i]=0.0\n")
	f.write("    tb1[i]=0.0\n")
	f.write("    tb2[i]=0.0\n")
	f.write("    \n")
	f.write("for itt in range(5):\n")
	f.write("    # compute scattering to make weights\n")
	f.write("    modd1=lmap1.reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("    modd2=lmap2.reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("    o1,o2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,gpupos=0)\n")
	f.write("    modd1=lmap1.reshape(1,12*nout**2)\n")
	f.write("    modd2=lmap2.reshape(1,12*nout**2)\n")
	f.write("    r1,r2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,gpupos=0)\n")
	f.write("    #calcul poids des coeffs\n")
	f.write("    np.save(scratch_path+'/b%s1_%d.npy'%(outname,itt), r1)\n")
	f.write("    np.save(scratch_path+'/b%s2_%d.npy'%(outname,itt), r2)\n")
	f.write("    np.save(scratch_path+'/n%s1_%d.npy'%(outname,itt), o1)\n")
	f.write("    np.save(scratch_path+'/n%s2_%d.npy'%(outname,itt), o2)\n")
	f.write("        \n")
	f.write("    modd1=lmap1.reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("    modd2=lmap2.reshape(1,12*nout**2)+0*np.random.randn(nsim,12*nout**2)\n")
	f.write("    of1,of2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,gpupos=1)\n")
	f.write("    \n")
	f.write("    modd1=td.reshape(1,12*nout**2)+0*np.random.randn(nsim,12*nout**2)\n")
	f.write("    modd2=((lmap1+lmap2)/2).reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("    onx1,onx2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,imaginary=True,gpupos=2)\n")
	f.write("    modd1=td.reshape(1,12*nout**2)\n")
	f.write("    modd2=((lmap1+lmap2)/2).reshape(1,12*nout**2)\n")
	f.write("    ox1,ox2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,imaginary=True,gpupos=2)\n")
	f.write("    \n")
	f.write("    tw1[0]=1/np.std(o1,0)\n")
	f.write("    tw2[0]=1/np.std(o2,0)\n")
	f.write("    tw1[1]=1/np.std(of1,0)\n")
	f.write("    tw2[1]=1/np.std(of2,0)\n")
	f.write("    tw1[2]=1/np.std(onx1,0)\n")
	f.write("    tw2[2]=1/np.std(onx2,0)\n")
	f.write("    \n")
	f.write("    tb1[0]=Alpha*(np.mean(o1-r1,0)-tb1[0])+tb1[0]\n")
	f.write("    tb2[0]=Alpha*(np.mean(o2-r2,0)-tb2[0])+tb2[0]\n")
	f.write("    tb1[1]=Alpha*(np.mean(of1-r1,0)-tb1[1])+tb1[1]\n")
	f.write("    tb2[1]=Alpha*(np.mean(of2-r2,0)-tb2[1])+tb2[1]\n")
	f.write("    tb1[2]=Alpha*(np.mean(onx1-ox1,0)-tb1[2])+tb1[2]\n")
	f.write("    tb2[2]=Alpha*(np.mean(onx2-ox2,0)-tb2[2])+tb2[2]\n")
	f.write("    \n")
	f.write("    # make the learn\n")
	f.write("    fc.reset()\n")
	f.write("    \n")
	f.write("    omap=fc.learn(tw1,tw2,tb1,tb2,NUM_EPOCHS = 500,DECAY_RATE=0.95,LEARNING_RATE=0.03)\n")
	f.write("\n")
	f.write("    print('ITT ',itt,((d-omap)*mask[1].reshape(12*nout**2)).std(),((d-di)*mask[1].reshape(12*nout**2)).std())\n")
	f.write("    sys.stdout.flush()\n")
	f.write("    modd1=omap.reshape(1,12*nout**2)\n")
	f.write("    oo1,oo2=fc.calc_stat(modd1,modd1,avg_ang=avg_ang)\n")
	f.write("    lmap1=1*omap\n")
	f.write("    lmap2=1*omap\n")
	f.write("    np.save(scratch_path+'/o%s1_%d.npy'%(outname,itt), oo1)\n")
	f.write("    np.save(scratch_path+'/o%s2_%d.npy'%(outname,itt), oo2)\n")
	f.write("    np.save(scratch_path+'/test%sresult_%d.npy'%(outname,itt),omap)\n")
	f.write("\n")
	f.write("\n")
	
	
	#=============================	
	
	f=open("testHplot.py","w")

	f.write("import numpy as np\n")
	f.write("import os, sys\n")
	f.write("import healpy as hp\n")
	f.write("import matplotlib.pyplot as plt\n")
	f.write("\n")
	f.write("nitt=10\n")
	f.write("scratch_path = 'foscat_data'\n")
	f.write("outname='TEST_MPI'\n")
	f.write("\n")
	f.write("def dodown(a,nout):\n")
	f.write("    nin=int(np.sqrt(a.shape[0]//12))\n")
	f.write("    if nin==nout:\n")
	f.write("        return(a)\n")
	f.write("    return(np.mean(a.reshape(12*nout*nout,(nin//nout)**2),1))\n")
	f.write("\n")
	f.write("plt.figure(figsize=(12,12))\n")
	f.write("#reference\n")
	f.write("i1=np.load(scratch_path+'/i%s1_%d.npy'%(outname,0))\n")
	f.write("i2=np.load(scratch_path+'/i%s2_%d.npy'%(outname,0))\n")
	f.write("#mesure\n")
	f.write("c1=np.load(scratch_path+'/c%s1_%d.npy'%(outname,0))\n")
	f.write("c2=np.load(scratch_path+'/c%s2_%d.npy'%(outname,0))\n")
	f.write("\n")
	f.write("plt.subplot(1,2,1)\n")
	f.write("plt.plot(abs(1-i1.flatten()/i1.flatten()),color='blue')\n")
	f.write("plt.plot(abs(1-c1.flatten()/i1.flatten()),color='orange')\n")
	f.write("plt.yscale('log')\n")
	f.write("plt.ylabel(r'$S_1$')\n")
	f.write("plt.xlabel('j1')\n")
	f.write("plt.subplot(1,2,2)\n")
	f.write("plt.plot(abs(1-i2.flatten()/i2.flatten()),color='blue')\n")
	f.write("plt.plot(abs(1-c2.flatten()/i2.flatten()),color='orange')\n")
	f.write("plt.yscale('log')\n")
	f.write("plt.ylabel(r'$S_2$')\n")
	f.write("plt.xlabel('j1,j2')\n")
	f.write("    \n")
	f.write("for itt in range(nitt):\n")
	f.write("    #foscat map\n")
	f.write("    o1=np.load(scratch_path+'/o%s1_%d.npy'%(outname,itt))\n")
	f.write("    o2=np.load(scratch_path+'/o%s2_%d.npy'%(outname,itt))\n")
	f.write("\n")
	f.write("    plt.subplot(1,2,1)\n")
	f.write("    plt.plot(abs(1-o1.flatten()/i1.flatten()),color='red',lw=1)\n")
	f.write("    plt.subplot(1,2,2)\n")
	f.write("    plt.plot(abs(1-o2.flatten()/i2.flatten()),color='red',lw=1)\n")
	f.write("    \n")
	f.write("plt.subplot(1,2,1)\n")
	f.write("plt.plot(abs(1-o1.flatten()/i1.flatten()),color='red',lw=4)\n")
	f.write("plt.subplot(1,2,2)\n")
	f.write("plt.plot(abs(1-o2.flatten()/i2.flatten()),color='red',lw=4)\n")
	f.write("    \n")
	f.write("plt.subplot(1,2,1)\n")
	f.write("plt.plot(abs(1-i1.flatten()/i1.flatten()),color='blue')\n")
	f.write("plt.plot(abs(1-c1.flatten()/i1.flatten()),color='orange')\n")
	f.write("plt.yscale('log')\n")
	f.write("plt.ylabel(r'$S_1$')\n")
	f.write("plt.xlabel('j1')\n")
	f.write("plt.subplot(1,2,2)\n")
	f.write("plt.plot(abs(1-i2.flatten()/i2.flatten()),color='blue')\n")
	f.write("plt.plot(abs(1-c2.flatten()/i2.flatten()),color='orange')\n")
	f.write("plt.yscale('log')\n")
	f.write("plt.ylabel(r'$S_2$')\n")
	f.write("plt.xlabel('j1,j2')\n")
	f.write("\n")
	f.write("d  = np.load(scratch_path+'/test%sref.npy'%(outname))\n")
	f.write("d1 = np.load(scratch_path+'/test%sinput1.npy'%(outname))\n")
	f.write("d2 = np.load(scratch_path+'/test%sinput2.npy'%(outname))\n")
	f.write("di = np.load(scratch_path+'/test%sinput.npy'%(outname))\n")
	f.write("s  = np.load(scratch_path+'/test%sresult_%d.npy'%(outname,nitt-1)).flatten()\n")
	f.write("\n")
	f.write("amp=4\n")
	f.write("\n")
	f.write("plt.figure(figsize=(12,6))\n")
	f.write("hp.mollview(d,cmap='jet',    nest=True,hold=False,sub=(2,3,1),min=-amp,max=amp,title='Model',norm='hist')\n")
	f.write("hp.mollview(di,cmap='jet',   nest=True,hold=False,sub=(2,3,2),min=-amp,max=amp,title='Noisy',norm='hist')\n")
	f.write("hp.mollview(s,cmap='jet',    nest=True,hold=False,sub=(2,3,3),min=-amp,max=amp,title='Cleanned',norm='hist')\n")
	f.write("hp.mollview(di-d,cmap='jet', nest=True,hold=False,sub=(2,3,4),min=-amp/4,max=amp/4,title='Noisy-Model')\n")
	f.write("hp.mollview(di-s,cmap='jet', nest=True,hold=False,sub=(2,3,5),min=-amp/4,max=amp/4,title='Noisy-Cleanned')\n")
	f.write("hp.mollview(s-d,cmap='jet',  nest=True,hold=False,sub=(2,3,6),min=-amp/4,max=amp/4,title='Cleanned-Model')\n")
	f.write("\n")
	f.write("nin=512\n")
	f.write("nout=int(np.sqrt(d.shape[0]//12))\n")
	f.write("idx=hp.ring2nest(nout,np.arange(12*nout**2))\n")
	f.write("\n")
	f.write("mask=dodown(np.load(scratch_path+'/MASK_GAL080_%d.npy'%(nin)),nout)\n")
	f.write("clr=hp.anafast((mask*d-np.median(mask*d))[idx])\n")
	f.write("cli=hp.anafast((mask*di-np.median(mask*di))[idx])\n")
	f.write("cln=hp.anafast((mask*(d-di)-np.median(mask*(d-di)))[idx])\n")
	f.write("\n")
	f.write("plt.figure(figsize=(12,12))\n")
	f.write("\n")
	f.write("for itt in range(nitt):\n")
	f.write("    s  = np.load(scratch_path+'/test%sresult_%d.npy'%(outname,itt)).flatten()\n")
	f.write("\n")
	f.write("    clo=hp.anafast((mask*s-np.median(mask*s))[idx])\n")
	f.write("    cld=hp.anafast((mask*(d-s)-np.median(mask*(d-s)))[idx])\n")
	f.write("\n")
	f.write("    plt.plot(clo,color='orange',label='s %d'%(itt),lw=1)\n")
	f.write("    plt.plot(cld,color='red',label='r-s %d'%(itt),lw=1)\n")
	f.write("\n")
	f.write("plt.plot(clo,color='orange',label='s %d'%(itt),lw=4)\n")
	f.write("plt.plot(cld,color='red',label='r-s %d'%(itt),lw=4)\n")
	f.write("    \n")
	f.write("plt.plot(clr,color='black',label='r')\n")
	f.write("plt.plot(cli,color='blue',label='d')\n")
	f.write("plt.plot(cln,color='grey',label='r-d')\n")
	f.write("\n")
	f.write("plt.legend()\n")
	f.write("plt.xscale('log')\n")
	f.write("plt.yscale('log')\n")
	f.write("plt.show()\n")
	
	
	#=============================	
	
	f=open("testHealpix_mpi.py","w")

	f.write("import numpy as np\n")
	f.write("import os, sys\n")
	f.write("import matplotlib.pyplot as plt\n")
	f.write("import healpy as hp\n")
	f.write("import foscat as FOC\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# DEFINE A PATH FOR scratch data\n")
	f.write("# The data are storred using a default nside to minimize the needed storage\n")
	f.write("#=================================================================================\n")
	f.write("scratch_path = 'foscat_data'\n")
	f.write("outname='TEST_MPI'\n")
	f.write("Default_nside=512\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# INITIALIZE foscat class\n")
	f.write("#=================================================================================\n")
	f.write("fc=FOC.foscat(NORIENT=8,\n")
	f.write("              KERNELSZ=5,\n")
	f.write("              healpix=True,\n")
	f.write("              OSTEP=0,\n")
	f.write("              slope=1.0,\n")
	f.write("              isMPI=True,\n")
	f.write("              TEMPLATE_PATH=scratch_path)\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# DENOISE NSIDE=32 MAP\n")
	f.write("#=================================================================================\n")
	f.write("nout=32\n")
	f.write("#=================================================================================\n")
	f.write("# Function to reduce the data used in the foscat algorithm \n")
	f.write("#=================================================================================\n")
	f.write("def dodown(a,nout):\n")
	f.write("    nin=int(np.sqrt(a.shape[0]//12))\n")
	f.write("    if nin==nout:\n")
	f.write("        return(a)\n")
	f.write("    return(np.mean(a.reshape(12*nout*nout,(nin//nout)**2),1))\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# Get data from web for demo\n")
	f.write("#=================================================================================\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# Get dust simulated map from PySM2\n")
	f.write("#=================================================================================\n")
	f.write("try:\n")
	f.write("    d=dodown(np.load(scratch_path+'/dust_512.npy'),nout)\n")
	f.write("except:\n")
	f.write("    if fc.get_rank()==0:\n")
	f.write("        os.system('wget -O '+scratch_path+'/dust2comp_I1_ns512_545.fits https://portal.nersc.gov/project/cmb/pysm-data/pysm_2/dust2comp_I1_ns512_545.fits')\n")
	f.write("\n")
	f.write("        print('wget -O '+scratch_path+'/dust2comp_I1_ns512_545.fits https://portal.nersc.gov/project/cmb/pysm-data/pysm_2/dust2comp_I1_ns512_545.fits')\n")
	f.write("        im=hp.ud_grade(hp.read_map(scratch_path+'/dust2comp_I1_ns512_545.fits'),512)\n")
	f.write("        idx=hp.nest2ring(512,np.arange(12*512**2))\n")
	f.write("        im=10*im/im.std()\n")
	f.write("        np.save(scratch_path+'/dust_512.npy',im[idx])\n")
	f.write("        os.system('rm '+scratch_path+'/dust2comp_I1_ns512_545.fits')\n")
	f.write("    fc.barrier()\n")
	f.write("    \n")
	f.write("    d=dodown(np.load(scratch_path+'/dust_512.npy'),nout)\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# Get HI experimetal map\n")
	f.write("#=================================================================================\n")
	f.write("try:\n")
	f.write("    td=dodown(np.load(scratch_path+'/TH1_512.npy'),nout)\n")
	f.write("except:\n")
	f.write("    if fc.get_rank()==0:\n")
	f.write("        os.system('wget -O '+scratch_path+'/haslam408_dsds_Remazeilles2014.fits http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=haslam408_dsds_Remazeilles2014.fits')\n")
	f.write("        h1=hp.ud_grade(hp.read_map(scratch_path+'/haslam408_dsds_Remazeilles2014.fits'),512)\n")
	f.write("        idx=hp.nest2ring(512,np.arange(12*512**2))\n")
	f.write("        h1=h1/h1.std()\n")
	f.write("        np.save(scratch_path+'/TH1_512.npy',h1[idx])\n")
	f.write("        os.system('rm '+scratch_path+'/haslam408_dsds_Remazeilles2014.fits')\n")
	f.write("    fc.barrier()\n")
	f.write("    td=dodown(np.load(scratch_path+'/TH1_512.npy'),nout)\n")
	f.write("\n")
	f.write("\n")
	f.write("# define the level of noise of the simulation\n")
	f.write("ampnoise=0.3\n")
	f.write("Alpha=1.0\n")
	f.write("nsim=100\n")
	f.write("avg_ang=True\n")
	f.write("\n")
	f.write("# Build to half mission by adding noise to the data on the first process\n")
	f.write("if fc.get_rank()==0:\n")
	f.write("    d1 = d+ampnoise*np.random.randn(12*nout**2)\n")
	f.write("    d2 = d+ampnoise*np.random.randn(12*nout**2)\n")
	f.write("    # simulate the noisy data\n")
	f.write("    di = d+ampnoise*np.random.randn(12*nout**2)/np.sqrt(2)\n")
	f.write("    np.save(scratch_path+'/test%sref.npy'%(outname), d)\n")
	f.write("    np.save(scratch_path+'/test%sinput.npy'%(outname),di)\n")
	f.write("    np.save(scratch_path+'/test%sinput1.npy'%(outname),d1)\n")
	f.write("    np.save(scratch_path+'/test%sinput2.npy'%(outname),d2)\n")
	f.write("    \n")
	f.write("# Ensure to use the same input data into all process\n")
	f.write("fc.barrier()\n")
	f.write("\n")
	f.write("d=np.load(scratch_path+'/test%sref.npy'%(outname))\n")
	f.write("di=np.load(scratch_path+'/test%sinput.npy'%(outname))\n")
	f.write("d1=np.load(scratch_path+'/test%sinput1.npy'%(outname))\n")
	f.write("d2=np.load(scratch_path+'/test%sinput2.npy'%(outname))\n")
	f.write("\n")
	f.write("#=================================================================================\n")
	f.write("# For real data:\n")
	f.write("# you have to give d1,d2 and d\n")
	f.write("# you have to define the value ampnoise\n")
	f.write("#=================================================================================\n")
	f.write("\n")
	f.write("\n")
	f.write("# All information of the map is used\n")
	f.write("nin=512\n")
	f.write("\n")
	f.write("tab=['MASK_GAL097_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL090_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL080_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL060_%d.npy'%(nin),\n")
	f.write("     'MASK_GAL040_%d.npy'%(nin)]\n")
	f.write("\n")
	f.write("mask=np.ones([len(tab),12*nout**2])\n")
	f.write("for imask in range(len(tab)):\n")
	f.write("    try:\n")
	f.write("        mask[imask]=dodown(np.load(scratch_path+'/'+tab[imask]),nout)\n")
	f.write("    except:\n")
	f.write("        if fc.get_rank()==0:\n")
	f.write("            print('==========================================================')\n")
	f.write("            print('')\n")
	f.write("            print('Get offical Planck Galactic masks...may take few minutes..')\n")
	f.write("            print('')\n")
	f.write("            print('==========================================================')\n")
	f.write("\n")
	f.write("            os.system('wget -O '+scratch_path+'/HFI_Mask_GalPlane-apo5_2048_R2.00.fits https://irsa.ipac.caltech.edu/data/Planck/release_2/ancillary-data/masks/HFI_Mask_GalPlane-apo5_2048_R2.00.fits')\n")
	f.write("            tab_data=['GAL020','GAL040','GAL060','GAL070','GAL080','GAL090','GAL097','GAL099']\n")
	f.write("\n")
	f.write("            idx=hp.nest2ring(512,np.arange(12*512**2))\n")
	f.write("            for i in range(10):\n")
	f.write("                mask=hp.ud_grade(hp.read_map(scratch_path+'/HFI_Mask_GalPlane-apo5_2048_R2.00.fits',i),512)\n")
	f.write("                np.save(scratch_path+'/MASK_%s_512.npy'%(tab_data[i]),mask[idx])\n")
	f.write("                print('Save '+scratch_path+'/MASK_%s_512.npy'%(tab_data[i]))\n")
	f.write("            os.system('rm '+scratch_path+'/HFI_Mask_GalPlane-apo5_2048_R2.00.fits')\n")
	f.write("        fc.barrier()\n")
	f.write("        mask[imask]=dodown(np.load(scratch_path+'/'+tab[imask]),nout)\n")
	f.write("        \n")
	f.write("mask[0,:]=1.0\n")
	f.write("fc.add_mask(mask)\n")
	f.write("\n")
	f.write("# convert data in tensor for foscat (should be done internally)\n")
	f.write("data1 = fc.convimage(d1)\n")
	f.write("data2 = fc.convimage(d2)\n")
	f.write("data  = fc.convimage(di)\n")
	f.write("tdata = fc.convimage(td)\n")
	f.write("\n")
	f.write("# Initialize the learning and initialize the tensor to be synthesized\n")
	f.write("ldata=fc.init_synthese(di)\n")
	f.write("\n")
	f.write("# Add losss:\n")
	f.write("# here d1 x d2 = s x s\n")
	f.write("if fc.get_rank()==0:\n")
	f.write("    fc.add_loss_healpix(data1,data2,ldata,ldata,avg_ang=avg_ang)\n")
	f.write("# here d1 x d2 = d x s\n")
	f.write("if fc.get_rank()==1:\n")
	f.write("    fc.add_loss_healpix(data,ldata,ldata,ldata,avg_ang=avg_ang)\n")
	f.write("# here T x d = T x s\n")
	f.write("if fc.get_rank()==2:\n")
	f.write("    fc.add_loss_healpix(tdata,data,tdata,ldata,avg_ang=avg_ang,imaginary=True)\n")
	f.write("\n")
	f.write("# initiliaze the loss\n")
	f.write("loss=fc.init_optim()\n")
	f.write("\n")
	f.write("moddr=d.reshape(1,12*nout**2)\n")
	f.write("x1,x2=fc.calc_stat(moddr,moddr,avg_ang=avg_ang)\n")
	f.write("if fc.get_rank()==0:\n")
	f.write("    np.save(scratch_path+'/i%s1_%d.npy'%(outname,0), x1)\n")
	f.write("    np.save(scratch_path+'/i%s2_%d.npy'%(outname,0), x2)\n")
	f.write("\n")
	f.write("c1,c2=fc.calc_stat(d1.reshape(1,12*nout**2),d2.reshape(1,12*nout**2),avg_ang=avg_ang)\n")
	f.write("if fc.get_rank()==0:\n")
	f.write("    np.save(scratch_path+'/c%s1_%d.npy'%(outname,0), c1)\n")
	f.write("    np.save(scratch_path+'/c%s2_%d.npy'%(outname,0), c2)\n")
	f.write("lmap1=1*d1\n")
	f.write("lmap2=1*d2\n")
	f.write("\n")
	f.write("tw1={}\n")
	f.write("tw2={}\n")
	f.write("tb1={}\n")
	f.write("tb2={}\n")
	f.write("for i in range(3):\n")
	f.write("    tw1[i]=0.0\n")
	f.write("    tw2[i]=0.0\n")
	f.write("    tb1[i]=0.0\n")
	f.write("    tb2[i]=0.0\n")
	f.write("\n")
	f.write("for itt in range(10):\n")
	f.write("    if fc.get_rank()==0:\n")
	f.write("        # compute scattering to make weights\n")
	f.write("        modd1=lmap1.reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("        modd2=lmap2.reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("        o1,o2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,gpupos=0)\n")
	f.write("        modd1=lmap1.reshape(1,12*nout**2)\n")
	f.write("        modd2=lmap2.reshape(1,12*nout**2)\n")
	f.write("        r1,r2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,gpupos=0)\n")
	f.write("        #calcul poids des coeffs\n")
	f.write("        np.save(scratch_path+'/b%s1_%d.npy'%(outname,itt), r1)\n")
	f.write("        np.save(scratch_path+'/b%s2_%d.npy'%(outname,itt), r2)\n")
	f.write("        np.save(scratch_path+'/n%s1_%d.npy'%(outname,itt), o1)\n")
	f.write("        np.save(scratch_path+'/n%s2_%d.npy'%(outname,itt), o2)\n")
	f.write("        \n")
	f.write("    if fc.get_rank()==1:\n")
	f.write("        modd1=lmap1.reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("        modd2=lmap2.reshape(1,12*nout**2)+0*np.random.randn(nsim,12*nout**2)\n")
	f.write("        of1,of2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,gpupos=1)\n")
	f.write("        modd1=lmap1.reshape(1,12*nout**2)\n")
	f.write("        modd2=lmap2.reshape(1,12*nout**2)\n")
	f.write("        r1,r2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,gpupos=1)\n")
	f.write("    if fc.get_rank()==2:\n")
	f.write("        modd1=td.reshape(1,12*nout**2)+0*np.random.randn(nsim,12*nout**2)\n")
	f.write("        modd2=((lmap1+lmap2)/2).reshape(1,12*nout**2)+ampnoise*np.random.randn(nsim,12*nout**2)\n")
	f.write("        onx1,onx2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,imaginary=True,gpupos=2)\n")
	f.write("        modd1=td.reshape(1,12*nout**2)\n")
	f.write("        modd2=((lmap1+lmap2)/2).reshape(1,12*nout**2)\n")
	f.write("        ox1,ox2=fc.calc_stat(modd1,modd2,avg_ang=avg_ang,imaginary=True,gpupos=2)\n")
	f.write("    \n")
	f.write("    \n")
	f.write("    if fc.get_rank()==0:\n")
	f.write("        tw1[0]=1/np.std(o1,0)\n")
	f.write("        tw2[0]=1/np.std(o2,0)\n")
	f.write("    if fc.get_rank()==1:\n")
	f.write("        tw1[0]=1/np.std(of1,0)\n")
	f.write("        tw2[0]=1/np.std(of2,0)\n")
	f.write("    if fc.get_rank()==2:\n")
	f.write("        tw1[0]=1/np.std(onx1,0)\n")
	f.write("        tw2[0]=1/np.std(onx2,0)\n")
	f.write("    \n")
	f.write("    if fc.get_rank()==0:\n")
	f.write("        tb1[0]=Alpha*(np.mean(o1-r1,0)-tb1[0])+tb1[0]\n")
	f.write("        tb2[0]=Alpha*(np.mean(o2-r2,0)-tb2[0])+tb2[0]\n")
	f.write("    if fc.get_rank()==1:\n")
	f.write("        tb1[0]=Alpha*(np.mean(of1-r1,0)-tb1[0])+tb1[0]\n")
	f.write("        tb2[0]=Alpha*(np.mean(of2-r2,0)-tb2[0])+tb2[0]\n")
	f.write("    if fc.get_rank()==2:\n")
	f.write("        tb1[0]=Alpha*(np.mean(onx1-ox1,0)-tb1[0])+tb1[0]\n")
	f.write("        tb2[0]=Alpha*(np.mean(onx2-ox2,0)-tb2[0])+tb2[0]\n")
	f.write("    \n")
	f.write("    # make the learn\n")
	f.write("    fc.reset()\n")
	f.write("    \n")
	f.write("    omap=fc.learn(tw1,tw2,tb1,tb2,NUM_EPOCHS = 1000,DECAY_RATE=0.995,LEARNING_RATE=0.03,ADDAPT_LEARN=2.0)\n")
	f.write("\n")
	f.write("    if fc.get_rank()==0:\n")
	f.write("        print('ITT ',itt,((d-omap)*mask[1].reshape(12*nout**2)).std(),((d-di)*mask[1].reshape(12*nout**2)).std())\n")
	f.write("        sys.stdout.flush()\n")
	f.write("        modd1=omap.reshape(1,12*nout**2)\n")
	f.write("        oo1,oo2=fc.calc_stat(modd1,modd1,avg_ang=avg_ang)\n")
	f.write("        lmap1=1*omap\n")
	f.write("        lmap2=1*omap\n")
	f.write("        np.save(scratch_path+'/o%s1_%d.npy'%(outname,itt), oo1)\n")
	f.write("        np.save(scratch_path+'/o%s2_%d.npy'%(outname,itt), oo2)\n")
	f.write("        np.save(scratch_path+'/test%sresult_%d.npy'%(outname,itt),omap)\n")
	f.write("\n")
	f.write("\n")
	f.close()	
#======= END OF DEMO ========
