示例#1
0
    def __init__(self, infile_coords='GWsky_coords'):
        """Creating a class in which the instance attributes are based on the dictionary
       "GWsky_coords" by default. GWsky_coords is created and pickled by the "user_values"
       module and will be deleted when the "ShowSkyCoverageGUI" will be closed.
       It contains the keys: "ra", "dec". ra and dec represents the central location of a FoV. 
        
        Starting sky coordinates:
             self.input_ra: right ascension [deg]
             self.input_dec: declination [deg]
         """

        self.infile_coords = infile_coords
        self.entries_GWsky_new = []  # new entries during the FoV sequence

        self.user = UserValues()  # compositions
        self.lvc = LVCskymap()
        self.query = Query()
        self.airmass = Airmass()
        self.moon = Moon()

        with open(infile_coords, 'rb') as data:
            coords_GWsky = pickle.load(data)

        for k, v in coords_GWsky.items():
            setattr(self, k, v)
示例#2
0
def paste_xforms():
    store = UserValues()
    selected = general.get_names_of_selected_objects()[0]
    if selected is None:
        general.message_box_ok("Please Select an object")
    xforms = store.get("xforms")
    general.set_position(selected, xforms['pos'][0], xforms['pos'][1], xforms['pos'][2])
    general.set_rotation(selected, xforms['rot'][0], xforms['rot'][1], xforms['rot'][2])
    general.set_scale(selected, xforms['scale'][0], xforms['scale'][1], xforms['scale'][2])
示例#3
0
def copy_xforms():
    store = UserValues()
    selected = general.get_names_of_selected_objects()[0]
    if selected is None:
        general.message_box_ok("Please Select an object")
    rot = general.get_rotation(selected)
    pos = general.get_position(selected)
    scale = general.get_scale(selected)
    store.set("xforms", {"rot": rot, "pos": pos, "scale": scale})
示例#4
0
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")

        self.user = UserValues()

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

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

        # 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="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.close_window)
        #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)
示例#5
0
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")

        self.user = UserValues()

        # putting the entry value(s) in a list
        self.entries_GWsky = []

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

        self.title(" Starting FoV")
        self.attributes("-topmost", True)

        self.label_1 = Label(self, text="RA (°) DEC (°)", bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, pady=0)

        # default: sky coords of maximum probability pixel
        fov_coords = str(self.user.get_ra_max_pixel()), str(
            self.user.get_dec_max_pixel())

        max_pixel_default = StringVar(self, value=fov_coords)
        self.entry_1 = Entry(self,
                             width=30,
                             justify=CENTER,
                             textvariable=max_pixel_default)

        self.entry_1.grid(row=0, padx=15, column=1)

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

        #Btn

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

        self.checkbox = Button(self,
                               text="Not show",
                               command=self.no_show_starting_fov)
        self.checkbox.grid(column=3, row=0, sticky=E, padx=2, pady=5)

        self.close = Button(self,
                            text="Obs",
                            fg='dark green',
                            command=self.obs)
        self.close.grid(column=4, row=0, sticky=W, padx=2, pady=5)

        self.close = Button(self, text="Close", command=self.close_window)
        self.close.grid(column=5, row=0, sticky=E, padx=2, pady=5)
 def __init__(self, infile_coords='GWsky_coords'):
     """Creating a class in which the instance attributes are based on the dictionary
    "GWsky_coords" by default. GWsky_coords is created and pickled by the "user_values"
    module and will be deleted when the "ShowSkyCoverageGUI" will be closed.
    It contains the keys: "ra", "dec". ra and dec represents the central location of a FoV. 
     
     Starting sky coordinates:
          self.input_ra: right ascension [deg]
          self.input_dec: declination [deg]
      """
    
     self.infile_coords = infile_coords
     self.entries_GWsky_new =[] # new entries during the FoV sequence
     
     self.user = UserValues() # compositions
     self.lvc = LVCskymap()
     self.query = Query()
     self.airmass = Airmass()
     self.moon = Moon()
     
     with open(infile_coords, 'rb') as data:  
         coords_GWsky = pickle.load(data)
         
     for k, v in coords_GWsky.items():          
         setattr(self, k, v)
示例#7
0
def add_embellishment():
    io = IconObjectDB()
    store = UserValues()
    obj = get_icon_object_in_scene()
    obj['embellishment_48'] = ''
    obj['embellishment_200'] = ''
    obj['embellishment_2048'] = ''
    save()
示例#8
0
def add_to_scene(obj):
    print("Adding: " + obj["name"])
    store = UserValues(init_funcs=[init_screenshot_values])
    store.set("current_icon_object", obj)
    ico_obj = "icon_object_shot"
    ico_obj_2 = "icon_object_shot_2"
    # update our ico_obj based on the settings from the collected icon_object
    general.set_position(ico_obj, obj["pos"][0], obj["pos"][1], obj["pos"][2])
    general.set_scale(ico_obj, obj["scale"][0], obj["scale"][1], obj["scale"][2])
    general.set_rotation(ico_obj, obj["rot"][0], obj["rot"][1], obj["rot"][2])
    general.set_entity_geometry_file(ico_obj, str(obj["brush"]))
    general.select_object(ico_obj)
    material.reset_selection()
    if obj["mtl"] is not None:
        general.set_custom_material(ico_obj, str(obj["mtl"]))
    if "tod" in obj.keys():
        tod_list = [str("e_TimeOfDay %s" % obj["tod"])]
        cycleConsolValue("mode_%s" % "e_TimeOfDay", tod_list)
示例#9
0
def add_to_scene(obj):
    print("Adding: " + obj["name"])
    store = UserValues(init_funcs=[init_screenshot_values])
    store.set("current_icon_object", obj)
    ico_obj = "icon_object_shot"
    ico_obj_2 = "icon_object_shot_2"
    # update our ico_obj based on the settings from the collected icon_object
    general.set_position(ico_obj, obj["pos"][0], obj["pos"][1], obj["pos"][2])
    general.set_scale(ico_obj, obj["scale"][0], obj["scale"][1],
                      obj["scale"][2])
    general.set_rotation(ico_obj, obj["rot"][0], obj["rot"][1], obj["rot"][2])
    general.set_entity_geometry_file(ico_obj, str(obj["brush"]))
    general.select_object(ico_obj)
    material.reset_selection()
    if obj["mtl"] is not None:
        general.set_custom_material(ico_obj, str(obj["mtl"]))
    if "tod" in obj.keys():
        tod_list = [str("e_TimeOfDay %s" % obj["tod"])]
        cycleConsolValue("mode_%s" % "e_TimeOfDay", tod_list)
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")
        
        self.user = UserValues()

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

        self.title("Observability" + "@" + self.user.get_obs_time())
        self.attributes("-topmost", True)
        
        # 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="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.close_window)
        #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)
