# Path: src/naima/plot.py
# def find_ML(sampler, modelidx):
#     """
#     Find Maximum Likelihood parameters as those in the chain with a highest log
#     probability.
#     """
#     lnprobability = sampler.get_log_prob()
#     index = np.unravel_index(np.argmax(lnprobability), lnprobability.shape)
#     MLp = sampler.get_chain()[index]
#     blobs = sampler.get_blobs()
#     if modelidx is not None and blobs is not None:
#         blob = blobs[index][modelidx]
#         if isinstance(blob, u.Quantity):
#             modelx = sampler.data["energy"].copy()
#             model_ML = blob.copy()
#         elif len(blob) == 2:
#             modelx = blob[0].copy()
#             model_ML = blob[1].copy()
#         else:
#             raise TypeError("Model {0} has wrong blob format".format(modelidx))
#     elif modelidx is not None and hasattr(sampler, "modelfn"):
#         blob = _process_blob(
#             [sampler.modelfn(MLp, sampler.data)],
#             modelidx,
#             energy=sampler.data["energy"],
#         )
#         modelx, model_ML = blob[0], blob[1][0]
#     else:
#         modelx, model_ML = None, None
# 
#     MLerr = []
#     for dist in sampler.get_chain(flat=True).T:
#         hilo = np.percentile(dist, [16.0, 84.0])
#         MLerr.append((hilo[1] - hilo[0]) / 2.0)
#     ML = lnprobability[index]
# 
#     return ML, MLp, MLerr, (modelx, model_ML)


import os
import astropy.units as u
import h5py
import numpy as np
    import yaml  # noqa
from pathlib import Path
from astropy import log
from astropy.io.misc.hdf5 import read_table_hdf5, write_table_hdf5
from astropy.table import Table
from .plot import find_ML
    from matplotlib import pyplot as plt
    from .plot import plot_blob, plot_chain, plot_corner
        from matplotlib.backends.backend_pdf import PdfPages
    if last_step:
        dists = sampler.get_chain()[:, -1, :]
    else:
        dists = sampler.get_chain(flat=True)

    quant = [16, 50, 84]
    # Do we need more info on the distributions?
    t = Table(
        names=["label", "median", "unc_lo", "unc_hi"],
        dtype=["S72", "f8", "f8", "f8"],
    )
    t["label"].description = "Name of the parameter"
    t["median"].description = "Median of the posterior distribution function"
    t["unc_lo"].description = (
        "Difference between the median and the"
        " {0}th percentile of the pdf, ~1sigma lower uncertainty".format(
            quant[0]
        )
    )
    t["unc_hi"].description = (
        "Difference between the {0}th percentile"
        " and the median of the pdf, ~1sigma upper uncertainty".format(
            quant[2]
        )
    )

    metadata = {}
    # Start with info from the distributions used for storing the results
    metadata["n_samples"] = dists.shape[0]
    # save ML parameter vector and best/median loglikelihood

# Path: src/naima/plot.py
# def find_ML(sampler, modelidx):
#     """
#     Find Maximum Likelihood parameters as those in the chain with a highest log
#     probability.
#     """
#     lnprobability = sampler.get_log_prob()
#     index = np.unravel_index(np.argmax(lnprobability), lnprobability.shape)
#     MLp = sampler.get_chain()[index]
#     blobs = sampler.get_blobs()
#     if modelidx is not None and blobs is not None:
#         blob = blobs[index][modelidx]
#         if isinstance(blob, u.Quantity):
#             modelx = sampler.data["energy"].copy()
#             model_ML = blob.copy()
#         elif len(blob) == 2:
#             modelx = blob[0].copy()
#             model_ML = blob[1].copy()
#         else:
#             raise TypeError("Model {0} has wrong blob format".format(modelidx))
#     elif modelidx is not None and hasattr(sampler, "modelfn"):
#         blob = _process_blob(
#             [sampler.modelfn(MLp, sampler.data)],
#             modelidx,
#             energy=sampler.data["energy"],
#         )
#         modelx, model_ML = blob[0], blob[1][0]
#     else:
#         modelx, model_ML = None, None
# 
#     MLerr = []
#     for dist in sampler.get_chain(flat=True).T:
#         hilo = np.percentile(dist, [16.0, 84.0])
#         MLerr.append((hilo[1] - hilo[0]) / 2.0)
#     ML = lnprobability[index]
# 
#     return ML, MLp, MLerr, (modelx, model_ML)


# Path: src/naima/analysis.py
import os
import astropy.units as u
import h5py
import numpy as np
    import yaml  # noqa
from pathlib import Path
from astropy import log
from astropy.io.misc.hdf5 import read_table_hdf5, write_table_hdf5
from astropy.table import Table
from .plot import find_ML
    from matplotlib import pyplot as plt
    from .plot import plot_blob, plot_chain, plot_corner
        from matplotlib.backends.backend_pdf import PdfPages

    if last_step:
        dists = sampler.get_chain()[:, -1, :]
    else:
        dists = sampler.get_chain(flat=True)

    quant = [16, 50, 84]
    # Do we need more info on the distributions?
    t = Table(
        names=["label", "median", "unc_lo", "unc_hi"],
        dtype=["S72", "f8", "f8", "f8"],
    )
    t["label"].description = "Name of the parameter"
    t["median"].description = "Median of the posterior distribution function"
    t["unc_lo"].description = (
        "Difference between the median and the"
        " {0}th percentile of the pdf, ~1sigma lower uncertainty".format(
            quant[0]
        )
    )
    t["unc_hi"].description = (
        "Difference between the {0}th percentile"
        " and the median of the pdf, ~1sigma upper uncertainty".format(
            quant[2]
        )
    )

    metadata = {}
    # Start with info from the distributions used for storing the results
    metadata["n_samples"] = dists.shape[0]
    # save ML parameter vector and best/median loglikelihood

    ML, MLp, MLerr, _ = find_ML(sampler, None)