Beispiel #1
0
class LVCskymap(object):
    """A set of methods for working with LVC healpix (3d) skymaps."""
    def __init__(self):

        self.user = UserValues()  #comp.
        self.skymap = self.user.get_skymap()
        print(self.skymap)  # TEST
        self.nside = self.user.get_nside()

        self.is_3d = Is3d(self.skymap)  #comp --> eredita
        self.tfield, self.header = self.is_3d.get_header()
        self.prob, self.distmu, self.distsigma, self.distnorm = self.is_3d.get_values(
            self.tfield)


##    def vertices(self, ra_center, dec_center, fov_base, fov_height):
##        """Finding the vertices of a FoV given the central location (ra[deg], dec[deg])
##           and the FoV size (FoV_base [deg], FoV_height [deg])."""
##
##        vert_ra, vert_dec = [], []  # ra list,  dec list
##
##        ra_center_rad, dec_center_rad = radians(ra_center), radians(dec_center)
##
##        fov_base_rad, fov_height_rad = radians(fov_base), radians(fov_height)
##
##        x = [-fov_base_rad/2, fov_base_rad/2,
##             fov_base_rad/2, -fov_base_rad/2]
##
##        y = [fov_height_rad/2, fov_height_rad/2,
##             -fov_height_rad/2, -fov_height_rad/2]
##
##        for i, j  in zip(x, y):
##            arg = -i/(cos(dec_center_rad)-j*sin(dec_center_rad))
##            v_ra = degrees( (ra_center_rad+atan(arg)) )
##
##            vert_ra.append(v_ra)
##
##            v_dec = degrees( (asin((sin(dec_center_rad)+j*cos(dec_center_rad))/(1+i**2+j**2)**0.5)) )
##
##            vert_dec.append(v_dec)
##
##        # test: field-of-view footprint vs vertices function
##        aladin.draw_circle(vert_ra[0], vert_dec[0], size = '15arsec')
##        aladin.draw_circle(vert_ra[1], vert_dec[1], size = '15arsec')
##        aladin.draw_circle(vert_ra[2], vert_dec[2], size = '15arsec')
##        aladin.draw_circle(vert_ra[3], vert_dec[3], size = '15arsec')
##
##        #print round(vert_ra[0],6), round(vert_dec[0],6), round(vert_ra[1],6), round(vert_dec[1],6),round(vert_ra[2],6), round(vert_dec[2],6), round(vert_ra[3],6), round(vert_dec[3],6)
##        print vert_ra[0], vert_ra[1], vert_ra[3], vert_ra[2], vert_dec[0], vert_dec[1], vert_dec[3], vert_dec[2]
##        return vert_ra[0], vert_ra[1], vert_ra[3], vert_ra[2], vert_dec[0], vert_dec[1], vert_dec[3], vert_dec[2]
##        print vert_ra[0], vert_ra[1], vert_ra[3], vert_ra[2], vert_dec[0], vert_dec[1], vert_dec[3], vert_dec[2]

    def vertices(self, ra_center, dec_center, fov_base, fov_height):
        """Finding the vertices of a FoV given the central location (ra[deg], dec[deg])
           and the FoV size (FoV_base [deg], FoV_height [deg])."""

        vert_ra, vert_dec = [], []  # ra list,  dec list

        ra_center_rad, dec_center_rad = radians(ra_center), radians(dec_center)

        fov_base_rad, fov_height_rad = radians(
            (fov_base + 0.00069) / 2.0), radians(
                (fov_height + 0.00069) / 2.0)  #0.0017119592190950605

        x = [-fov_base_rad, fov_base_rad, fov_base_rad, -fov_base_rad]

        y = [fov_height_rad, fov_height_rad, -fov_height_rad, -fov_height_rad]

        ##        Dato un FOV quadrato di lato L e orientato come dicevo nella mia mail precedente, es:
        ##       deg2rad=pi/180;
        ##
        ##      L=3*deg2rad;
        ##
        ##       In coord. ortogonali i vertici del quadrato in senso orario partendo da quello in alto a sx, assumendo
        #che l'origine sia nel punto centrale del FOV, sono:
        ##
        ##
        ##   X1=(-L/2,L/2,L/2,-L/2);
        ##
        ##    Y1=(L/2,L/2,-L/2,-L/2);
        ##
        ##
        ##In coord. angolari diventano:
        ##
        ##
        ##arg1=-X1/(cos(d0)-Y1*sin(d0));
        ##
        ##a1=(a0+atan(arg1))/deg2rad
        ##
        ##d1=(asin( (sin(d0)+Y1*cos(d0))/(1+X1.^2+Y1.^2).^0.5))/deg2rad
        ##
        ##dove (a0,d0) sono le coordinate del centro del FOV
        ##
        ##Ho fatto delle prove con Aladin e a me torna ma fai un check...

        for i, j in zip(x, y):
            arg = -i / (cos(dec_center_rad) - j * sin(dec_center_rad))
            v_ra = degrees((ra_center_rad + atan(arg)))

            vert_ra.append(v_ra)

            v_dec = degrees(
                (asin((sin(dec_center_rad) + j * cos(dec_center_rad)) /
                      (1 + i**2 + j**2)**0.5)))

            vert_dec.append(v_dec)

        # test: field-of-view footprint vs vertices function
        #aladin.draw_circle(vert_ra[0], vert_dec[0], size = '5arcmin')
        #aladin.draw_circle(vert_ra[1], vert_dec[1], size = '5arcmin')
        #aladin.draw_circle(vert_ra[2], vert_dec[2], size = '5arcmin')
        #aladin.draw_circle(vert_ra[3], vert_dec[3], size = '5arcmin')

        #print round(vert_ra[0],6), round(vert_dec[0],6), round(vert_ra[1],6), round(vert_dec[1],6),round(vert_ra[2],6), round(vert_dec[2],6), round(vert_ra[3],6), round(vert_dec[3],6)
        #print vert_ra[0], vert_ra[1], vert_ra[3], vert_ra[2], vert_dec[0], vert_dec[1], vert_dec[3], vert_dec[2]
        return vert_ra[0], vert_ra[1], vert_ra[3], vert_ra[2], vert_dec[
            0], vert_dec[1], vert_dec[3], vert_dec[2]
        #print vert_ra[0], vert_ra[1], vert_ra[3], vert_ra[2], vert_dec[0], vert_dec[1], vert_dec[3], vert_dec[2]

    def __ipix_sum(self, ra_vertices, dec_vertices):
        """Return the ipix sum inside a polygon."""

        theta = 0.5 * np.pi - np.deg2rad(dec_vertices)
        phi = np.deg2rad(ra_vertices)
        xyz = hp.ang2vec(theta, phi)

        ipix_poly = hp.query_polygon(self.nside, xyz)

        ipix_sum_polygon = self.prob[ipix_poly].sum()

        return ipix_sum_polygon

    def prob_in_box(self, ra, dec, width, height):
        """Return the probability inside a box."""

        v1_ra, v2_ra, v3_ra, v4_ra, v1_dec, v2_dec, v3_dec, v4_dec = self.vertices(
            ra, dec, width, height)

        ra_vertices, dec_vertices = ([v1_ra, v2_ra, v4_ra,
                                      v3_ra], [v1_dec, v2_dec, v4_dec, v3_dec])

        probability_fov_box = self.__ipix_sum(ra_vertices, dec_vertices)

        return '%.1e' % probability_fov_box

    def prob_in_circle(self, ra, dec, radius):
        """Return the probability inside a circle."""

        theta = 0.5 * np.pi - np.deg2rad(dec)
        phi = np.deg2rad(ra)
        radius = np.deg2rad(radius)

        xyz = hp.ang2vec(theta, phi)
        ipix_disc = hp.query_disc(self.nside, xyz, radius)
        probability_fov_disc = self.prob[ipix_disc].sum()

        return '%.1e' % probability_fov_disc

    def conditional_distance_linesight(self, ra, dec):
        """Conditional distance distribution along the line of sight of a FoV center:
            see https://arxiv.org/pdf/1605.04242v3.pdf - section 4.4 for more details."""

        if self.tfield == 4:  # 3d skymap
            theta = 0.5 * np.pi - np.deg2rad(dec)
            phi = np.deg2rad(ra)
            ipix = hp.ang2pix(self.nside, theta, phi)

            line_end = self.header['DISTMEAN'] + (self.header['DISTSTD'] * 4)
            r = np.linspace(0, line_end)
            dp_dr = r**2 * self.distnorm[ipix] * norm(
                self.distmu[ipix], self.distsigma[ipix]).pdf(r)

            return r, dp_dr
        else:
            r = "nan"
            dp_dr = "nan"

            return r, dp_dr