示例#11
0
def get_icon_object_in_scene():
    try:
        store = UserValues()
        io = IconObjectDB()
    except ValueError as val_err:
        general.message_box_ok(str(val_err))
        return None
    store_obj = store.get("current_icon_object")
    if store_obj:
        print('Returning Stored Object from User Values')
        print(store_obj)
        return store_obj
    # if we can't find a stored version try and find it
    if not store_obj:
        general.select_object("icon_object_shot")
        obj = io.get_obj_by_brush_and_mtl(
            lodtools.getselected().lower(),
            general.get_assigned_material("icon_object_shot"),
        )
        if obj:
            return obj
    # object was not set in store and is not set in io_db
    return None
示例#12
0
def get_icon_object_in_scene():
    try:
        store = UserValues()
        io = IconObjectDB()
    except ValueError as val_err:
        general.message_box_ok(str(val_err))
        return None
    store_obj = store.get("current_icon_object")
    if store_obj:
        print('Returning Stored Object from User Values')
        print(store_obj)
        return store_obj
    # if we can't find a stored version try and find it
    if not store_obj:
        general.select_object("icon_object_shot")
        obj = io.get_obj_by_brush_and_mtl(
            lodtools.getselected().lower(),
            general.get_assigned_material("icon_object_shot"),
        )
        if obj:
            return obj
    # object was not set in store and is not set in io_db
    return None
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")
        
        self.user = UserValues()

        # putting the entry value(s) in a list
        self.entries_GWsky=[]  

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

        self.title(" Starting FoV")
        self.attributes("-topmost", True)
        
        self.label_1 = Label(self, text="RA (°) DEC (°)", bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, pady=0)

        # default: sky coords of maximum probability pixel
        fov_coords = str(self.user.get_ra_max_pixel()), str(self.user.get_dec_max_pixel()) 
        
        max_pixel_default = StringVar(self, value=fov_coords) 
        self.entry_1 = Entry(self, width=30, justify=CENTER,
                             textvariable=max_pixel_default)

        self.entry_1.grid(row=0, padx=15, column=1)

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

        #Btn

        self.show = Button(self, text='Show',
                           command=self.show_starting_fov)
        self.show.grid(column=2, row=0, sticky=W, padx=2, pady=5)
        
        self.checkbox = Button(self, text="Not show",      
                               command=self.no_show_starting_fov)
        self.checkbox.grid(column=3,row=0, sticky=E, padx=2, pady=5)

        self.close = Button(self, text="Obs",  fg='dark green',
                            command=self.obs)  
        self.close.grid(column=4,row=0, sticky=W, padx=2, pady=5) 
        
        self.close = Button(self, text="Close",
                            command=self.close_window)  
        self.close.grid(column=5,row=0, sticky=E, padx=2, pady=5)
class Observability(Toplevel):
    """GUI to create a MOC region in which the airmass is less than a value defined by users."""

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

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

        self.title("Observability" + "@" + self.user.get_obs_time())
        self.attributes("-topmost", True)
        
        # 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="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.close_window)
        #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 moc_obs(self):
        """Creating a MOC region in which the airmass is less than a value defined by users."""

        percentage = float(self.entry_percentage.get())/100.0

        hpx = hp.read_map(self.user.get_skymap(), verbose = False)
        
        sort = sorted(hpx, reverse = True)
        cumsum = np.cumsum(sort)
        index, value = min(enumerate(cumsum), key = lambda x: abs(x[1] - percentage))
        value = round(value, 1) # value --> threshold
        print percentage
        print index, value

        # finding ipix indices confined in a given percentage 
        index_hpx = range(0, len(hpx))
        hpx_index = np.c_[hpx, index_hpx]

        sort_2array = sorted(hpx_index, key = lambda x: x[0], reverse = True)
        value_contour = sort_2array[0:index]

        j = 1 
        table_ipix_contour = [ ]

        for i in range (0, len(value_contour)):
            ipix_contour = int(value_contour[i][j])
            table_ipix_contour.append(ipix_contour)
          
     
        # from index to polar coordinates
        theta, phi = hp.pix2ang(self.user.get_nside(), table_ipix_contour)

        # converting these to right ascension and declination in degrees
        ra = np.rad2deg(phi)
        dec = np.rad2deg(0.5 * np.pi - theta)

        #print ra

        # airmass calculation
        obs_time = Time(self.user.get_obs_time())

        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)

        sky_coord = SkyCoord(ra = ra*u.deg,dec=dec*u.deg, frame='icrs')

        altaz = sky_coord.transform_to(AltAz(obstime=self.user.get_obs_time(),
                                             location=observatory))

        airmass_values = altaz.secz
        print airmass_values
        # creating an astropy.table with RA[deg] and DEC[deg] ipix positions
        contour_ipix = Table([ ra, dec, airmass_values ], names = (
           'RA[deg]', 'DEC[deg]', 'airmass'), meta = {'ipix': 'ipix table'})

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

        obs1=contour_ipix[mask]

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

        obs = obs1[mask2]

        # setting MOC order
        from math import log
        moc_order = int(log( self.user.get_nside(), 2))

        # creating a MOC map from the contour_ipix table
        moc = MOC.from_table( obs, 'RA[deg]', 'DEC[deg]', moc_order )

        # writing MOC file in fits
        moc.write( 'obs_airmass_'+self.entry_airmass.get()+'MOC_'+str(percentage), format = 'fits' )
        print type(self.entry_airmass.get())

    def close_window(self):
        self.destroy()
