# Path: frbpoppy/paths.py
# class Paths():
#     def __init__(self):
#     def __str__(self):
#     def check(self, path):
#     def store(self, name, default, *args):
#     def data(self, *args):
#     def populations(self, *args):
#     def surveys(self, *args):
#     def models(self, *args):
#     def frbcat(self, *args):
# 
# Path: frbpoppy/misc.py
# def poisson_interval(k, sigma=1):
#     """
#     Use chi-squared info to get the poisson interval.
# 
#     Given a number of observed events, which range of observed events would
#     have been just as likely given a particular interval?
# 
#     Based off https://stackoverflow.com/questions/14813530/
#     poisson-confidence-interval-with-numpy
#     """
#     gauss = norm(0, 1).pdf
#     a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0]
#     low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2)
#     if k == 0:
#         low = 0.0
# 
#     return low, high
# 
# Path: frbpoppy/population.py
# def unpickle(filename=None, uid=None):
#     """Quick function to unpickle a population.
# 
#     Args:
#         filename (str, optional): Define the path to the pickled population,
#             or give the population name
#         uid (str, optional): Unique Identifier
# 
#     Returns:
#         Population: Population class
# 
#     """
#     # Find population file
#     if os.path.isfile(filename):
#         f = open(filename, 'rb')
#     else:
#         # Find standard population files
#         try:
#             name = filename.lower()
#             if uid:
#                 name += f'_{uid}'
#             p = paths.populations() + f'{name}.p'
#             f = open(p, 'rb')
#         except FileNotFoundError:
#             s = 'Pickled population file "{0}" does not exist'.format(filename)
#             raise FileNotFoundError(s)
# 
#     # Unpickle
#     pop = pickle.load(f)
#     f.close()
#     return pop
# 
# Path: tests/convenience.py
# def plot_aa_style(cols=1):
#     """Use a plotting style specifically for Astronomy & Astrophyiscs."""
#     # Use a style file
#     dir = os.path.abspath(os.path.dirname(__file__))
#     style_file = os.path.join(dir, './aa.mplstyle')
#     plt.style.use(style_file)
# 
#     # Check whether interactive backend is present
#     if os.name == 'posix' and "DISPLAY" not in os.environ:
#         # On a cluster
#         plt.switch_backend('Agg')
#         # Use just the basic latex package allowing \text to be used
#         plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
# 
#     if cols == 2:
#         plt.rcParams["figure.figsize"] = (5.75373, 3.556)
# 
# def rel_path(path):
#     """Return the relative path name for this directory."""
#     return os.path.join(os.path.abspath(os.path.dirname(__file__)), path)


import numpy as np
import os
import matplotlib.pyplot as plt
from glob import glob
from matplotlib.colors import LogNorm
from frbpoppy import paths, unpickle, poisson_interval
from tests.convenience import plot_aa_style, rel_path
from alpha_real import EXPECTED
      'li': np.linspace(-2, 0, 5),  # Luminosity function index
      'si': np.linspace(-2, 2, 5)}  # Spectral index
SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa')


def get_pops(alpha='*', li='*', si='*', survey='*'):
    filename = f'complex_alpha_{alpha}_lum_{li}_si_{si}_{survey}.p'
    filter = os.path.join(paths.populations(), filename)
    pop_paths = glob(filter)

    pops = []
    for path in pop_paths:
        if '_for_plotting' not in path:
            pops.append(unpickle(path))
    return pops


def make_mesh(x_par, y_par, survey):
    v = np.zeros([len(vs[x_par]), len(vs[y_par])])
    print(x_par, y_par)
    for i, x_val in enumerate(vs[x_par]):
        for j, y_val in enumerate(vs[y_par]):
            print(x_val, y_val)

            pops = get_pops(survey=survey, **{x_par: x_val, y_par: y_val})

            if pops:
                rates = []
                for pop in pops:
                    rate = pop.source_rate.det / pop.source_rate.days