Beispiel #2
0
class Observability(Toplevel):
    """Initializi"""
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")

        self.user = UserValues()
        self.moc = MOC_confidence_region()

        self.observatory = astropy.coordinates.EarthLocation(
            lat=self.user.get_latitude() * u.deg,
            lon=self.user.get_longitude() * u.deg,
            height=self.user.get_altitude() * u.m)

        self.wait_visibility()
        self.wm_attributes('-alpha', 0.8)  # transparency

        self.title("Observability" + "starting from" +
                   self.user.get_obs_time())
        self.attributes("-topmost", True)

        self.bttn_clicks = 0  # counter ">>" Button

        # first label
        self.label_1 = Label(self,
                             text="Show the region in the",
                             bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, padx=0)

        moc_value = 90  # default
        moc_default = StringVar(self, value=moc_value)

        self.entry_percentage = Entry(self,
                                      width=5,
                                      justify=CENTER,
                                      textvariable=moc_default)
        self.entry_percentage.grid(row=0, padx=2, column=1)

        # second label
        self.label_2 = Label(self,
                             text="% MOC in which the airmass is ≤",
                             bg="slate grey")
        self.label_2.grid(row=0, column=2, sticky=E, pady=0)

        airmass_value = "2.5"  # default
        airmass_default = StringVar(self, value=airmass_value)

        self.entry_airmass = Entry(self,
                                   width=5,
                                   justify=CENTER,
                                   textvariable=airmass_default)
        self.entry_airmass.grid(row=0, padx=2, column=3)

        #Btn
        self.show = Button(self, text='Show', command=self.moc_obs)
        self.show.grid(column=4, row=0, sticky=W, padx=2, pady=5)

        #self.moon = Button(self, text="Sun/Moon",
        #                    command=self.close_window)
        #self.moon.grid(column=5,row=0, sticky=W, padx=2, pady=5)

        self.forward = Button(self, text=">>", command=self.moc_obs_update)
        self.forward.grid(column=6, row=0, sticky=E, padx=2, pady=5)

        self.close = Button(self, text="Close", command=self.close_window)
        self.close.grid(column=7, row=0, sticky=E, padx=2, pady=5)

    #Actions
    def update_count(self):
        """Return the time in step of 1h when the button ">>" is clicked."""

        self.bttn_clicks += 1

        dt = TimeDelta(3600.0, format='sec')
        update_time = int(self.bttn_clicks) * dt

        obs_time = Time(self.user.get_obs_time())
        time_update = obs_time + update_time

        return time_update

    def from_ipixs_to_moc(self, time_input):
        """Return ipix table with the associated airmass"""

        prob = self.moc.read_prob(self.user.get_skymap())
        percentage = float(self.entry_percentage.get()) / 100.0
        ipixs = self.moc.ipixs_in_percentage(prob, percentage)
        nside = int(self.user.get_nside())
        ra, dec = self.moc.sky_coords(ipixs, nside)

        sky_coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg, frame='icrs')
        altaz = sky_coord.transform_to(
            AltAz(obstime=time_input, location=self.observatory))
        airmass_values = altaz.secz

        contour_ipix = Table([ra, dec, airmass_values, ipixs],
                             names=('RA[deg]', 'DEC[deg]', 'airmass', 'ipix'),
                             meta={'ipix': 'ipix table'})  # astropy table

        mask = (contour_ipix['airmass']) >= 1  # clearing
        obs1 = contour_ipix[mask]

        mask2 = (obs1['airmass']) <= float(
            self.entry_airmass.get())  # airmass user values
        obs = obs1[mask2]

        # test
        print obs

        nside = self.user.get_nside()

        if len(obs) == 0:
            tkMessageBox.showinfo('MOC visibility',
                                  'No region for the selected  airmass')
        else:
            moc_order = self.moc.moc_order(nside)
            moc = MOC.from_table(obs, 'RA[deg]', 'DEC[deg]',
                                 moc_order)  # moc creation
            moc.write('obs_airmass_', format='fits')  # fit file

            return aladin.send_file('obs_airmass_')

    def moc_obs(self):
        """Return the MOC region in which the airmass is <= the airmass value defined by the user."""

        time_start = self.user.get_obs_time()
        contour_ipix = self.from_ipixs_to_moc(time_start)

        percentage = float(self.entry_percentage.get()) / 100.0
        aladin.rename('obs_airmass_' + self.entry_airmass.get() + 'MOC_' +
                      str(percentage))

        # test
        print time_start

    def moc_obs_update(self):
        """Return the MOC region in which the airmass is <= the airmass value defined by the user."""

        time_update = self.update_count()
        contour_ipix = self.from_ipixs_to_moc(time_update)

        percentage = float(self.entry_percentage.get()) / 100.0
        aladin.rename('obs_airmass_' + self.entry_airmass.get() + 'MOC_' +
                      str(percentage) + '@' + str(time_update.isot))

        # test
        print time_update

    def close_window(self):
        self.destroy()