class StartingFoV(Toplevel):
    """Starting a sequence from a list of FoV(s). The window contains 1 keyboard entries and 3 Buttons.

        entry:
             ra_1 dec_1 ra_2 dec_2 ra_3 dec_3 ... ra_n dec_n [deg]
             By default: sky coords of maximum probability pixel

        Btns:
           Show : draw user-defined FoV footprint(s) in Aladin Plane(s)
           No show : no draw user-defined FoV footprint(s) in Aladin Plane(s)
           Close : close the widget
        """
    
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")
        
        self.user = UserValues()

        # putting the entry value(s) in a list
        self.entries_GWsky=[]  

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

        self.title(" Starting FoV")
        self.attributes("-topmost", True)
        
        self.label_1 = Label(self, text="RA (°) DEC (°)", bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, pady=0)

        # default: sky coords of maximum probability pixel
        fov_coords = str(self.user.get_ra_max_pixel()), str(self.user.get_dec_max_pixel()) 
        
        max_pixel_default = StringVar(self, value=fov_coords) 
        self.entry_1 = Entry(self, width=30, justify=CENTER,
                             textvariable=max_pixel_default)

        self.entry_1.grid(row=0, padx=15, column=1)

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

        #Btn

        self.show = Button(self, text='Show',
                           command=self.show_starting_fov)
        self.show.grid(column=2, row=0, sticky=W, padx=2, pady=5)
        
        self.checkbox = Button(self, text="Not show",      
                               command=self.no_show_starting_fov)
        self.checkbox.grid(column=3,row=0, sticky=E, padx=2, pady=5)

        self.close = Button(self, text="Obs",  fg='dark green',
                            command=self.obs)  
        self.close.grid(column=4,row=0, sticky=W, padx=2, pady=5) 
        
        self.close = Button(self, text="Close",
                            command=self.close_window)  
        self.close.grid(column=5,row=0, sticky=E, padx=2, pady=5)

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

        if op == 'scroll':
            units = L[2]
            self.entry_1.xview_scroll(howMany, units)
        elif op == 'moveto':
            self.entry_1.xview_moveto(howMany)
            
    def __split_entries(self):
        """Splitting the entries in ra and dec; # odd: ra and # even: dec."""
        
        current_fov_coords = self.entry_1.get().replace(';',' ').replace(',',' ').split()
        fov_center_ra = current_fov_coords[0::2]
        fov_center_dec = current_fov_coords[1::2]

        return current_fov_coords, fov_center_ra, fov_center_dec
    
    def show_starting_fov(self):
        """Drawing the FoV footprint(s) in the Aladin plane(s).
         By default: sky coords (ra[deg], dec[deg]) of maximum probability pixel."""   
   
        show_sky_coverage = ShowSkyCoverage()
        
        current_fov_coords, fov_center_ra, fov_center_dec = self.__split_entries()
        
        try:
            for ra_starting, dec_starting in zip (fov_center_ra, fov_center_dec):
                aladin.get_FoV(float(ra_starting), float(dec_starting))
                show_sky_coverage.pick_coverage(float(ra_starting), float(dec_starting))
                              
        except ValueError as value_error:
            tkMessageBox.showerror ('Error', value_error)
          
        self.entries_GWsky.extend(current_fov_coords)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky, data)
            
        self.entries_GWsky=[] # re-init.
        
    def no_show_starting_fov(self):
        """No Draw the FoV footprint(s) in the Aladin plane(s);
               useful to re-initialize the sequence."""

        self.entries_GWsky=[] # re-init.     
        current_fov_coords, fov_center_ra, fov_center_dec = self.__split_entries()

        self.entries_GWsky.extend(current_fov_coords)

        with open('GWsky_entries', 'wb') as data:
            return pickle.dump(self.entries_GWsky, data)

    def obs(self):
        """Inizializing observability window."""
        
        observability = Observability()
     
    def close_window(self):
        self.destroy()
