# Path: astwro/phot/lc_io.py
# def write_lc(hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
#     if ids is None:
#         ids = range(lc.shape[0])
#     masked = isinstance(lc, np.ma.MaskedArray)
#     if masked:
#         smask = lc.count(axis=1) >= min_obs
#     else:
#         smask = np.ones(lc.shape[0], dtype=bool)
#     logging.info('Number of stars to save: {}'.format(np.count_nonzero(smask)))
#     for i in smask.nonzero()[0]:
#         fname = '{:s}{:05d}{:s}'.format(prefix, ids[i], suffix)
#         logging.info('Processing star id: ',i)
#         d = lc[i]
#         if masked:
#             m = ~d.mask
#             t = hjd[m]
#             e = lc_e[i][m] if lc_e is not None else None
#             d = d.compressed()
#         else:
#             t = hjd
#             e = lc_e[i] if lc_e is not None else None
#         if lc_e is None:
#             out = np.array([t, d]).T
#         else:
#             out = np.array([t, d, e]).T
#         np.savetxt(fname, out, fmt='%15f')
# 
# def write_lc_filters(filters_masks, filternames, hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
#     if isinstance(filters_masks, dict):
#         filters_masks = [filters_masks[f] for f in filternames]
#     filters_masks = np.array(filters_masks, dtype=bool)
# 
#     for i, mask in enumerate(filters_masks):
#         logging.info('Writing lc for Filter: {}'.format(filternames[i]))
#         s = '_' + filternames[i] + suffix
#         mhjd = hjd[mask]
#         mlc = lc[:, mask]
#         if lc_e is not None:
#             mlc_e = lc_e[:, mask]
#         else:
#             mlc_e = None
#         write_lc(mhjd, mlc, mlc_e, ids, min_obs, prefix, s)
# 
# Path: astwro/utils/TmpDir.py
# class TmpDir(PathLike):
#     """
#     instances of TmpDir keeps track and lifetime of temporary directory
#     """
#     path = None
#     dir_is_tmp = True
#     _prefix = ''
#     _base = None
# 
#     def __init__(self, use_existing=None, prefix='astwro_tmp_', base_dir=None):
#         """
#         :param str use_existing:    If provided, instance will point to that directory and not delete it on destruct
#         :param str prefix:          Prefix for temporary dir
#         :param str base_dir:        Where to crate tem dir, in None system default is used
#         """
#         self._prefix = prefix
#         self._base = base_dir
#         if use_existing is None:
#             self.path = mkdtemp(prefix=prefix, dir=base_dir)
#             self.dir_is_tmp = True
#         else:
#             self.path = use_existing
#             self.dir_is_tmp = False
# 
#     def clone(self):
#         return deepcopy(self)
# 
#     def __del__(self):
#         self._rm_dir()
# 
#     def __enter__(self):
#         return self
# 
#     def __exit__(self, type_, value, traceback):
#         self._rm_dir()
# 
#     def __repr__(self):
#         return ('Tmp dir:' if self.dir_is_tmp else 'Ext dir:') + (self.path if self.path else 'none')
# 
#     def __str__(self):
#         return self.path
# 
#     def __deepcopy__(self, memo):
#         cls = self.__class__
#         new = cls.__new__(cls)
#         memo[id(self)] = new
#         if self.dir_is_tmp:
#             new.__init__(prefix=self._prefix, base_dir=self._base)
#             shutil.rmtree(new.path)
#             shutil.copytree(self.path, new.path, symlinks=True)
#         else:
#             new.__init__(use_existing=self.path)
#         return new
# 
#     def __fspath__(self):
#         """Implements ``os.PathLike interface``"""
#         return str(self)
# 
#     def _rm_dir(self):
#         """Deletes working dir with all content."""
#         if self.dir_is_tmp:
#             try:
#                 shutil.rmtree(self.path)
#             except OSError:
#                 pass


from astwro.phot import *
from os.path import join
from astwro.phot.lc_io import write_lc, write_lc_filters
from astwro.utils import TmpDir
import numpy as np
import sys
    import os
    import pickle
    s, l, o, se, le, oe = dphot(d, e, c)
    dp = DiffPhot(d, e, c)
    assert  np.allclose(dp.mag, s)
    assert  np.allclose(dp.lc, l)
    assert  np.allclose(dp.obs_deltas, o)


    e = dp.err
    e2= e**2
    d = dp.obs_deltas_stddev
    d2 = d**2

    x =  (dp.mag, dp.mag_v2, dp.lc_e)
#    assert  np.allclose(dp.mag_e, se)



def test_write_lc():
    #TODO: Limit numer of stars in some_stars_data.pkl
    with TmpDir() as td:
        d, e, f = prepare_testset_real()
        hjd = np.linspace(989.34316, 1002.63264, d.shape[1])
        write_lc(hjd, d, e, prefix=join(td.path, 'lc_'))

def test_write_lc_filter():
    d, e, f = prepare_testset_real()
    hjd = np.linspace(989.34316, 1002.63264, d.shape[1])
    fn = ['B', 'Han']
    r = np.random.uniform(size=d.shape[1])
    fm = np.array([r<0.5, r>=0.5], dtype=bool)