Beispiel #3
0
class Pinpoint(Toplevel):
    """The class is designed to determine in which level of probability a source is localized."""

    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")
        
        # get trasparency windows from global variable
        self.wait_visibility()
        self.wm_attributes('-alpha', trasparency)   

        self.title(" Pinpoint Localization")
        self.attributes("-topmost", True)

        # label 1
        self.label_1 = Label(self,
                             text=" In which level of probability the source(s) falls/fall", bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, pady=0)

        # showing example entries
        help_string = ("source_3 085.91935 +33.34139; source_4 073.87703 +23.36612 ")
        
        help_string_default = StringVar(self, value=help_string) 
        self.entry_pin = Entry(self, width=30, justify=CENTER,
                             textvariable=help_string_default)
        self.entry_pin.grid(row=0, padx=15, column=1)

        # label 2
        self.label_2 = Label(self, text=" from  ", bg="slate grey")
        self.label_2.grid(row=0, column=3, sticky=E, pady=0) 

        from_default = StringVar(self, value="10") # default

        self.entry_from = Entry(self, width=5, justify=CENTER,
                                textvariable=from_default)
        self.entry_from.grid(row=0, column=4, columnspan=8, pady=2, sticky='WE')

        # label 3
        self.label_3 = Label(self, text=" to  ", bg="slate grey")
        self.label_3.grid(row=0, column=20, sticky=E, pady=0) 

        to_default = StringVar(self, value="90") # default

        self.entry_to = Entry(self, width=5, justify=CENTER,
                                textvariable=to_default)
        self.entry_to.grid(row=0, column=25, columnspan=8, pady=2, sticky='WE')

        # label 4
        self.label_4 = Label(self, text=" grid  ", bg="slate grey")
        self.label_4.grid(row=0, column=40, sticky=E, pady=0) 

        grid_default = StringVar(self, value="10") # default

        self.entry_grid = Entry(self, width=5, justify=CENTER,
                                textvariable=grid_default)
        self.entry_grid.grid(row=0, column=45, columnspan=8, pady=2, sticky='WE')

        # label 4
        folder = "pinpoint"  # default     
        folder_default = StringVar(self, value=folder)
        
        self.entry_folder = Entry(self, width=20, justify=CENTER,
                             textvariable=folder_default)
        self.entry_folder.grid(row=1, padx=2, column=0)

        # label 3.1
        self.label_3 = Label(self, text="  Folder:",justify=LEFT,
                             bg="slate grey")
        self.label_3.grid(row=1, column=0, sticky=W, pady=0)
        
        self.entryScroll = Scrollbar(self, orient=HORIZONTAL,
                                     command=self.__scrollHandler)
        self.entryScroll.grid(row=1, column=1, sticky=E+W)
        self.entry_pin['xscrollcommand'] = self.entryScroll.set

        # -------------Btns--------------#

        # Do
        self.show = Button(self, text='Do',
                           command=self.pinpoint_for)
        self.show.grid(column=55, row=0, sticky=W, padx=2, pady=5)

        # Close
        self.close = Button(self, text="Close",
                            command=self.close_window)  
        self.close.grid(column=70,row=0, sticky=W, padx=2, pady=5)
        
    #Actions
    def __scrollHandler(self, *L):
        """Scroll entry."""
       
        op, howMany = L[0], L[1]

        if op == 'scroll':
            units = L[2]
            self.entry_pin.xview_scroll(howMany, units)
        elif op == 'moveto':
            self.entry_pin.xview_moveto(howMany)
          
    def __split_entries_3(self):
        """Splitting the entries in 'id source', 'ra' and 'dec'."""
        
        entry_sources = self.entry_pin.get().replace(';',' ').replace(',',' ').split()
                                                          # TRY TO DO BETTER: numpy!!!
        # defined lists
        label = entry_sources[::3]
        source_ra = entry_sources[1::3]
        source_dec = entry_sources[2::3]

        # Check if the lists are of the same length
        if len(label)==len(source_ra)==len(source_dec):
            return label[0::], source_ra[0::], source_dec[0::]
        else:
            msg_err = 'ENTER: id source ra[deg] dec[deg]'
            MSG.split_entries_3(msg_err)
    
    def pinpoint_for(self):
        """Finding in which confidence level the sources fall.
           List of sources are inserted in 'self.entry_pin'."""

        aladin.md(self.entry_folder.get()) # creating folder defined by user
        aladin.remove(self.entry_folder.get() + '~1') # removing multiple copy of the folder
                                                       ## TRY TO DO BETTER!!!!
        # splitting the entries
        labels, ra_transients, dec_transients = self.__split_entries_3()
        
        for ra_transient, dec_transient, label in zip(
            ra_transients, dec_transients, labels):

            # aladin stack organization: draw source position/move in folder                       
            aladin.draw_newtool(label)
            aladin.draw_source(ra_transient, dec_transient, label)
            aladin.mv(label, self.entry_folder.get()) 

            try:
                self.pinpoint(ra_transient, dec_transient, label)
            except ValueError as value_error:
                MSG.value_error(value_error)
            
    def pinpoint(self, ra_transient, dec_transient, label):        
        """Finding in which confidence level the source falls.
        
        Input parameters
        ---------------
        ra_transient, dec_transient : float
              sky coordinates in degrees
        label : string
              id source transient
        """
        
        # (re)initialization: skymap/nside
        self.user = UserValues()
        skymap = self.user.get_skymap() 
        nside = int(self.user.get_nside())

        # getting probability array
        prob = moc.read_prob(skymap)

        # user input values: from/to/resolution
        from_percentage = float(self.entry_from.get())/100.0
        to_percentage = float(self.entry_to.get())/100.0
        resolution_percentage = float(self.entry_grid.get())/100.0

        # from sky coords to ipix
        ipix = healpixIpix.find_ipix(ra_transient, dec_transient,
                                     nside)            

        find = "n"         
        while from_percentage <= to_percentage or find =="y":
            ipixs = moc.ipixs_in_percentage(prob, from_percentage)        
            is_there = ipix in ipixs  # is the ipix within the MOC contour plot defined by user?
            
            if is_there != True: # ipix not found                            
                from_percentage = from_percentage + resolution_percentage                
            else:
                find = "y"  # ipix found    
                res_yes = ("The sky coord" + " " + "ra="+str(ra_transient)+"°," + ' ' + "dec="+str(dec_transient)+"°"+" " + "(label:" + label+")" \
                           "lies within the" + " " + str(from_percentage*100)+'%' + " " + "c.l.\n" +"["+skymap+"]")
                MSG.pinpoint_find(label, res_yes)

                return find
            
        # ipix not found [from_percentage -- to_percentage]
        from_percentage = to_percentage
        
        res_no = ("The sky coord" + " " + "ra="+str(ra_transient)+"°," + ' '
                 + "dec="+str(dec_transient)+"°"+" " + "(label:" + label+")" \
                 + " " + "is not localized within the" + " " + str(from_percentage*100)+'%' + " " + "c.l.\n" +"["+skymap+"]")

        MSG.pinpoint_nofind(label, res_no)
                           
    def close_window(self):
        """Closing window"""
        
        return self.destroy()
Beispiel #4
0
class LocalizeSources(Toplevel):
    """The class is designed to answer if an astrophysical source falls within a
        specific level of probability (MOC contour plot)."""
    
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")

        # get trasparency windows from global variable
        self.wait_visibility()
        self.wm_attributes('-alpha', trasparency)   

        self.title(" Localize Sources in probability skymap")
        self.attributes("-topmost", True)

        # label 1
        self.label_1 = Label(self, text="Is/Are the [ID Source(s) RA (°) DEC (°)]",
                             bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, pady=0)

        # showing example entries
        help_string = ("source_1 079.91935 +43.34139; source_2 063.87703 +33.36612 ")
        
        help_string_default = StringVar(self, value=help_string) 
        self.entry_sources = Entry(self, width=30, justify=CENTER,
                             textvariable=help_string_default)
        self.entry_sources.grid(row=0, padx=15, column=1)

        # label 2
        self.label_2 = Label(self, text="whithin the", bg="slate grey")
        self.label_2.grid(row=0, column=3, sticky=E, pady=0)

        moc_value = 90  # default     
        moc_default = StringVar(self, value=moc_value)
        
        self.entry_percentage = Entry(self, width=5, justify=CENTER,
                             textvariable=moc_default)
        self.entry_percentage.grid(row=0, padx=2, column=5)

        # label 3
        self.label_2 = Label(self, text="% MOC?  ",
                             bg="slate grey")
        self.label_2.grid(row=0, column=6, sticky=E, pady=0)

        # label 4
        folder = "transients"  # default     
        folder_default = StringVar(self, value=folder)
        
        self.entry_folder = Entry(self, width=15, justify=CENTER,
                             textvariable=folder_default)
        self.entry_folder.grid(row=1, padx=2, column=0)

        # label 3.1
        self.label_3 = Label(self, text="  Folder: ",justify=LEFT,
                             bg="slate grey")
        self.label_3.grid(row=1, column=0, sticky=W, pady=0)

        self.entryScroll = Scrollbar(self, orient=HORIZONTAL,
                                     command=self.__scrollHandler)
        self.entryScroll.grid(row=1, column=1, sticky=E+W)
        self.entry_sources['xscrollcommand'] = self.entryScroll.set

        # -------------Btns--------------#

        # Ask
        self.show = Button(self, text='Ask',
                           command=self.in_skymap)
        self.show.grid(column=7, row=0, sticky=W, padx=2, pady=5)

        # Pinpoint
        self.checkbox = Button(self, text="Pinpoint", fg='black',     
                               command=self.pinpoint)
        self.checkbox.grid(column=8,row=0, sticky=E, padx=2, pady=5)

        # Dist
        self.checkbox = Button(self, text="Dist", fg='black',     
                               command=self.cond_distance_source_for)
        self.checkbox.grid(column=15,row=0, sticky=E, padx=2, pady=5)

        # Close
        self.close = Button(self, text="Close",
                            command=self.close_window)  
        self.close.grid(column=25,row=0, sticky=W, padx=2, pady=5)

    #Actions
    def __scrollHandler(self, *L):
        """Scroll entry."""
       
        op, howMany = L[0], L[1]

        if op == 'scroll':
            units = L[2]
            self.entry_sources.xview_scroll(howMany, units)
        elif op == 'moveto':
            self.entry_sources.xview_moveto(howMany)
           
    def __split_entries_3(self):
        """Splitting the entries in 'id source', 'ra' and 'dec'."""
        
        entry_sources = self.entry_sources.get().replace(';',' ').replace(',',' ').split()

        # defined lists
        label = entry_sources[::3]
        source_ra = entry_sources[1::3]
        source_dec = entry_sources[2::3]

        # Check if the lists are of the same length
        if len(label)==len(source_ra)==len(source_dec):

            return label[0::], source_ra[0::], source_dec[0::]
        else:
            msg_err = 'ENTER: id source ra[deg] dec[deg]'
            MSG.split_entries_3(msg_err)
                              
    def in_skymap(self):
        """Checking if an object falls in a given probability level defined by an user.
           List of sources are inserted in 'self.entry_sources'."""

        aladin.md(self.entry_folder.get()) # creating folder defined by user
        aladin.remove(self.entry_folder.get() + '~1') # removing multiple copy of the folder
                                                      # TO DO BETTER
        # (re)initialization: skymap/nside
        self.user = UserValues()
        skymap = self.user.get_skymap()
        nside = int(self.user.get_nside())

        # getting probability array
        prob = moc.read_prob(skymap)

        # user input: MOC confidence level in percentage
        percentage = float(self.entry_percentage.get())/100.0

        # splitting the entries              
        labels, ra_transients, dec_transients = self.__split_entries_3()       
      
        for ra_transient, dec_transient, label in zip(
           ra_transients, dec_transients, labels):

            # aladin stack organization: draw source position/move in folder
            aladin.draw_newtool(label)
            aladin.draw_source(ra_transient, dec_transient, label)
            aladin.mv(label, self.entry_folder.get())

            # from sky coords to ipix
            ipixs = moc.ipixs_in_percentage(prob, percentage)
            
            try:
                ipix = healpixIpix.find_ipix(ra_transient, dec_transient,
                                             nside)
            
                is_there = ipix in ipixs  # is the ipix within the MOC contour plot defined by user?

                if is_there is True: # ipix found
                    res_true = ("The sky coord" + " " + "ra="+str(ra_transient)+"°," + " " + "dec="+str(dec_transient)+"°" + " " + \
                                "(labels: " + label+")" + " " +  "lies within the" + " " + str(percentage*100)+'%' + " " + "c.l.\n" +"["+skymap+"]")
                    MSG.in_skymap_true(label, res_true)
                else:
                    res_false = ("The sky coord" + " " + "ra="+str(ra_transient)+"°," + " " +"dec="+str(dec_transient)+"°" + " " + \
                                 "(labels: " + label+")" + " " + "is outside the" + " " + str(percentage*100)+'%' + " " + "c.l.\n" + "["+skymap+"]")
                    MSG.in_skymap_false(label, res_false)

            except ValueError as value_error:
                MSG.value_error(value_error)

    def pinpoint(self):
        """Initialize Pinpoint class."""
        
        pinpoint_localize = Pinpoint()
        return pinpoint_localize

    def cond_distance_source_for(self):
        """Plot of the conditional distance distribution  along the line of sight for a list of sources."""
        
        self.lvc = LVCskymap() # basic module for handling LVC skymaps
        
        labels, ra_transients, dec_transients = self.__split_entries_3()
        
        plt.ion()
        for label, ra_transient, dec_transient in zip(
            labels, ra_transients, dec_transients):

           try:
               r, dp_dr = self.lvc.conditional_distance_linesight(
                   float(ra_transient), float(dec_transient))
           
               self.__cond_distance_source(label, r, dp_dr)
               
           except ValueError as value_error:
               MSG.value_error(value_error)          

    def __cond_distance_source(self, label, r, dp_dr):
        """Plot of the conditional distance distribution  along the line of sight."""
        
        # (re)initialization: skymap
        self.user = UserValues() 
        skymap=self.user.get_skymap()
        
        fig, ax = plt.subplots()

        ax.plot(r, dp_dr)
        title_string = label + ':' + ' '+ ' \n conditional distance distribution along the line of sight \n' + '['+skymap+']'
        ax.set_title(title_string,fontsize=10)
        ax.set_xlabel('distance (Mpc)')
        ax.set_ylabel('prob Mpc$^{-1}$')

        plt.show()

    def close_window(self):
        """Closing window"""
        
        return self.destroy()