示例#16
0
class ShowSkyCoverage(object):
    """Moving the FoV-footprint coverage by choosing a starting pointing."""

    SHIFT_CORRECTION = 0.00001  # A shift correction of 0.00001 is added

    # --> to escape math error during the FoV sequence

    def __init__(self, infile_coords='GWsky_coords'):
        """Creating a class in which the instance attributes are based on the dictionary
       "GWsky_coords" by default. GWsky_coords is created and pickled by the "user_values"
       module and will be deleted when the "ShowSkyCoverageGUI" will be closed.
       It contains the keys: "ra", "dec". ra and dec represents the central location of a FoV. 
        
        Starting sky coordinates:
             self.input_ra: right ascension [deg]
             self.input_dec: declination [deg]
         """

        self.infile_coords = infile_coords
        self.entries_GWsky_new = []  # new entries during the FoV sequence

        self.user = UserValues()  # compositions
        self.lvc = LVCskymap()
        self.query = Query()
        self.airmass = Airmass()
        self.moon = Moon()

        with open(infile_coords, 'rb') as data:
            coords_GWsky = pickle.load(data)

        for k, v in coords_GWsky.items():
            setattr(self, k, v)

    def ra0ra1(self, A, dec0, dec1):
        """From the angular distance:
           cos(A) = sin(Dec1)sin(Dec2)+cos(Dec1)cos(Dec2)cos(ra1-ra2) --> 
           cos(ra1-ra2) = [cos(A)-sin(dec0)sin(dec1)]/[cos(dec0)cos(dec1)]."""

        dec0, dec1, A = radians(dec0), radians(dec1), radians(A)
        cos_ra0_ra1 = (cos(A) - sin(dec0) * sin(dec1)) / (cos(dec0) *
                                                          cos(dec1))
        ra0ra1 = degrees(acos(cos_ra0_ra1))

        return round(ra0ra1, 5)

    def __updating_center_coords(self, ra, dec):
        """Getting/Updating FoV-center (ra, dec) in the dict named by default "GWsky_coords".
.          For each tile across the sky the file is updated.""" ""

        with open('GWsky_coords', 'rb') as data:
            coords_GWsky = pickle.load(data)

        coords_GWsky['input_ra'], coords_GWsky['input_dec'] = ra, dec

        with open('GWsky_coords', 'wb') as data:
            pickle.dump(coords_GWsky, data)

    def __are_all_same(self, items):
        """Check if all elements of a list are the same."""

        return all(x == items[0] for x in items)

    def __fov_stats(self, ra, dec, table, integrated_prob, distance_grid,
                    ansatz_distribution, moon_illumination):
        """Managing the descriptive statistic window. If the airmass is outside the default range [airmass_min, airmass_max]
            the window is not opened otherwise the window is shown."""

        airmass_values, datestrings = self.airmass.airmass_step(ra, dec)
        same = self.__are_all_same(airmass_values)

        if same == True:
            tkMessageBox.showerror('Warning',
                                   "airmass outside the range of {1 - 5.8}")
            aladin.remove_FoV(ra, dec)
            aladin.remove("C_" + str(ra) + "/" + str(dec))
        else:
            time_step = [dateutil.parser.parse(s) for s in datestrings]
            self.__updating_center_coords(ra, dec)
            fov_statistics = FoVstatistics()
            fov_statistics.plot_stats(time_step, airmass_values, ra, dec,
                                      table, integrated_prob, distance_grid,
                                      ansatz_distribution, moon_illumination)
        print airmass_values, datestrings

    def update_pointings_file(self, infile, ra, dec, prob_fov):
        """The central location (ra[deg], dec[deg]) and the integrated probability of
             a selected FoV are saved locally in an external file.
             By default the file is named "GWsky_pointings.txt"."""

        with open(infile, 'a') as pointing:
            pointing.write(
                str(ra) + ' ' + str(dec) + ' ' + str(prob_fov) + '\n')

    def __query_shape(self, ra, dec, fov_shape):
        """Return the catalog query according with the defined-user FoV shape:
                   (1) box and (2) circle. """

        if self.user.get_fov_shape() != 2:  # box FoV
            query_result = self.query.query_box(ra, dec,
                                                self.user.get_fov_width(),
                                                self.user.get_fov_height(),
                                                self.user.get_catalog(),
                                                self.user.get_column_1(),
                                                self.user.get_column_2(),
                                                self.user.get_filter_1(),
                                                self.user.get_filter_2())
        else:  # circle FoV
            query_result = self.query.query_circle(ra, dec,
                                                   self.user.get_fov_radius(),
                                                   self.user.get_catalog(),
                                                   self.user.get_column_1(),
                                                   self.user.get_column_2(),
                                                   self.user.get_filter_1(),
                                                   self.user.get_filter_2())

        return query_result

    def __prob_shape(self, ra, dec, fov_shape):
        """Return the integrated probability according with the defined-user FoV shape:
                   (1) box and (2) circle."""

        if self.user.get_fov_shape() != 2:  # box FoV
            prob_fov = self.lvc.prob_in_box(ra, dec, self.user.get_fov_width(),
                                            self.user.get_fov_height())
        else:  # circle FoV
            prob_fov = self.lvc.prob_in_circle(ra, dec,
                                               self.user.get_fov_radius())

        return prob_fov

    def pick_coverage(self, ra, dec):
        """Setting GWsky: with statistic window (A); without statistic window (D)."""

        if self.user.get_GWsky_basic() == "A":  # full version

            query_result = self.__query_shape(ra, dec,
                                              self.user.get_fov_shape())
            prob_fov = self.__prob_shape(ra, dec, self.user.get_fov_shape())
            moon_illumination = self.moon.illumination()  # moon_illumination
            # moon_dist
            # TEST
            fov_sep = Utils.separation(self.input_ra, self.input_dec, ra, dec)
            print('The distance between 2 consecutive FoV centers is',
                  fov_sep.round(6))

            r, dp_dr = self.lvc.conditional_distance_fov_center(ra, dec)
            self.__fov_stats(ra, dec, query_result, prob_fov, r, dp_dr,
                             moon_illumination)  # add moon ill, moon dist

        elif self.user.get_GWsky_basic(
        ) == "D":  # basic version-> no Stats win

            prob_fov = self.__prob_shape(ra, dec, self.user.get_fov_shape())

            # TEST
            #Utils.separation(self.input_ra, self.input_dec, ra, dec)

            self.update_pointings_file("GWsky_pointings.txt", ra, dec,
                                       prob_fov)

    def intercardinal_distance(self, ra, dec, shift_up_down, shift_right_left):
        """Moving from the fixed cardinal direction using the bi-directional windows;
           shift_up_down ↕ and/or shift_right_left ↔."""

        if shift_right_left > 0:
            shift_east_west = self.ra0ra1(
                (shift_right_left - self.SHIFT_CORRECTION),
                (dec + self.user.get_fov_height() + shift_up_down),
                (dec + self.user.get_fov_height() + shift_up_down))
            dist = ra + shift_east_west

        elif shift_right_left < 0:
            shift_east_west = self.ra0ra1(
                (shift_right_left + self.SHIFT_CORRECTION),
                (dec + self.user.get_fov_height() + shift_up_down),
                (dec + self.user.get_fov_height() + shift_up_down))
            dist = ra - shift_east_west

        else:
            dist = ra

        return dist

    def load_entries(self, infile_entries):
        """Opening the file in which the input entries are stored: ra_1 dec_1 ra_2 dec_2 ... ra_n dec_n
           By default the file is named "GWsky_entries". "GWsky_entries" is created from the
           "show_starting_fov" method in "StartingFoV" class.
           A error message invites users to press the "Start FoV" button before carrying out any"""

        try:
            with open(infile_entries, 'rb') as data:
                entries_GWsky = pickle.load(data)
                return entries_GWsky
        except IOError as io_error:
            message = "Press the button 'Start FoV' and choose a starting position; \
                        by default the sky position of the max probability pixel is shown"

            tkMessageBox.showerror('Error', message)

    def north(self, shift_up_down=0, shift_right_left=0):
        """Moving the FoV tiles in North direction from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔ """

        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[
            1::2]

        for ra_start, dec_start in zip(fov_center_ra, fov_center_dec):
            dist = self.intercardinal_distance(float(ra_start),
                                               float(dec_start), shift_up_down,
                                               shift_right_left)
            north_pointing = [
                (dist),
                (float(dec_start) + self.user.get_fov_height() + shift_up_down)
            ]

            ra, dec = north_pointing[0], north_pointing[1]

            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)

            new_sky_pos = [ra, dec]  # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)

    def south(self, shift_up_down=0, shift_right_left=0):
        """Moving the FoV tiles in South direction from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔"""

        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[
            1::2]

        for ra_start, dec_start in zip(fov_center_ra, fov_center_dec):
            dist = self.intercardinal_distance(float(ra_start),
                                               float(dec_start), shift_up_down,
                                               shift_right_left)
            south_pointing = [
                (dist),
                (float(dec_start) - self.user.get_fov_height() - shift_up_down)
            ]

            ra, dec = south_pointing[0], south_pointing[1]

            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)

            new_sky_pos = [ra, dec]  # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)

    def east(self, shift_up_down=0, shift_right_left=0):
        """Moving the FoV tiles in East direction  from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔.
           A shift correction of 0.00001 is added to escape math error."""

        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[
            1::2]

        for ra_start, dec_start in zip(fov_center_ra, fov_center_dec):
            ra_distance = self.ra0ra1(
                (self.user.get_fov_width() - self.SHIFT_CORRECTION +
                 shift_right_left), float(dec_start), float(dec_start))

            east_pointing = [(float(ra_start) + ra_distance),
                             (float(dec_start) + shift_up_down)]
            ra, dec = east_pointing[0], east_pointing[1]

            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)

            new_sky_pos = [ra, dec]  # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)

    def west(self, shift_up_down=0, shift_right_left=0):
        """Moving the FoV tiles in West direction  from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔.
            A shift correction of 0.00001 is added to escape math error."""

        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[
            1::2]

        for ra_start, dec_start in zip(fov_center_ra, fov_center_dec):

            ra_distance = self.ra0ra1(
                (self.user.get_fov_width() - self.SHIFT_CORRECTION +
                 shift_right_left), float(dec_start), float(dec_start))

            west_pointing = [(float(ra_start) - ra_distance),
                             (float(dec_start) + shift_up_down)]
            ra, dec = west_pointing[0], west_pointing[1]

            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)

            new_sky_pos = [ra, dec]  # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)