# Path: astwro/phot/lc_io.py
# def write_lc(hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
#     if ids is None:
#         ids = range(lc.shape[0])
#     masked = isinstance(lc, np.ma.MaskedArray)
#     if masked:
#         smask = lc.count(axis=1) >= min_obs
#     else:
#         smask = np.ones(lc.shape[0], dtype=bool)
#     logging.info('Number of stars to save: {}'.format(np.count_nonzero(smask)))
#     for i in smask.nonzero()[0]:
#         fname = '{:s}{:05d}{:s}'.format(prefix, ids[i], suffix)
#         logging.info('Processing star id: ',i)
#         d = lc[i]
#         if masked:
#             m = ~d.mask
#             t = hjd[m]
#             e = lc_e[i][m] if lc_e is not None else None
#             d = d.compressed()
#         else:
#             t = hjd
#             e = lc_e[i] if lc_e is not None else None
#         if lc_e is None:
#             out = np.array([t, d]).T
#         else:
#             out = np.array([t, d, e]).T
#         np.savetxt(fname, out, fmt='%15f')
# 
# def write_lc_filters(filters_masks, filternames, hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
#     if isinstance(filters_masks, dict):
#         filters_masks = [filters_masks[f] for f in filternames]
#     filters_masks = np.array(filters_masks, dtype=bool)
# 
#     for i, mask in enumerate(filters_masks):
#         logging.info('Writing lc for Filter: {}'.format(filternames[i]))
#         s = '_' + filternames[i] + suffix
#         mhjd = hjd[mask]
#         mlc = lc[:, mask]
#         if lc_e is not None:
#             mlc_e = lc_e[:, mask]
#         else:
#             mlc_e = None
#         write_lc(mhjd, mlc, mlc_e, ids, min_obs, prefix, s)
# 
# Path: astwro/utils/TmpDir.py
# class TmpDir(PathLike):
#     """
#     instances of TmpDir keeps track and lifetime of temporary directory
#     """
#     path = None
#     dir_is_tmp = True
#     _prefix = ''
#     _base = None
# 
#     def __init__(self, use_existing=None, prefix='astwro_tmp_', base_dir=None):
#         """
#         :param str use_existing:    If provided, instance will point to that directory and not delete it on destruct
#         :param str prefix:          Prefix for temporary dir
#         :param str base_dir:        Where to crate tem dir, in None system default is used
#         """
#         self._prefix = prefix
#         self._base = base_dir
#         if use_existing is None:
#             self.path = mkdtemp(prefix=prefix, dir=base_dir)
#             self.dir_is_tmp = True
#         else:
#             self.path = use_existing
#             self.dir_is_tmp = False
# 
#     def clone(self):
#         return deepcopy(self)
# 
#     def __del__(self):
#         self._rm_dir()
# 
#     def __enter__(self):
#         return self
# 
#     def __exit__(self, type_, value, traceback):
#         self._rm_dir()
# 
#     def __repr__(self):
#         return ('Tmp dir:' if self.dir_is_tmp else 'Ext dir:') + (self.path if self.path else 'none')
# 
#     def __str__(self):
#         return self.path
# 
#     def __deepcopy__(self, memo):
#         cls = self.__class__
#         new = cls.__new__(cls)
#         memo[id(self)] = new
#         if self.dir_is_tmp:
#             new.__init__(prefix=self._prefix, base_dir=self._base)
#             shutil.rmtree(new.path)
#             shutil.copytree(self.path, new.path, symlinks=True)
#         else:
#             new.__init__(use_existing=self.path)
#         return new
# 
#     def __fspath__(self):
#         """Implements ``os.PathLike interface``"""
#         return str(self)
# 
#     def _rm_dir(self):
#         """Deletes working dir with all content."""
#         if self.dir_is_tmp:
#             try:
#                 shutil.rmtree(self.path)
#             except OSError:
#                 pass


# Path: astwro/phot/tests/dphot_test.py
from astwro.phot import *
from os.path import join
from astwro.phot.lc_io import write_lc, write_lc_filters
from astwro.utils import TmpDir
import numpy as np
import sys
    import os
    import pickle

    s, l, o, se, le, oe = dphot(d, e, c)
    dp = DiffPhot(d, e, c)
    assert  np.allclose(dp.mag, s)
    assert  np.allclose(dp.lc, l)
    assert  np.allclose(dp.obs_deltas, o)


    e = dp.err
    e2= e**2
    d = dp.obs_deltas_stddev
    d2 = d**2

    x =  (dp.mag, dp.mag_v2, dp.lc_e)
#    assert  np.allclose(dp.mag_e, se)



def test_write_lc():
    #TODO: Limit numer of stars in some_stars_data.pkl
    with TmpDir() as td:
        d, e, f = prepare_testset_real()
        hjd = np.linspace(989.34316, 1002.63264, d.shape[1])
        write_lc(hjd, d, e, prefix=join(td.path, 'lc_'))

def test_write_lc_filter():
    d, e, f = prepare_testset_real()
    hjd = np.linspace(989.34316, 1002.63264, d.shape[1])
    fn = ['B', 'Han']
    r = np.random.uniform(size=d.shape[1])
    fm = np.array([r<0.5, r>=0.5], dtype=bool)

    with TmpDir() as td: