# Path: sedfitter/fit_info.py
# class FitInfoFile(object):
# 
#     def __init__(self, fits, mode=None):
# 
#         if isinstance(fits, six.string_types):
# 
#             if mode not in 'wr':
#                 raise ValueError('mode should be r or w')
# 
#             self._handle = open(fits, mode + 'b')
#             self._mode = mode
# 
#             if mode == 'r':
#                 self._first_meta = FitInfoMeta()
#                 self._first_meta.model_dir = pickle.load(self._handle)
#                 self._first_meta.filters = pickle.load(self._handle)
#                 self._first_meta.extinction_law = pickle.load(self._handle)
#             else:
#                 self._first_meta = None
# 
#             self._fits = None
# 
#         elif isinstance(fits, FitInfo):
# 
#             self._fits = [fits]
# 
#         elif isinstance(fits, (list, tuple)):
# 
#             for info in self._fits[1:]:
#                 if info.meta != self._fits[0].meta:
#                     raise ValueError("The meta property of all FitInfo instances should match")
# 
#             self._fits = fits
# 
#         else:
# 
#             raise TypeError('fits should be a string, FitInfo instance, or iterable of FitInfo instances')
# 
#     @property
#     def meta(self):
#         if self._fits is None:
#             if self._mode != 'r':
#                 raise ValueError("meta property is only available in read mode")
#             return self._first_meta
#         else:
#             return self._fits[0].meta
# 
#     def write(self, info):
# 
#         if self._mode != 'w':
#             raise ValueError("File not open for writing")
# 
#         # We only write the metadata for the first source, and we then check
#         # the metadata of other sources against the first one to make sure it
#         # matches.
# 
#         if self._first_meta is None:
#             pickle.dump(info.meta.model_dir, self._handle, 2)
#             pickle.dump(info.meta.filters, self._handle, 2)
#             pickle.dump(info.meta.extinction_law, self._handle, 2)
#             self._first_meta = info.meta
#         else:
#             if not info.meta == self._first_meta:
#                 raise ValueError("meta does not match previously written value")
# 
#         pickle.dump(info, self._handle, 2)
# 
#     def close(self):
#         if self._fits is None:
#             self._handle.close()
# 
#     def __iter__(self):
#         if self._fits is None:
#             if self._mode != 'r':
#                 raise ValueError("File not open for reading")
#             while True:
#                 try:
#                     info = pickle.load(self._handle)
#                 except EOFError:
#                     return
#                 else:
#                     info.meta = self._first_meta
#                     yield info
#         else:
#             for info in self._fits:
#                 yield info
# 
# Path: sedfitter/models.py
# def load_parameter_table(model_dir):
# 
#     if os.path.exists(model_dir + '/parameters.fits'):
#         t = read_table(model_dir + '/parameters.fits')
#     elif os.path.exists(model_dir + '/parameters.fits.gz'):
#         t = read_table(model_dir + '/parameters.fits.gz')
#     else:
#         raise Exception("Parameter file not found in %s" % model_dir)
# 
#     return t
# 
# Path: sedfitter/utils/io.py
# def create_dir(dir_name):
# def delete_dir(dir_name):
# def delete_file(file_name):
# def read_table(file_name):
# 
# Path: sedfitter/utils/formatter.py
# class LogFormatterMathtextAuto(LogFormatterMathtext):
# 
#     def __call__(self, x, pos=None):
#         if x in [0.001, 0.01, 0.1]:
#             return str(x)
#         elif x in [1., 10., 100., 1000.]:
#             return str(int(x))
#         else:
#             return LogFormatterMathtext.__call__(self, x, pos=pos)
# 
# Path: sedfitter/plot_helpers.py
# def tex_friendly(string):
#     if plt.rcParams['text.usetex']:
#         return string.replace('_', '\_').replace('%', '\%')
#     else:
#         return string


from copy import deepcopy
from astropy.table import join
from astropy.convolution import Tophat2DKernel
from scipy.ndimage import convolve
from matplotlib.font_manager import FontProperties
from .fit_info import FitInfoFile
from .models import load_parameter_table
from .utils import io
from .utils.formatter import LogFormatterMathtextAuto
from .plot_helpers import tex_friendly
import numpy as np
import matplotlib.pyplot as plt
                                          np.log10(tpos[parameter_y]), bins=npix,
                                          range=[[xmin, xmax],
                                                 [np.log10(ymin), np.log10(ymax)]])
    else:
        gray_all, ex, ey = np.histogram2d(tpos[parameter_x],
                                          tpos[parameter_y], bins=npix,
                                          range=[[xmin, xmax],
                                                 [ymin, ymax]])

    gray_all = convolve(gray_all, KERNEL)
    gray_all = np.clip(gray_all, 0., 13.)

    # Grayscale showing all models. Since pcolormesh is very slow for PDF, we
    # create a 'ghost' axis which is already in log space.
    ax_log = get_axes(fig, label='log', zorder=-100)
    ax_log.axis('off')
    ax_log.imshow(gray_all.transpose(), cmap='binary', vmin=0, vmax=40.,
                  extent=[ex[0], ex[-1], ey[0], ey[-1]], aspect='auto',
                  zorder=-100, origin='lower')

    ax.patch.set_facecolor('none')

    ax.set_xlabel(parameter_x if label_x is None else label_x)
    ax.set_ylabel(parameter_y if label_y is None else label_y)

    if log_x:
        ax.set_xscale('log')
        ax.xaxis.set_major_formatter(LogFormatterMathtextAuto())
    if log_y:
        ax.set_yscale('log')