class ShowSkyCoverage(object): 
    """Moving the FoV-footprint coverage by choosing a starting pointing."""
    
    SHIFT_CORRECTION = 0.00001  # A shift correction of 0.00001 is added
                                 # --> to escape math error during the FoV sequence

    def __init__(self, infile_coords='GWsky_coords'):
        """Creating a class in which the instance attributes are based on the dictionary
       "GWsky_coords" by default. GWsky_coords is created and pickled by the "user_values"
       module and will be deleted when the "ShowSkyCoverageGUI" will be closed.
       It contains the keys: "ra", "dec". ra and dec represents the central location of a FoV. 
        
        Starting sky coordinates:
             self.input_ra: right ascension [deg]
             self.input_dec: declination [deg]
         """
       
        self.infile_coords = infile_coords
        self.entries_GWsky_new =[] # new entries during the FoV sequence
        
        self.user = UserValues() # compositions
        self.lvc = LVCskymap()
        self.query = Query()
        self.airmass = Airmass()
        self.moon = Moon()
        
        with open(infile_coords, 'rb') as data:  
            coords_GWsky = pickle.load(data)
            
        for k, v in coords_GWsky.items():          
            setattr(self, k, v)
            
            
    def ra0ra1(self, A, dec0, dec1):
        """From the angular distance:
           cos(A) = sin(Dec1)sin(Dec2)+cos(Dec1)cos(Dec2)cos(ra1-ra2) --> 
           cos(ra1-ra2) = [cos(A)-sin(dec0)sin(dec1)]/[cos(dec0)cos(dec1)]."""

        dec0, dec1, A = radians(dec0),  radians(dec1), radians(A)
        cos_ra0_ra1 = ( cos(A)-sin(dec0)*sin(dec1) )/( cos(dec0)*cos(dec1) )
        ra0ra1 = degrees( acos(cos_ra0_ra1) )

        return  round(ra0ra1, 5)         
    
    def __updating_center_coords(self, ra, dec):
        """Getting/Updating FoV-center (ra, dec) in the dict named by default "GWsky_coords".
.          For each tile across the sky the file is updated."""""

        with open('GWsky_coords', 'rb') as data:
            coords_GWsky = pickle.load(data)
            
        coords_GWsky['input_ra'], coords_GWsky ['input_dec'] = ra, dec

        with open('GWsky_coords', 'wb') as data:
            pickle.dump(coords_GWsky, data)
   
    def __are_all_same(self, items):
        """Check if all elements of a list are the same."""
        
        return all(x == items[0] for x in items)

    def __fov_stats(self, ra, dec, table, integrated_prob, distance_grid, ansatz_distribution, moon_illumination):    
        """Managing the descriptive statistic window. If the airmass is outside the default range [airmass_min, airmass_max]
            the window is not opened otherwise the window is shown."""
        
        airmass_values, datestrings = self.airmass.airmass_step(ra, dec) 
        same = self.__are_all_same(airmass_values) 
                                                 
        if same == True:
            tkMessageBox.showerror('Warning',"airmass outside the range of {1 - 5.8}")
            aladin.remove_FoV(ra, dec) 
            aladin.remove("C_" + str( ra ) + "/" + str( dec ))  
        else:
            time_step = [dateutil.parser.parse(s) for s in datestrings]
            self.__updating_center_coords(ra,dec)  
            fov_statistics = FoVstatistics()                 
            fov_statistics.plot_stats(time_step, airmass_values,
                                      ra, dec,
                                      table,
                                      integrated_prob,
                                      distance_grid, ansatz_distribution, moon_illumination)
        print airmass_values, datestrings
    
    def update_pointings_file(self, infile, ra, dec, prob_fov):
         """The central location (ra[deg], dec[deg]) and the integrated probability of
             a selected FoV are saved locally in an external file.
             By default the file is named "GWsky_pointings.txt"."""
           
         with open(infile, 'a') as pointing:
             pointing.write(str(ra) + ' ' + str(dec)+ ' '+ str(prob_fov)+'\n')

    def __query_shape(self, ra, dec, fov_shape):
        """Return the catalog query according with the defined-user FoV shape:
                   (1) box and (2) circle. """
        
        if self.user.get_fov_shape() != 2:  # box FoV
                    query_result = self.query.query_box(
                       ra, dec, self.user.get_fov_width(), self.user.get_fov_height(), self.user.get_catalog(),
                       self.user.get_column_1(), self.user.get_column_2(),
                       self.user.get_filter_1(), self.user.get_filter_2())               
        else: # circle FoV
            query_result = self.query.query_circle(
               ra, dec, self.user.get_fov_radius(), self.user.get_catalog(),
               self.user.get_column_1(), self.user.get_column_2(),
               self.user.get_filter_1(), self.user.get_filter_2())
            
        return query_result

    def __prob_shape(self, ra, dec, fov_shape):
        """Return the integrated probability according with the defined-user FoV shape:
                   (1) box and (2) circle."""
        
        if self.user.get_fov_shape() !=2:  # box FoV
            prob_fov = self.lvc.prob_in_box(
               ra, dec, self.user.get_fov_width(), self.user.get_fov_height())                
        else: # circle FoV
            prob_fov = self.lvc.prob_in_circle(
               ra, dec, self.user.get_fov_radius())
            
        return  prob_fov
                  
    def pick_coverage(self, ra, dec):
        """Setting GWsky: with statistic window (A); without statistic window (D)."""                                      

        if self.user.get_GWsky_basic() == "A":  # full version 

            query_result = self.__query_shape(ra, dec, self.user.get_fov_shape())
            prob_fov = self.__prob_shape(ra, dec, self.user.get_fov_shape())
            moon_illumination =  self.moon.illumination()              # moon_illumination
                                                                             # moon_dist
            # TEST   
            fov_sep = Utils.separation(self.input_ra, self.input_dec, 
                                        ra, dec)
            print ('The distance between 2 consecutive FoV centers is', fov_sep.round(6))
            
            r, dp_dr = self.lvc.conditional_distance_fov_center(ra, dec) 
            self.__fov_stats(ra, dec, query_result, prob_fov, r, dp_dr, moon_illumination) # add moon ill, moon dist
            
        elif self.user.get_GWsky_basic() == "D":  # basic version-> no Stats win
           
            prob_fov = self.__prob_shape(ra, dec, self.user.get_fov_shape())

            # TEST  
            #Utils.separation(self.input_ra, self.input_dec, ra, dec)                                       

            self.update_pointings_file("GWsky_pointings.txt", ra, dec, prob_fov)
            
    def intercardinal_distance(self, ra, dec, shift_up_down, shift_right_left):
        """Moving from the fixed cardinal direction using the bi-directional windows;
           shift_up_down ↕ and/or shift_right_left ↔."""

        if shift_right_left > 0:
           shift_east_west = self.ra0ra1((shift_right_left-self.SHIFT_CORRECTION),
                                                   (dec + self.user.get_fov_height() + shift_up_down),
                                                   (dec + self.user.get_fov_height() + shift_up_down))
           dist = ra + shift_east_west 
         
        elif shift_right_left < 0 :
           shift_east_west = self.ra0ra1((shift_right_left + self.SHIFT_CORRECTION),
                                                   (dec + self.user.get_fov_height() + shift_up_down),
                                                   (dec + self.user.get_fov_height() + shift_up_down))
           dist = ra - shift_east_west
         
        else:
           dist = ra

        return dist 

    def load_entries(self, infile_entries):
        """Opening the file in which the input entries are stored: ra_1 dec_1 ra_2 dec_2 ... ra_n dec_n
           By default the file is named "GWsky_entries". "GWsky_entries" is created from the
           "show_starting_fov" method in "StartingFoV" class.
           A error message invites users to press the "Start FoV" button before carrying out any"""
       
        try:
            with open(infile_entries, 'rb') as data:
                entries_GWsky = pickle.load(data)
                return entries_GWsky
        except IOError as io_error:
            message = "Press the button 'Start FoV' and choose a starting position; \
                        by default the sky position of the max probability pixel is shown"
            tkMessageBox.showerror ('Error', message)
                         
    def north(self, shift_up_down=0, shift_right_left=0):
        """Moving the FoV tiles in North direction from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔ """

        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[1::2]  

        for ra_start, dec_start in zip (fov_center_ra, fov_center_dec):
            dist = self.intercardinal_distance(float(ra_start), float(dec_start),
                                                 shift_up_down, shift_right_left)
            north_pointing = [(dist),
                               (float(dec_start) + self.user.get_fov_height() + shift_up_down)]
             
            ra, dec = north_pointing[0], north_pointing[1]

            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)
            
            new_sky_pos = [ra,dec] # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)
            
    def south(self, shift_up_down=0, shift_right_left=0):    
        """Moving the FoV tiles in South direction from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔"""

        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[1::2]

        for ra_start, dec_start in zip (fov_center_ra, fov_center_dec):
            dist = self.intercardinal_distance(float(ra_start), float(dec_start),
                                                 shift_up_down, shift_right_left)
            south_pointing = [(dist), (float(dec_start) - self.user.get_fov_height() - shift_up_down)]
                    
            ra, dec = south_pointing[0], south_pointing[1]
            
            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)
                                
            new_sky_pos = [ra,dec] # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)    
          
    def east(self, shift_up_down=0, shift_right_left=0):
        """Moving the FoV tiles in East direction  from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔.
           A shift correction of 0.00001 is added to escape math error."""
        
        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[1::2]

        for ra_start, dec_start in zip (fov_center_ra, fov_center_dec):              
            ra_distance = self.ra0ra1((self.user.get_fov_width() - self.SHIFT_CORRECTION + shift_right_left),
                                        float(dec_start), float(dec_start))
                
            east_pointing = [(float(ra_start) + ra_distance), (float(dec_start) + shift_up_down)]
            ra, dec = east_pointing[0], east_pointing[1]

            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)           

            new_sky_pos = [ra,dec] # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)
                   
    def west(self, shift_up_down=0, shift_right_left=0):
        """Moving the FoV tiles in West direction  from input sky-position(s).
           The related bidirectional button permits small shifts from such pre-defined direction:
           shift_up_down ↕ and/or shift_right_left ↔.
            A shift correction of 0.00001 is added to escape math error."""
        
        entries_GWsky = self.load_entries("GWsky_entries")
        fov_center_ra, fov_center_dec = entries_GWsky[0::2], entries_GWsky[1::2]  
      
        for ra_start, dec_start in zip (fov_center_ra, fov_center_dec):
               
            ra_distance = self.ra0ra1((self.user.get_fov_width() - self.SHIFT_CORRECTION + shift_right_left),
                                      float(dec_start), float(dec_start))

            west_pointing = [(float(ra_start) - ra_distance), (float(dec_start) + shift_up_down)]
            ra, dec = west_pointing[0], west_pointing[1] 

            aladin.get_FoV(ra, dec)
            self.pick_coverage(ra, dec)
            
            new_sky_pos = [ra,dec] # cycle variables
            self.entries_GWsky_new.extend(new_sky_pos)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky_new, data)