class Observability(Toplevel):
    """Initializi"""

    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")
        
        self.user = UserValues()
        self.moc = MOC_confidence_region()

        self.observatory = astropy.coordinates.EarthLocation(
           lat=self.user.get_latitude()*u.deg, lon=self.user.get_longitude()*u.deg,
           height=self.user.get_altitude()*u.m)

        self.wait_visibility()
        self.wm_attributes('-alpha',0.8) # transparency

        self.title("Observability" + "starting from" + self.user.get_obs_time())
        self.attributes("-topmost", True)

        self.bttn_clicks = 0 # counter ">>" Button
        
        # first label
        self.label_1 = Label(self, text="Show the region in the",
                             bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, padx=0)

        moc_value = 90  # default     
        moc_default = StringVar(self, value=moc_value)
        
        self.entry_percentage = Entry(self, width=5, justify=CENTER,
                             textvariable=moc_default)
        self.entry_percentage.grid(row=0, padx=2, column=1)

        # second label
        self.label_2 = Label(self, text="% MOC in which the airmass is ≤",
                             bg="slate grey")
        self.label_2.grid(row=0, column=2, sticky=E, pady=0)

        airmass_value = "2.5" # default
        airmass_default = StringVar(self, value=airmass_value)
        
        self.entry_airmass = Entry(self, width=5, justify=CENTER,
                             textvariable=airmass_default)
        self.entry_airmass.grid(row=0, padx=2, column=3)

        #Btn
        self.show = Button(self, text='Show',
                           command=self.moc_obs)
        self.show.grid(column=4, row=0, sticky=W, padx=2, pady=5)
        
        #self.moon = Button(self, text="Sun/Moon",
        #                    command=self.close_window)  
        #self.moon.grid(column=5,row=0, sticky=W, padx=2, pady=5) 
        
        self.forward = Button(self, text=">>",      
                               command=self.moc_obs_update)
        self.forward.grid(column=6,row=0, sticky=E, padx=2, pady=5)

        self.close = Button(self, text="Close",
                            command=self.close_window)  
        self.close.grid(column=7,row=0, sticky=E, padx=2, pady=5)


    #Actions
    def update_count(self):
        """Return the time in step of 1h when the button ">>" is clicked."""
   
        self.bttn_clicks += 1
              
        dt = TimeDelta(3600.0, format='sec')
        update_time = int(self.bttn_clicks) * dt
        
        obs_time = Time(self.user.get_obs_time())
        time_update = obs_time + update_time
        
        return time_update

    def from_ipixs_to_moc(self, time_input):
        """Return ipix table with the associated airmass"""

        prob = self.moc.read_prob(self.user.get_skymap())       
        percentage = float(self.entry_percentage.get())/100.0    
        ipixs = self.moc.ipixs_in_percentage(prob, percentage )
        nside = int(self.user.get_nside())       
        ra, dec = self.moc.sky_coords(ipixs, nside)
        
        sky_coord = SkyCoord(ra = ra*u.deg,dec=dec*u.deg, frame='icrs')
        altaz = sky_coord.transform_to(AltAz(obstime=time_input, location=self.observatory))
        airmass_values = altaz.secz
        
        contour_ipix = Table([ ra, dec, airmass_values, ipixs ],
                             names = ('RA[deg]', 'DEC[deg]', 'airmass', 'ipix'),
                             meta = {'ipix': 'ipix table'})             # astropy table       

        mask = (contour_ipix['airmass']) >= 1 # clearing
        obs1 = contour_ipix[mask]

        mask2 = (obs1['airmass']) <= float(self.entry_airmass.get())  # airmass user values
        obs = obs1[mask2]

        # test
        print obs
        
        nside = self.user.get_nside()

        if len(obs)==0:
            tkMessageBox.showinfo('MOC visibility',
                                  'No region for the selected  airmass')
        else:
            moc_order = self.moc.moc_order(nside)
            moc = MOC.from_table( obs, 'RA[deg]', 'DEC[deg]',
                                  moc_order )                # moc creation
            moc.write( 'obs_airmass_', format = 'fits' )     # fit file
            
            return aladin.send_file('obs_airmass_')
      
    def moc_obs(self):
        """Return the MOC region in which the airmass is <= the airmass value defined by the user."""

        time_start = self.user.get_obs_time()
        contour_ipix = self.from_ipixs_to_moc(time_start)

        percentage = float(self.entry_percentage.get())/100.0 
        aladin.rename('obs_airmass_'+self.entry_airmass.get()+'MOC_'+str(percentage))

        # test
        print time_start

    def moc_obs_update(self):
        """Return the MOC region in which the airmass is <= the airmass value defined by the user."""

        time_update = self.update_count()
        contour_ipix = self.from_ipixs_to_moc(time_update)

        percentage = float(self.entry_percentage.get())/100.0  
        aladin.rename('obs_airmass_'+self.entry_airmass.get()+'MOC_'+str(percentage)+ '@' + str(time_update.isot))

        # test
        print time_update

    def close_window(self):
        self.destroy()