text: # This backend is required for X11 forwarding.
  import os
  from astropy.coordinates import SkyCoord, Angle
  from astropy.nddata import Cutout2D
  from astropy.stats import sigma_clipped_stats
  from astropy.table import Table
  from astropy.wcs.utils import pixel_to_skycoord, skycoord_to_pixel
  from scipy.stats import sigmaclip
  
  from src.utils import Str, table_to_dict, wcs_pixel_info
  
  # matplotlib.use('TkAgg')
  import matplotlib.pyplot as plt
  
  plt.switch_backend('Agg')
  import matplotlib.colors as mplc
  
  from astropy.io import fits
  from astropy import wcs
  from astropy import units as u
  from astropy.visualization import ZScaleInterval
  from regions import CircleSkyRegion
  import logging
  import pandas as pd
  import numpy as np
  import pickle
  import matplotlib.gridspec as gridspec
  from mpl_toolkits import axes_grid1
  from reproject import reproject_interp, reproject_exact
  ################
  import shutil
  import os
  import logging
  import subprocess as sp
  from src.utils import Str
  import os
  import numpy as np
  from astropy.io import fits
  from astropy.visualization import make_lupton_rgb
  
  import src.globals as glo
  
  
  # def create_mosaics(file_list):
  #     assert len(set([f.band for f in file_list])) ==1, "Not from same band."
  #     f = file_list[0]
  #     data_out = os.path.join(f.entry, 'mosaics')
  #     path_swarp = shutil.which("swarp")
  #     logging.info("swarp path: {0}".format(path_swarp))
  #     image_out_name = os.path.join(data_out, 'mosaic_{0:l}'.format(f.band))
  #     ims = " ".join([f.name for f in file_list])
  #     swarp = sp.Popen(["swarp", ims, "-IMAGE_OUT_NAME", image_out_name])
  #     swarp.wait()
  #     logging.info("Completed swarp: {0}".format(image_out_name))
  
  def create_mosaics(c):
      dir_in = os.path.join(c.entry, 'interim')
      data_out = os.path.join(c.entry, 'mosaics')
      path_swarp = shutil.which("swarp")
      logging.info("swarp path: {0}".format(path_swarp))
      for b in glo.band_options:
          imageout_name = os.path.join(data_out, '{0}_mosaic_{1:l}.fits'.format(c, b))
          ims = [os.path.join(dir_in, im.name) for im in c.files_sex() if im.band == b]
          swarp = sp.Popen(["swarp", " ".join(ims), "-IMAGEOUT_NAME",
                            imageout_name])
          swarp.wait()
          logging.info("Completed swarp: {0}".format(imageout_name))
  
  
  def crete_colour_mosaic(c):
      create_mosaics(c)
      c.get_mosaic_files()
  
      dir_in = os.path.join(c, 'mosaics')
  
      g_name = os.path.join(dir_in, 'mosaic_g', 'mosaic.fits')
      r_name = os.path.join(dir_in, 'mosaic_r', 'mosaic.fits')
      i_name = os.path.join(dir_in, 'mosaic_i', 'mosaic.fits')
      # z_name = os.path.join(dir_in, 'mosaic_z', 'mosaic.fits')
  
      g = fits.open(g_name)[0].data
      r = fits.open(r_name)[0].data
      i = fits.open(i_name)[0].data
      # z = fits.open(z_name)[0].data
      # iz = np.mean(i, z)
  
      dir_out = os.path.join(c.entry, 'mosaics')
      data_out = os.path.join(dir_out, '{0}_mosaic_{1}.fits'.format(c, glo.bands))
      rgb_default = make_lupton_rgb(i, r, g, filename=dir_out)
  
  
  def get_background():
      dir_in = "/home/jacobic/projects/PanPipes/data/9_999_igrz/raw/stiff_test" \
               "/uncomp"
  
      g_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.g.unconv.fits')
      r_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.r.unconv.fits')
      i_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.i.unconv.fits')
      z_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.z.unconv.fits')
  
      # g_name = os.path.join(dir_in, 'mosaic_g', 'mosaic.fits')
      # r_name = os.path.join(dir_in, 'mosaic_r', 'mosaic.fits')
      # i_name = os.path.join(dir_in, 'mosaic_i', 'mosaic.fits')
      # z_name = os.path.join(dir_in, 'mosaic_z', 'mosaic.fits')
  
      g = fits.open(g_name)[0].data
  
  
  def crete_colour_mosaic_test():
      # create_mosaics(c)
      # c.get_mosaic_files()
  
      # dir_in = os.path.join(c, 'mosaics')
      dir_in = "/home/jacobic/projects/PanPipes/data/9_999_igrz/raw/stiff_test" \
               "/uncomp"
  
      g_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.g.unconv.fits')
      r_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.r.unconv.fits')
      i_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.i.unconv.fits')
      z_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.z.unconv.fits')
      y_name = os.path.join(dir_in,
                            'uncomp_rings.v3.skycell.2003.070.stk.y.unconv.fits')
  
      all_name = os.path.join(dir_in, '1_9419_all.csv')
      # g_name = os.path.join(dir_in, 'mosaic_g', 'mosaic.fits')
      # r_name = os.path.join(dir_in, 'mosaic_r', 'mosaic.fits')
      # i_name = os.path.join(dir_in, 'mosaic_i', 'mosaic.fits')
      # z_name = os.path.join(dir_in, 'mosaic_z', 'mosaic.fits')
  
      g = fits.open(g_name)[0].data
      r = fits.open(r_name)[0].data
      i = fits.open(i_name)[0].data
      y = fits.open(y_name)[0].data
  
      rgb = [g, r, i]
      rgb = [y, i, g]
      interval = ZScaleInterval()
      def bar(data):
          interval.get_limits(data)
          return np.sinh(interval(data))
      rgb = list(map(bar, rgb))
      all = pd.read_csv(all_name, header=0).to_records()
  
      mask_wcs, idx_sources, shape = wcs_pixel_info(Angle(all.RA, u.deg),
                                                    Angle(all.DEC, u.deg))
      hdu_density = fits.open(i_name)
      # To use a RA and DEC co-ord system, you must use a world coordinate system.
      # http://docs.astropy.org/en/stable/visualization/wcsaxes/
      i_wcs = wcs.WCS(hdu_density[0].header)
      # density_data = hdu_density[0].data
      # title = str('SPIDERS_ID: {0}, z = {0.z} col(s): {1:l}\n'.format(c, col))
      # name_fig = "{0}_density_map_{1:l}.png".format(c, col)
  
      data = np.zeros(shape)
      # Indexing the arrays this way makes the dimensions of the *_oarr the same
      #  as the weight_* arrays so that they can be added.
      # data[idx_sources] = data[idx_sources] + 1
      # projected_mask, footprint = reproject_exact(
      #     input_data=(data, mask_wcs ),
      #     output_projection=i_wcs,
      #     shape_out=i.shape,
      #     parallel=False)
      # projected_mask = projected_mask.as_type("bool")
      # rgb_list = [g,r,i]
      # foobar= map(bar, rgb_list)
      # # z = fits.open(z_name)[0].data
      # # iz = np.mean(i, z)
      # g, r, i = foobar
  
      # for Q in range(0, 15, 1):
      #     for s in range(1, 5, 1):
      #         s = s * 5
      # rgb = list(map(lambda x: sigma_clipped_stats(data=x, sigma=3.0), rgb))
      # foo = np.median(sigmaclip(rgb[0], low=3.0, high=3.0))
      # rgb = map(sigma_clipped_stats(sigma=3.0, mask=projected_mask), rgb)
      # min = zip(*rgb)[1]
      m = tuple(
          (map(lambda x: np.median(sigmaclip(np.where(x is not np.nan, x,
                                                      0), low=3.0, high=3.0)[0]),
               rgb)))
      # m = np.percentile(i, 1), np.percentile(r, 1), np.percentile(g, 1)
      # m = 300, 300, 300
      data_out = os.path.join(dir_in, 'sweep', 'mosaic_test.jpeg')
      rgb = make_lupton_rgb(i, r, g, minimum=m, filename=data_out)
      # name_density = '{0}_density_map_{1:l}.fits'.format(c, col)
      # data_in = os.path.join(c.entry, 'processed', name_density)
      # data_in = os.path.join(name)
  
      plt.clf()
      fig = plt.figure(figsize=(15, 15))
      # initializing axes with world coordinates
      # http://docs.astropy.org/en/stable/visualization/wcsaxes
      # /initializing_axes.html
  
      ax0 = fig.add_subplot(111, projection=i_wcs)
      im0 = ax0.imshow(rgb, origin='lower', vmin=0, vmax=2.5)
      name_dens = "/home/jacobic/projects/PanPipes/data/9_999_igrz" \
                  "/processed/1_9419_limit_weights_70.csv"
      lim_dens = pd.read_csv(name_dens, sep=',').to_records()
      ax0.scatter(lim_dens.RA, lim_dens.DEC, marker="o", facecolors='none',
                  edgecolors='cyan', transform=ax0.get_transform('world'))
  
      # To remove the whitespace surrounding the figure add xlim and ylim
      ax0.set_xlabel('RA')
      ax0.set_ylabel('Dec')
      ax0.set_xlim(0, rgb.shape[1])
      ax0.set_ylim(0, rgb.shape[0])
      data_out = os.path.join(glo.DIR_FIGS, 'stiff_test.png')
      plt.savefig(data_out, format='png', dpi=300)
  