示例#18
0
class StartingFoV(Toplevel):
    """Starting a sequence from a list of FoV(s). The window contains 1 keyboard entries and 3 Buttons.

        entry:
             ra_1 dec_1 ra_2 dec_2 ra_3 dec_3 ... ra_n dec_n [deg]
             By default: sky coords of maximum probability pixel

        Btns:
           Show : draw user-defined FoV footprint(s) in Aladin Plane(s)
           No show : no draw user-defined FoV footprint(s) in Aladin Plane(s)
           Close : close the widget
        """
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")

        self.user = UserValues()

        # putting the entry value(s) in a list
        self.entries_GWsky = []

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

        self.title(" Starting FoV")
        self.attributes("-topmost", True)

        self.label_1 = Label(self, text="RA (°) DEC (°)", bg="slate grey")
        self.label_1.grid(row=0, column=0, sticky=E, pady=0)

        # default: sky coords of maximum probability pixel
        fov_coords = str(self.user.get_ra_max_pixel()), str(
            self.user.get_dec_max_pixel())

        max_pixel_default = StringVar(self, value=fov_coords)
        self.entry_1 = Entry(self,
                             width=30,
                             justify=CENTER,
                             textvariable=max_pixel_default)

        self.entry_1.grid(row=0, padx=15, column=1)

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

        #Btn

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

        self.checkbox = Button(self,
                               text="Not show",
                               command=self.no_show_starting_fov)
        self.checkbox.grid(column=3, row=0, sticky=E, padx=2, pady=5)

        self.close = Button(self,
                            text="Obs",
                            fg='dark green',
                            command=self.obs)
        self.close.grid(column=4, row=0, sticky=W, padx=2, pady=5)

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

    #Actions
    def __scrollHandler(self, *L):
        """Scroll entry in starting FoV window."""

        op, howMany = L[0], L[1]

        if op == 'scroll':
            units = L[2]
            self.entry_1.xview_scroll(howMany, units)
        elif op == 'moveto':
            self.entry_1.xview_moveto(howMany)

    def __split_entries(self):
        """Splitting the entries in ra and dec; # odd: ra and # even: dec."""

        current_fov_coords = self.entry_1.get().replace(';', ' ').replace(
            ',', ' ').split()
        fov_center_ra = current_fov_coords[0::2]
        fov_center_dec = current_fov_coords[1::2]

        return current_fov_coords, fov_center_ra, fov_center_dec

    def show_starting_fov(self):
        """Drawing the FoV footprint(s) in the Aladin plane(s).
         By default: sky coords (ra[deg], dec[deg]) of maximum probability pixel."""

        show_sky_coverage = ShowSkyCoverage()

        current_fov_coords, fov_center_ra, fov_center_dec = self.__split_entries(
        )

        try:
            for ra_starting, dec_starting in zip(fov_center_ra,
                                                 fov_center_dec):
                aladin.get_FoV(float(ra_starting), float(dec_starting))
                show_sky_coverage.pick_coverage(float(ra_starting),
                                                float(dec_starting))

        except ValueError as value_error:
            tkMessageBox.showerror('Error', value_error)

        self.entries_GWsky.extend(current_fov_coords)

        with open('GWsky_entries', 'wb') as data:
            pickle.dump(self.entries_GWsky, data)

        self.entries_GWsky = []  # re-init.

    def no_show_starting_fov(self):
        """No Draw the FoV footprint(s) in the Aladin plane(s);
               useful to re-initialize the sequence."""

        self.entries_GWsky = []  # re-init.
        current_fov_coords, fov_center_ra, fov_center_dec = self.__split_entries(
        )

        self.entries_GWsky.extend(current_fov_coords)

        with open('GWsky_entries', 'wb') as data:
            return pickle.dump(self.entries_GWsky, data)

    def obs(self):
        """Inizializing observability window."""

        observability = Observability()

    def close_window(self):
        self.destroy()