# Path: frbpoppy/paths.py
# class Paths():
#     def __init__(self):
#     def __str__(self):
#     def check(self, path):
#     def store(self, name, default, *args):
#     def data(self, *args):
#     def populations(self, *args):
#     def surveys(self, *args):
#     def models(self, *args):
#     def frbcat(self, *args):
# 
# Path: frbpoppy/misc.py
# def poisson_interval(k, sigma=1):
#     """
#     Use chi-squared info to get the poisson interval.
# 
#     Given a number of observed events, which range of observed events would
#     have been just as likely given a particular interval?
# 
#     Based off https://stackoverflow.com/questions/14813530/
#     poisson-confidence-interval-with-numpy
#     """
#     gauss = norm(0, 1).pdf
#     a = 1 - quad(gauss, -sigma, sigma, limit=1000)[0]
#     low, high = (chi2.ppf(a/2, 2*k) / 2, chi2.ppf(1-a/2, 2*k + 2) / 2)
#     if k == 0:
#         low = 0.0
# 
#     return low, high
# 
# Path: frbpoppy/population.py
# def unpickle(filename=None, uid=None):
#     """Quick function to unpickle a population.
# 
#     Args:
#         filename (str, optional): Define the path to the pickled population,
#             or give the population name
#         uid (str, optional): Unique Identifier
# 
#     Returns:
#         Population: Population class
# 
#     """
#     # Find population file
#     if os.path.isfile(filename):
#         f = open(filename, 'rb')
#     else:
#         # Find standard population files
#         try:
#             name = filename.lower()
#             if uid:
#                 name += f'_{uid}'
#             p = paths.populations() + f'{name}.p'
#             f = open(p, 'rb')
#         except FileNotFoundError:
#             s = 'Pickled population file "{0}" does not exist'.format(filename)
#             raise FileNotFoundError(s)
# 
#     # Unpickle
#     pop = pickle.load(f)
#     f.close()
#     return pop
# 
# Path: tests/convenience.py
# def plot_aa_style(cols=1):
#     """Use a plotting style specifically for Astronomy & Astrophyiscs."""
#     # Use a style file
#     dir = os.path.abspath(os.path.dirname(__file__))
#     style_file = os.path.join(dir, './aa.mplstyle')
#     plt.style.use(style_file)
# 
#     # Check whether interactive backend is present
#     if os.name == 'posix' and "DISPLAY" not in os.environ:
#         # On a cluster
#         plt.switch_backend('Agg')
#         # Use just the basic latex package allowing \text to be used
#         plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
# 
#     if cols == 2:
#         plt.rcParams["figure.figsize"] = (5.75373, 3.556)
# 
# def rel_path(path):
#     """Return the relative path name for this directory."""
#     return os.path.join(os.path.abspath(os.path.dirname(__file__)), path)


# Path: tests/rates/corner.py
import numpy as np
import os
import matplotlib.pyplot as plt
from glob import glob
from matplotlib.colors import LogNorm
from frbpoppy import paths, unpickle, poisson_interval
from tests.convenience import plot_aa_style, rel_path
from alpha_real import EXPECTED

      'li': np.linspace(-2, 0, 5),  # Luminosity function index
      'si': np.linspace(-2, 2, 5)}  # Spectral index
SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa')


def get_pops(alpha='*', li='*', si='*', survey='*'):
    filename = f'complex_alpha_{alpha}_lum_{li}_si_{si}_{survey}.p'
    filter = os.path.join(paths.populations(), filename)
    pop_paths = glob(filter)

    pops = []
    for path in pop_paths:
        if '_for_plotting' not in path:
            pops.append(unpickle(path))
    return pops


def make_mesh(x_par, y_par, survey):
    v = np.zeros([len(vs[x_par]), len(vs[y_par])])
    print(x_par, y_par)
    for i, x_val in enumerate(vs[x_par]):
        for j, y_val in enumerate(vs[y_par]):
            print(x_val, y_val)

            pops = get_pops(survey=survey, **{x_par: x_val, y_par: y_val})

            if pops:
                rates = []
                for pop in pops:
                    rate = pop.source_rate.det / pop.source_rate.days

                    rate_err = poisson_interval(pop.source_rate.det, sigma=1)