def make_histogram_vars(simlib, all_KN):

    #Creates list of all pointings with [LIBID, RA, DECL, MJD IDEXPT FLT GAIN NOISE SKYSIG (pixels)  RATIO  ZPTAVG ZPTERR  MAG]
    libid_details, pointings = parse_simlib(simlib)
    print 'Number of LSST pointings: ', len(pointings)

    if all_KN == 'no':

        DIR = '/data/des41.b/data/SNDATA_ROOT/SIM/GW170817_AT2017gfo_LSST_WFD/'
        #get KN locations of simulated events in snana
        file_count = len(
            [f for f in os.walk(DIR).next()[2] if f[-4:] == ".DAT"])
        KN_locations = np.zeros([file_count, 3])

        # run through all .dat files in the specified directory and get time and location of KN
        file_num = 0
        for file in os.listdir(DIR):
            if file.endswith(".DAT"):
                obs, headerdict = parse_observations(DIR + file)
                KN_locations[file_num, :] = [
                    headerdict['PEAKMJD'], headerdict['RA'], headerdict['DECL']
                ]
                file_num += 1
        print 'Number of KN observed by snana: ', len(KN_locations)

    elif all_KN == 'yes':

        KN_locations = findall_KN()

    else:
        print 'Invalid choice entry for all_KN'

    #get time taken until observed for all KN
    time_taken = np.zeros(len(KN_locations))
    time_taken[:] = np.nan
    for i, KN in enumerate(KN_locations):
        if i % 50 == 0:
            print i

        #get pointings in the next week
        pointings_later = pointings[KN[0] < pointings[:, 3], :]
        pointings_nextweek = pointings_later[pointings_later[:,
                                                             3] < (KN[0] + 7)]
        if len(pointings_nextweek) == 0:  #if no pointings in the next 24hrs
            continue

        #get angles between all of pointings and KN
        kilonova_loc = SkyCoord(ra=KN[1] * u.degree, dec=KN[2] * u.degree)
        pointings_locs = SkyCoord(ra=pointings_nextweek[:, 1] * u.degree,
                                  dec=pointings_nextweek[:, 2] * u.degree)
        angsep = kilonova_loc.separation(pointings_locs).deg
        observations_arg = np.argwhere(angsep < np.sqrt(9.6 / np.pi))
        if len(observations_arg) == 0:
            continue
        mjd_observed = pointings_nextweek[observations_arg[0], :][0][3]

        time_taken[i] = mjd_observed - KN[0]

    return time_taken, KN_locations
import numpy as np
from astropy import units as u
from astropy.coordinates import SkyCoord
import random
#import os


from python_utilities.des_io import parse_observations
from parse_simlib import parse_simlib

libid_details, pointings = parse_simlib('../LSST_WFD_COADD.SIMLIB')
#libid_details islist with each row giving ['LIBID:', 'RA:', 'DECL:', 'NOBS:', 'MWEBV:', 'PIXSIZE:', 'first observation index', 'last observation index']


def find_ang_sep(RA1, DECL1, RA2, DECL2): #all inputs and output are in degrees and are floats
    event1 = SkyCoord(ra=float(RA1) * u.degree, dec=float(DECL1) * u.degree)
    event2 = SkyCoord(ra=float(RA2) * u.degree, dec=float(DECL2) * u.degree)
    angsep = event1.separation(event2)
    return angsep.deg


def get_timelocation(datfile):
    obs, headerdict = parse_observations(datfile)
    SIM_PEAKMJD = float(headerdict['SIM_PEAKMJD'])
    RA = float(headerdict['RA'])
    DECL = float(headerdict['DECL'])
    return SIM_PEAKMJD, RA, DECL


def day_min_separation(SIM_PEAKMJD, RA, DECL, band): #RA and DECL both in degrees
#returns the minimum angular separation and the details of the closest observation in the given band in the next 24 hours after the peakMJD
import numpy as np
import matplotlib.pyplot as plt

from parse_simlib import parse_simlib

libid_details, pointings = parse_simlib('../minion_1016_WFD.simlib')

bands = ['u', 'g', 'r', 'i', 'z', 'Y']

#map bands onto numbers to we can put list of pointings into a np array and convert all strings into floats
for row in range(len(pointings)):
    for num, band in enumerate(bands):
        if pointings[row][5] == band:
            pointings[row][5] = num
    pointings[row] = [float(i) for i in pointings[row]
                      ]  #turn all entries in list into floats
    pointings[row][0], pointings[row][4], pointings[row][5] = int(
        pointings[row][0]), int(pointings[row][4]), int(
            pointings[row][5])  #some values take integers only e.g. libid

pointings_arr = np.array(pointings)
pointings_arr = pointings_arr[pointings_arr[:,
                                            3].argsort()]  #sort in time order

print pointings_arr[0:10]

#check mjd is rising
# x = np.arange(0,len(pointings_arr))
# fig3 = plt.figure()
# plt.plot(x,pointings_arr[:,3], alpha=0.5)
# plt.show()