示例#19
0
# 	3. snap rigid body ex to xform of selected object
# 	4. and prompt user for weight
# 	5. hide selected object
# 	6. simulate rigidbody ex
# 	7. after simulation is done copy original object to new xform of simulated rigid body
# 	8. delete rigid body.
import general
import lodtools
import physics

from user_values import UserValues

PHYS_OBJECT_NAME = "brush_sim_temp"

if __name__ == "__main__":
    store = UserValues()
    stored_brush = store.get("simmed_brush")
    # 	1. Get selected object.
    # grab some properties for our selected object
    user_selection = general.get_names_of_selected_objects()[0]

    if stored_brush is None:
        print('Simulating Brush')
        # store the users selection for setting the physics state later on
        store.set("simmed_brush", user_selection)
        # grab the transforms of the object
        obj_pos = general.get_position(user_selection)
        obj_rot = general.get_rotation(user_selection)
        obj_scale = general.get_scale(user_selection)

        # 	2. Create rigid body ex and copy model to rigidbodyex
示例#20
0
def save(name=False, overwrite=False, embellishment=None):
    """
	Save an Icon Setup
	:return: string name of the entity class name
	"""
    # name of icon_object in icon_level.cry
    ico_obj = "icon_object_shot"
    store = UserValues()

    # the obj to insert
    obj = dict()

    # instantiate our iodb
    try:
        io = IconObjectDB()
    except ValueError as val_err:
        general.message_box_ok(str(val_err))
        return None

    # clear the selection
    general.clear_selection()

    # get the info from the icon_object_shot
    obj["pos"] = general.get_position(ico_obj)
    obj["scale"] = general.get_scale(ico_obj)
    obj["rot"] = general.get_rotation(ico_obj)
    obj["mtl"] = general.get_assigned_material(ico_obj)
    obj["tod"] = general.get_cvar("e_timeOfDay")

    # get the brush by selecting the ico_obj
    general.select_object(ico_obj)
    obj["brush"] = lodtools.getselected().lower()
    general.clear_selection()
    stored = io.get_obj_by_brush_and_mtl(obj["brush"], obj["mtl"])

    if embellishment:
        print("Saving Embellishments")
        obj["embellishment_48"] = embellishment["embellishment_48"]
        obj["embellishment_200"] = embellishment["embellishment_200"]
        obj["embellishment_2048"] = embellishment["embellishment_2048"]
        if "embellishment_under" in embellishment.keys():
            obj["embellishment_under"] = True
    else:
        icon_obj = store.get("current_icon_object")
        if icon_obj:
            keys = icon_obj.keys()
            if "embellishment_under" in keys:
                obj["embellishment_under"] = True
            if "embellishment_48" in keys:
                obj["embellishment_48"] = icon_obj["embellishment_48"]
            if "embellishment_200" in keys:
                obj["embellishment_200"] = icon_obj["embellishment_200"]
            if "embellishment_2048" in keys:
                obj["embellishment_2048"] = icon_obj["embellishment_2048"]

    if name:
        obj["name"] = name
    elif stored:
        obj["name"] = stored["name"]
        if not general.message_box_yes_no(str("Save " + stored["name"] + "?")):
            obj["name"] = general.edit_box("Entity ClassName")
        else:
            overwrite = True
    else:
        obj["name"] = general.edit_box("Entity ClassName")

    if io.insert_object(obj) is False:
        if overwrite:
            io.insert_object(obj, override=True)
        else:
            if general.message_box_yes_no("Overwrite?"):
                io.insert_object(obj, override=True)
    print("Storing Item into UserValues")
    store.set("current_icon_object", obj)
    return obj["name"]
