# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
#     FORMATS = {'DEFAULT'       : "%(message)s",
#                logging.WARNING : "WARNING: %(message)s",
#                logging.ERROR   : "ERROR: %(message)s"}
#     def format(self, record):
# def file_found(filename,force):
# 
# Path: ugali/utils/healpix.py
# def superpixel(subpix, nside_subpix, nside_superpix):
# def subpixel(superpix, nside_superpix, nside_subpix):
# def d_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def phi2lon(phi): return np.degrees(phi)
# def lon2phi(lon): return np.radians(lon)
# def theta2lat(theta): return 90. - np.degrees(theta)
# def lat2theta(lat): return np.radians(90. - lat)
# def pix2ang(nside, pix, nest=False):
# def ang2pix(nside, lon, lat, nest=False):
# def ang2vec(lon, lat):
# def get_nside(m):
# def healpixMap(nside, lon, lat, fill_value=0., nest=False):
# def in_pixels(lon,lat,pixels,nside):
# def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
# def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
# def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
# def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
# def get_interp_val(m, lon, lat, *args, **kwargs):
# def header_odict(nside,nest=False,coord=None, partial=True):
# def write_partial_map(filename, data, nside, coord=None, nest=False,
#                       header=None,dtype=None,**kwargs):
# def read_partial_map(filenames, column, fullsky=True, **kwargs):
# def merge_partial_maps(filenames,outfile,**kwargs):
# def merge_likelihood_headers(filenames, outfile, **kwargs):
# def merge_likelihood_headers2(filenames, outfile, **kwargs):
# def read_map(filename, nest=False, hdu=None, h=False, verbose=True):


import glob
import os
import numpy as np
import ugali.utils.skymap
        import matplotlib
        import pylab as plt
        import ugali.utils.plotting as plotting
        import fitsio
        import numpy as np
        import healpy as hp
from os.path import join, exists, basename
from ugali.analysis.farm import Farm
from ugali.analysis.pipeline import Pipeline
from ugali.utils.shell import mkdir
from ugali.utils.logger import logger
from ugali.utils import healpix
        from ugali.utils.skymap import inFootprint
    if 'scan' in self.opts.run:
        logger.info("Running 'scan'...")
        farm = Farm(self.config,verbose=self.opts.verbose)
        farm.submit_all(coords=self.opts.coords,queue=self.opts.queue,debug=self.opts.debug)

    if 'merge' in self.opts.run:
        logger.info("Running 'merge'...")
        mergefile = self.config.mergefile
        roifile = self.config.roifile
        filenames = self.config.likefile.split('_%')[0]+'_*.fits'
        infiles = np.array(sorted(glob.glob(filenames)))

        if 'mergedir' in self.config['output']:
            mkdir(self.config['output']['mergedir'])

        pixels = np.char.rpartition(np.char.rpartition(infiles,'_')[:,0],'_')[:,-1]
        pixels = pixels.astype(int)
        superpixel = healpix.superpixel(pixels,
                                        self.config['coords']['nside_likelihood'],
                                        self.config['coords']['nside_merge'])
                         
        for pix in np.unique(superpixel):
            outfile = mergefile%pix
            if exists(outfile) and not self.opts.force:
                logger.warn("  Found %s; skipping..."%outfile)
            else:
                healpix.merge_partial_maps(infiles[superpixel == pix],
                                           outfile,multiproc=8)

        if exists(roifile) and not self.opts.force:

# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
#     FORMATS = {'DEFAULT'       : "%(message)s",
#                logging.WARNING : "WARNING: %(message)s",
#                logging.ERROR   : "ERROR: %(message)s"}
#     def format(self, record):
# def file_found(filename,force):
# 
# Path: ugali/utils/healpix.py
# def superpixel(subpix, nside_subpix, nside_superpix):
# def subpixel(superpix, nside_superpix, nside_subpix):
# def d_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
# def phi2lon(phi): return np.degrees(phi)
# def lon2phi(lon): return np.radians(lon)
# def theta2lat(theta): return 90. - np.degrees(theta)
# def lat2theta(lat): return np.radians(90. - lat)
# def pix2ang(nside, pix, nest=False):
# def ang2pix(nside, lon, lat, nest=False):
# def ang2vec(lon, lat):
# def get_nside(m):
# def healpixMap(nside, lon, lat, fill_value=0., nest=False):
# def in_pixels(lon,lat,pixels,nside):
# def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
# def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
# def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
# def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
# def get_interp_val(m, lon, lat, *args, **kwargs):
# def header_odict(nside,nest=False,coord=None, partial=True):
# def write_partial_map(filename, data, nside, coord=None, nest=False,
#                       header=None,dtype=None,**kwargs):
# def read_partial_map(filenames, column, fullsky=True, **kwargs):
# def merge_partial_maps(filenames,outfile,**kwargs):
# def merge_likelihood_headers(filenames, outfile, **kwargs):
# def merge_likelihood_headers2(filenames, outfile, **kwargs):
# def read_map(filename, nest=False, hdu=None, h=False, verbose=True):


# Path: ugali/pipeline/run_03.0_likelihood.py
import glob
import os
import numpy as np
import ugali.utils.skymap
        import matplotlib
        import pylab as plt
        import ugali.utils.plotting as plotting
        import fitsio
        import numpy as np
        import healpy as hp
from os.path import join, exists, basename
from ugali.analysis.farm import Farm
from ugali.analysis.pipeline import Pipeline
from ugali.utils.shell import mkdir
from ugali.utils.logger import logger
from ugali.utils import healpix
        from ugali.utils.skymap import inFootprint

    if 'scan' in self.opts.run:
        logger.info("Running 'scan'...")
        farm = Farm(self.config,verbose=self.opts.verbose)
        farm.submit_all(coords=self.opts.coords,queue=self.opts.queue,debug=self.opts.debug)

    if 'merge' in self.opts.run:
        logger.info("Running 'merge'...")
        mergefile = self.config.mergefile
        roifile = self.config.roifile
        filenames = self.config.likefile.split('_%')[0]+'_*.fits'
        infiles = np.array(sorted(glob.glob(filenames)))

        if 'mergedir' in self.config['output']:
            mkdir(self.config['output']['mergedir'])

        pixels = np.char.rpartition(np.char.rpartition(infiles,'_')[:,0],'_')[:,-1]
        pixels = pixels.astype(int)
        superpixel = healpix.superpixel(pixels,
                                        self.config['coords']['nside_likelihood'],
                                        self.config['coords']['nside_merge'])
                         
        for pix in np.unique(superpixel):
            outfile = mergefile%pix
            if exists(outfile) and not self.opts.force:
                logger.warn("  Found %s; skipping..."%outfile)
            else:
                healpix.merge_partial_maps(infiles[superpixel == pix],
                                           outfile,multiproc=8)

        if exists(roifile) and not self.opts.force:

            logger.warn("  Found %s; skipping..."%roifile)