# Path: sedfitter/fit_info.py
# class FitInfoFile(object):
# 
#     def __init__(self, fits, mode=None):
# 
#         if isinstance(fits, six.string_types):
# 
#             if mode not in 'wr':
#                 raise ValueError('mode should be r or w')
# 
#             self._handle = open(fits, mode + 'b')
#             self._mode = mode
# 
#             if mode == 'r':
#                 self._first_meta = FitInfoMeta()
#                 self._first_meta.model_dir = pickle.load(self._handle)
#                 self._first_meta.filters = pickle.load(self._handle)
#                 self._first_meta.extinction_law = pickle.load(self._handle)
#             else:
#                 self._first_meta = None
# 
#             self._fits = None
# 
#         elif isinstance(fits, FitInfo):
# 
#             self._fits = [fits]
# 
#         elif isinstance(fits, (list, tuple)):
# 
#             for info in self._fits[1:]:
#                 if info.meta != self._fits[0].meta:
#                     raise ValueError("The meta property of all FitInfo instances should match")
# 
#             self._fits = fits
# 
#         else:
# 
#             raise TypeError('fits should be a string, FitInfo instance, or iterable of FitInfo instances')
# 
#     @property
#     def meta(self):
#         if self._fits is None:
#             if self._mode != 'r':
#                 raise ValueError("meta property is only available in read mode")
#             return self._first_meta
#         else:
#             return self._fits[0].meta
# 
#     def write(self, info):
# 
#         if self._mode != 'w':
#             raise ValueError("File not open for writing")
# 
#         # We only write the metadata for the first source, and we then check
#         # the metadata of other sources against the first one to make sure it
#         # matches.
# 
#         if self._first_meta is None:
#             pickle.dump(info.meta.model_dir, self._handle, 2)
#             pickle.dump(info.meta.filters, self._handle, 2)
#             pickle.dump(info.meta.extinction_law, self._handle, 2)
#             self._first_meta = info.meta
#         else:
#             if not info.meta == self._first_meta:
#                 raise ValueError("meta does not match previously written value")
# 
#         pickle.dump(info, self._handle, 2)
# 
#     def close(self):
#         if self._fits is None:
#             self._handle.close()
# 
#     def __iter__(self):
#         if self._fits is None:
#             if self._mode != 'r':
#                 raise ValueError("File not open for reading")
#             while True:
#                 try:
#                     info = pickle.load(self._handle)
#                 except EOFError:
#                     return
#                 else:
#                     info.meta = self._first_meta
#                     yield info
#         else:
#             for info in self._fits:
#                 yield info
# 
# Path: sedfitter/models.py
# def load_parameter_table(model_dir):
# 
#     if os.path.exists(model_dir + '/parameters.fits'):
#         t = read_table(model_dir + '/parameters.fits')
#     elif os.path.exists(model_dir + '/parameters.fits.gz'):
#         t = read_table(model_dir + '/parameters.fits.gz')
#     else:
#         raise Exception("Parameter file not found in %s" % model_dir)
# 
#     return t
# 
# Path: sedfitter/utils/io.py
# def create_dir(dir_name):
# def delete_dir(dir_name):
# def delete_file(file_name):
# def read_table(file_name):
# 
# Path: sedfitter/utils/formatter.py
# class LogFormatterMathtextAuto(LogFormatterMathtext):
# 
#     def __call__(self, x, pos=None):
#         if x in [0.001, 0.01, 0.1]:
#             return str(x)
#         elif x in [1., 10., 100., 1000.]:
#             return str(int(x))
#         else:
#             return LogFormatterMathtext.__call__(self, x, pos=pos)
# 
# Path: sedfitter/plot_helpers.py
# def tex_friendly(string):
#     if plt.rcParams['text.usetex']:
#         return string.replace('_', '\_').replace('%', '\%')
#     else:
#         return string


# Path: sedfitter/plot_params_2d.py
from copy import deepcopy
from astropy.table import join
from astropy.convolution import Tophat2DKernel
from scipy.ndimage import convolve
from matplotlib.font_manager import FontProperties
from .fit_info import FitInfoFile
from .models import load_parameter_table
from .utils import io
from .utils.formatter import LogFormatterMathtextAuto
from .plot_helpers import tex_friendly
import numpy as np
import matplotlib.pyplot as plt

                                          np.log10(tpos[parameter_y]), bins=npix,
                                          range=[[xmin, xmax],
                                                 [np.log10(ymin), np.log10(ymax)]])
    else:
        gray_all, ex, ey = np.histogram2d(tpos[parameter_x],
                                          tpos[parameter_y], bins=npix,
                                          range=[[xmin, xmax],
                                                 [ymin, ymax]])

    gray_all = convolve(gray_all, KERNEL)
    gray_all = np.clip(gray_all, 0., 13.)

    # Grayscale showing all models. Since pcolormesh is very slow for PDF, we
    # create a 'ghost' axis which is already in log space.
    ax_log = get_axes(fig, label='log', zorder=-100)
    ax_log.axis('off')
    ax_log.imshow(gray_all.transpose(), cmap='binary', vmin=0, vmax=40.,
                  extent=[ex[0], ex[-1], ey[0], ey[-1]], aspect='auto',
                  zorder=-100, origin='lower')

    ax.patch.set_facecolor('none')

    ax.set_xlabel(parameter_x if label_x is None else label_x)
    ax.set_ylabel(parameter_y if label_y is None else label_y)

    if log_x:
        ax.set_xscale('log')
        ax.xaxis.set_major_formatter(LogFormatterMathtextAuto())
    if log_y:
        ax.set_yscale('log')

        ax.yaxis.set_major_formatter(LogFormatterMathtextAuto())