示例#21
0
class Observability(Toplevel):
    """GUI to create a MOC region in which the airmass is less than a value defined by users."""
    def __init__(self):
        Toplevel.__init__(self, border=8, bg="slate grey")

        self.user = UserValues()

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

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

        # 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="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.close_window)
        #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 moc_obs(self):
        """Creating a MOC region in which the airmass is less than a value defined by users."""

        percentage = float(self.entry_percentage.get()) / 100.0

        hpx = hp.read_map(self.user.get_skymap(), verbose=False)

        sort = sorted(hpx, reverse=True)
        cumsum = np.cumsum(sort)
        index, value = min(enumerate(cumsum),
                           key=lambda x: abs(x[1] - percentage))
        value = round(value, 1)  # value --> threshold
        print percentage
        print index, value

        # finding ipix indices confined in a given percentage
        index_hpx = range(0, len(hpx))
        hpx_index = np.c_[hpx, index_hpx]

        sort_2array = sorted(hpx_index, key=lambda x: x[0], reverse=True)
        value_contour = sort_2array[0:index]

        j = 1
        table_ipix_contour = []

        for i in range(0, len(value_contour)):
            ipix_contour = int(value_contour[i][j])
            table_ipix_contour.append(ipix_contour)

        # from index to polar coordinates
        theta, phi = hp.pix2ang(self.user.get_nside(), table_ipix_contour)

        # converting these to right ascension and declination in degrees
        ra = np.rad2deg(phi)
        dec = np.rad2deg(0.5 * np.pi - theta)

        #print ra

        # airmass calculation
        obs_time = Time(self.user.get_obs_time())

        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)

        sky_coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg, frame='icrs')

        altaz = sky_coord.transform_to(
            AltAz(obstime=self.user.get_obs_time(), location=observatory))

        airmass_values = altaz.secz
        print airmass_values
        # creating an astropy.table with RA[deg] and DEC[deg] ipix positions
        contour_ipix = Table([ra, dec, airmass_values],
                             names=('RA[deg]', 'DEC[deg]', 'airmass'),
                             meta={'ipix': 'ipix table'})

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

        obs1 = contour_ipix[mask]

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

        obs = obs1[mask2]

        # setting MOC order
        from math import log
        moc_order = int(log(self.user.get_nside(), 2))

        # creating a MOC map from the contour_ipix table
        moc = MOC.from_table(obs, 'RA[deg]', 'DEC[deg]', moc_order)

        # writing MOC file in fits
        moc.write('obs_airmass_' + self.entry_airmass.get() + 'MOC_' +
                  str(percentage),
                  format='fits')
        print type(self.entry_airmass.get())

    def close_window(self):
        self.destroy()
示例#22
0
# 2. Run Script
# 	1. Get selected object.
# 	2. Create rigid body ex and copy model to rigidbodyex
# 	3. snap rigid body ex to xform of selected object
# 	4. and prompt user for weight
# 	5. hide selected object
# 	6. simulate rigidbody ex
# 	7. after simulation is done copy original object to new xform of simulated rigid body
# 	8. delete rigid body.
import better_cry
from user_values import UserValues

if __name__ == "__main__":
    PHY_OBJ_NAME = "brush_sim_temp"
    level = better_cry.Level()
    store = UserValues()
    # check if we have a stored brush
    stored_brush = store.get("simmed_brush")

    if stored_brush is None:
        # 	1. Get selected object.
        brush = level.selected[0]
        # store the users selection for setting the physics state later on
        store.set("simmed_brush", brush.name)
        # 	2. Create rigid body ex and copy model to rigidbodyex
        phys_obj = level.new_object("Entity", r"RigidBodyEx", PHY_OBJ_NAME, 0, 0, 0)
        # mark it with a special material so you know it's being simulated
        phys_obj.material = "Materials/Special/green_screen.mtl"
        # set the physobj to be the selected brush object
        phys_obj.geometry_file = brush.geometry_file
        # 	3. snap physobj to xform of selected object
示例#23
0
    try:
        io = IconObjectDB()
    except ValueError as val_err:
        general.message_box_ok(str(val_err))
        return False
    xml_path = store.get("todo")[0]
    name = get_item_name_from_xml(xml_path)
    if xml_path is not None:
        icon_object = io.get_obj_by_name(name)
        if icon_object:
            add_to_scene(icon_object)
        else:
            print('Inserting ' + name + 'to icon database')
            add_to_scene(
                get_default_object(
                    get_item_geometry_from_xml(xml_path),
                    mtl=get_item_material_from_xml(xml_path),
                    name=name
                )
            )
            save(name)
        add_item_to_processed_list(xml_path, store)


if __name__ == "__main__":
    store = UserValues()
    if store.get("todo") is None:
        store.set("todo", items)
        store.set("done", [])
    load_batch(store)