"""
Identifier:     KSC-SJ1-MSC-MBI/magfluxconvert.py
Name:           stats.py
Description:    conversion between magnitude and flux
Author:         Hu Zou (zouhu@nao.cas.cn)
Created:        2022-11-11
Modified-History:
    2022-11-11, created
    2023-12-04, add docstring
"""

import numpy as np


def fluxerr2magerr(flux, fluxerr, asinh=False, filter='u', zp=22.5):
    """
    convert flux and flux error to mag and mag error (in pogson or asinh form)

    Parameters:
    flux, fluxerr in nanamaggie

    return mag and magerr
    """
    flux = np.array(flux)
    fluxerr = np.array(fluxerr)
    # f0 = 1.0e9
    f0 = 10**(zp/2.5)
    nn = flux.size
    mag = np.array(np.ones_like(flux)*99.0)
    magerr = np.array(np.ones_like(flux)*99.0)
    if not asinh:
        mask = flux > 0
        if mask.any():
            mag[mask] = -2.5*np.log10(flux[mask]/f0)
            magerr[mask] = 2.5/np.log(10.0)*fluxerr[mask]/flux[mask]
    else:
        bs = {'u': 1.4e-10, 'g': 0.9e-10,
              'r': 1.2e-10, 'i': 1.8e-10, 'z': 7.4e-10}
        b = bs[filter]
        mag = -(2.5/np.log(10.0))*(np.arcsinh((flux/f0)/(2.0*b))+np.log(b))
        magerr = 2.5/np.log(10.0)*(fluxerr/f0)/(2.0*b) / \
            np.sqrt(1.0+((flux/f0)/(2.0*b))**2)
    return mag, magerr
