Exemple #1
0
class Stars:
    '''
    Stars
    '''
    def __init__(self):
        self.path, fil = os.path.split(os.path.abspath(__file__))
        self.win = gtk.Window()
        self.win.set_size_request(800, 800)
        self.win.set_title('Stars')
        self.win.set_resizable(False)
        self.win.set_events(self.win.get_events() | gtk.gdk.BUTTON_PRESS_MASK)
        self.win.connect('destroy', gtk.main_quit)
       

        self.fix = gtk.Fixed()
        self.win.add(self.fix)
        self.win.show_all()
        img = gtk.Image()
        img.set_from_file(self.path+'/img/star800.png')
        img.show()
        self.fix.put(img, 0, 0)
        #Creating controller
        self.controller = Controller()
        star_status = self.controller.get_stars_status()
        #Create all buttons here:
        for i in range(1, star_coord.__len__() +1):
            if i <= 53:
                button = gtk.ToggleButton("%d"%i)
                button.connect("toggled", self.callback, "%d"%i)
                button.show()
                self.fix.put(button, star_coord[i][0], star_coord[i][1])
                self.default_style_toogle = button.get_modifier_style()
                if star_status[i].__contains__('ON') is True:
                    button.set_active(True)
            else:
                pass
        
    def callback(self, widget, data=None):
        '''
        callback
        '''
        print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()])
        star = int(data)
        map   = widget.get_colormap()
        color_on  = map.alloc_color("red")

        if widget.get_active() is True:
            widget.modify_bg(gtk.STATE_ACTIVE, color_on)
            
            try:
                self.controller.star_on(star)
            except Exception, e:
                print e
        else:
Exemple #2
0
    def __init__(self):
        self.path, fil = os.path.split(os.path.abspath(__file__))
        self.win = gtk.Window()
        self.win.set_size_request(800, 800)
        self.win.set_title('Stars')
        self.win.set_resizable(False)
        self.win.set_events(self.win.get_events() | gtk.gdk.BUTTON_PRESS_MASK)
        self.win.connect('destroy', gtk.main_quit)
       

        self.fix = gtk.Fixed()
        self.win.add(self.fix)
        self.win.show_all()
        img = gtk.Image()
        img.set_from_file(self.path+'/img/star800.png')
        img.show()
        self.fix.put(img, 0, 0)
        #Creating controller
        self.controller = Controller()
        star_status = self.controller.get_stars_status()
        #Create all buttons here:
        for i in range(1, star_coord.__len__() +1):
            if i <= 53:
                button = gtk.ToggleButton("%d"%i)
                button.connect("toggled", self.callback, "%d"%i)
                button.show()
                self.fix.put(button, star_coord[i][0], star_coord[i][1])
                self.default_style_toogle = button.get_modifier_style()
                if star_status[i].__contains__('ON') is True:
                    button.set_active(True)
            else:
                pass
Exemple #3
0
    def __init__(self,dir_name='slopes',camera='pike',server='corba'):
        #Camera instance
        self.Cam = Camera(camera)
        #Darc Controller instance
        self.c = darc.Control(self.Cam.name)
        #Beagle Controller instance
        self.bbbc = None
        if server=='corba':
            self.bbbc = Controller()
        else:
            self.bbbc = Controller(server=server)
        #self.logger = logging.getLogger(__name__)
        #Camera instance
        self.Cam = Camera(camera)

        #
        self.niter = 5
        self.image_path = self.Cam.image_path
        self.dir_name = dir_name
        self.cases = {'slopes':0,'images':1,'both':2}
    def __init__(self,cameraName):
        '''
        INPUT
        cameraName       [string]
        '''
        #Darc Controller instance
        self.c = darc.Control(cameraName)
        #Beagle Controller instance
        self.bbbc = Controller()
        #Darc camera instance
        self.Cam = Camera(cameraName)

        #Parameters
        self.niter = int(1)
        self.nsubaps = int(self.Cam.nsubaps)                             # number of active subaps(208*2)
        self.nsubaps *= 2
        self.nstars = self.Cam.nstars                                    # number of stars
        self.maxexptime = float(self.Cam.maxexptime)                     # maximum exptime time. when exptime time is set outside
                                                                    # the range [0:4095] it is taken as the modulus of tExptime/4095
        self.sat = float(self.Cam.saturation)                          # self.Cam.name saturation value
        self.majorpattern = None
        self.minorpattern = None
Exemple #5
0
class Acquisition:
    def __init__(self,dir_name='slopes',camera='pike',server='corba'):
        #Camera instance
        self.Cam = Camera(camera)
        #Darc Controller instance
        self.c = darc.Control(self.Cam.name)
        #Beagle Controller instance
        self.bbbc = None
        if server=='corba':
            self.bbbc = Controller()
        else:
            self.bbbc = Controller(server=server)
        #self.logger = logging.getLogger(__name__)
        #Camera instance
        self.Cam = Camera(camera)

        #
        self.niter = 5
        self.image_path = self.Cam.image_path
        self.dir_name = dir_name
        self.cases = {'slopes':0,'images':1,'both':2}

    def grab(self,stream,niter):
        taken = pp.unpack(self.c.GetStreamBlock(self.Cam.name+stream,niter)).sum(0)/float(niter)
        return taken

    def grab_data_from_darc(self,acquire):
        '''
        Using darc, take a FITS image and save it into the disk. By default use
        a <camera name>_<image prefix>_YEAR-MONTH-DAYTHOUR-MIN-SEC.fits as
        image name.  The path to be store the file as well as image_prefix can
        be modified in configuration file
    
        This should also take slopes (which will be used as training data)
        '''
        logging.info('About to take data with darc ...')
        slope_stream = None

        #Get slope_streams:
        if(self.cases[acquire]==0):
            slope_stream = self.grab('rtcCentBuf',self.niter)
            logging.debug(slope_stream)
            return slope_stream
        elif(self.cases[acquire]==1):
            slope_stream = self.grab('rtcCalPxlBuf',self.niter)
            logging.debug(slope_stream)
            return slope_stream
        else:
            print 'Can\'t acquire!'
            return
        
    
    def take_data(self, star_list, cmd_list,acquire):
            '''
            This method does:
            After that,  start all over again,  given a number of times in num
            variable

            star_list is a Star object list

            from BeagleDarc.Model import Star
            star_list = []
            for i in range(1,n+1):
                star_list.append(Star(i))
            
            '''
            print 'Acquisition position: ',
            print cmd_list

            #Turning on a star to prevent noise
            self.bbbc.star_on(1)

            #horizontal motor move
            self.bbbc.set_position('horizontal_altitude_layer',cmd_list[0], 200)

            #vertical motor move
            self.bbbc.set_position('vertical_altitude_layer',cmd_list[1], 200)
            
            slopes_frame = None
            images_frame = None

            if(self.cases[acquire]==0):
                slopes_frame = np.array([])
            elif(self.cases[acquire]==1):
                images_frame = np.array([])
            elif(self.cases[acquire]==2):
                slopes_frame = np.array([])
                images_frame = np.array([])

            # led on
            self.bbbc.star_off(1)
            for star in star_list:
                star.setup(self.Cam)
                self.bbbc.star_on(int(star.image_prefix))
                #take img with darc
                if(self.cases[acquire]==0):
                    slopes_frame = np.append(slopes_frame,self.grab_data_from_darc(acquire))
                elif(self.cases[acquire]==1):
                    images_frame = np.append(images_frame,self.grab_data_from_darc(acquire))
                elif(self.cases[acquire]==2):
                    slopes_frame = np.append(slopes_frame,self.grab_data_from_darc('slopes'))
                    images_frame = np.append(images_frame,self.grab_data_from_darc('images'))
                
                #led off
                self.bbbc.star_off(int(star.image_prefix))
            
            if(self.cases[acquire]==0):
                return slopes_frame
            elif(self.cases[acquire]==1):
                return images_frame
            elif(self.cases[acquire]==2):
                return (slopes_frame,images_frame)
            return slopes_frame
 

    def take_all_data(self,iterations,star_list,prefix,acquire='slopes',altitude=-1,fpf=10):
        '''
        fpf = frames per FITS.
        smpling = steps per position
        '''
        Start_time = str(time.strftime("%Y_%m_%dT%H_%M_%S.fits", time.gmtime()))
        #cali = Calibration(self.Cam.name)
        #cali.routine_calibration(star_list)

        # Comment this flush when calibrating
        self.bbbc.flush_all_leds()
        all_slopes = None
        all_images = None
        cmd_list = None
        if(self.cases[acquire]==0):
            all_slopes = np.zeros((fpf,len(star_list)*2*self.Cam.nsubaps))
        elif(self.cases[acquire]==1):
            all_images = np.zeros((fpf,len(star_list)*self.Cam.pxlx*self.Cam.pxly))
        elif(self.cases[acquire]==2):
            all_slopes = np.zeros((fpf,len(star_list)*2*self.Cam.nsubaps))
            all_images = np.zeros((fpf,len(star_list)*self.Cam.pxlx*self.Cam.pxly))
        else:
            print 'Can\'t acquire!'
            return
        Star_list = []
        cmd_list = self.cmdlist_gen(iterations,altitude)
        for s in star_list:
            Star_list.append(Star(s))
        
        for i in range(0,int(iterations)):
            Start_time = str(time.strftime("%Y_%m_%dT%H_%M_%S.fits", time.gmtime()))
            print '\nTaking iteration #: %d' % (i+1)
            if(self.cases[acquire]==0):
                oli = self.take_data(Star_list, cmd_list[i],'slopes')
                all_slopes[i%fpf,:] = oli
            elif(self.cases[acquire]==1):
                oli = self.take_data(Star_list, cmd_list[i],'images')
                all_images[i%fpf,:] = oli
            elif(self.cases[acquire]==2):
                oli = self.take_data(Star_list, cmd_list[i],'both')
                all_slopes[i%fpf,:] = oli[0]
                all_images[i%fpf,:] = oli[1]
            
            if((i+1)%fpf==0 or i==(iterations-1)):
                if os.path.exists(self.image_path+self.dir_name) is False:
                    os.mkdir(self.image_path+self.dir_name)
                slope_name = self.Cam.name + '_slopes_' + prefix + '_' +str(fpf).zfill(3) + '_T' +Start_time
                image_name = self.Cam.name + '_images_' + prefix + '_' +str(fpf).zfill(3) + '_T' +Start_time 
                slp_path = os.path.normpath(self.image_path+self.dir_name+'/'+slope_name)
                img_path = os.path.normpath(self.image_path+self.dir_name+'/'+image_name)
                if(self.cases[acquire]==0):
                    FITS.Write(all_slopes.astype(np.float32), slp_path, writeMode='w')
                elif(self.cases[acquire]==1):
                    FITS.Write(all_images.astype(np.float32), img_path, writeMode='w')
                elif(self.cases[acquire]==2):
                    FITS.Write(all_slopes.astype(np.float32), slp_path, writeMode='w')
                    FITS.Write(all_images.astype(np.float32), img_path, writeMode='w')
                logging.info('Data saved : %s' % slp_path)
                Start_time = str(time.strftime("%Y_%m_%dT%H_%M_%S.fits", time.gmtime()))
                if(self.cases[acquire]==0):
                    all_slopes = all_slopes*0.
                elif(self.cases[acquire]==1):
                    all_images = all_images*0.
                elif(self.cases[acquire]==2):
                    all_slopes = all_slopes*0.
                    all_images = all_images*0.
                self.bbbc.flush_all_leds()
               
        
    def cmdlist_gen(self,iterations,altitude=-1):
        # Motor 0: horizontal
        motorh = Layer('horizontal_altitude_layer')
        # Motor 1: vertical
        motorv = Layer('vertical_altitude_layer')
        cmd_temp = []
        cmd_list = []
        cur_pos = [0,0]
        mindis = motorh.vr_end + motorv.vr_end
        minarg = 0
        cmdx = []
        cmdy = []
        
        for cmd in range(0,int(iterations)):
            if(altitude>=0.0 and altitude<=1.0):
                cmd_temp = cmd_temp + [[int(motorh.vr_end*cmd/iterations),int(altitude*motorv.vr_end)]]
            else:
                cmd_temp = cmd_temp + [[random.randint(0,motorh.vr_end),random.randint(0,motorv.vr_end)]]

        for it0 in range(0,int(iterations)):
            for it1 in range(0,len(cmd_temp)):
                if(mindis > (abs(cmd_temp[it1][0]-cur_pos[0])*0.5 + (cmd_temp[it1][1]-cur_pos[1]))):
                    mindis = abs(cmd_temp[it1][0]-cur_pos[0])*0.5 + (cmd_temp[it1][1]-cur_pos[1])
                    minarg = it1
            
            cur_pos = cmd_temp.pop(minarg)
            cmd_list = cmd_list + [cur_pos]
            cmdx = cmdx + [cur_pos[0]]
            cmdy = cmdy + [cur_pos[1]]
            minarg = 0
            mindis = motorh.vr_end + motorv.vr_end
            
        #plt.plot(cmdx,cmdy,'k')
        #plt.show()
        return cmd_list

    def first_calibration(self,star_list):
        cali = Calibration(self.Cam.camera)
        cali.first_calibration(star_list)
Exemple #6
0
    def __init__(self):
        self.path, fil = os.path.split(os.path.abspath(__file__))
        self.win = gtk.Window()
        self.win.set_size_request(800, 800)
        self.win.set_title('Layers')
        self.win.set_resizable(False)
        self.win.set_events(self.win.get_events() | gtk.gdk.BUTTON_PRESS_MASK)
        self.win.connect('destroy', gtk.main_quit)
       

        self.fix = gtk.Fixed()
        self.win.add(self.fix)
        self.win.show_all()

        ### LED POSITION ###
        # ground: sts init
        self.sts_ground_init = gtk.Image()
        self.sts_ground_init.set_from_file(self.path+'/img/led-green.gif')
        self.fix.put(self.sts_ground_init, 135, 695)
        self.sts_ground_init.show()

        # ground: sts end
        self.sts_ground_end = gtk.Image()
        self.sts_ground_end.set_from_file(self.path+'/img/led-green.gif')
        self.fix.put(self.sts_ground_end, 650, 695)
        self.sts_ground_end.show()

        # altitude X : sts init
        self.sts_altitude_X_init = gtk.Image()
        self.sts_altitude_X_init.set_from_file(self.path+'/img/led-green.gif')
        self.fix.put(self.sts_altitude_X_init, 135, 615)
        self.sts_altitude_X_init.show()

        # altitude X : sts end
        self.sts_altitude_X_end = gtk.Image()
        self.sts_altitude_X_end.set_from_file(self.path+'/img/led-green.gif')
        self.fix.put(self.sts_altitude_X_end, 650, 615)
        self.sts_altitude_X_end.show()

        # altitude Y : sts init
        self.sts_altitude_Y_init = gtk.Image()
        self.sts_altitude_Y_init.set_from_file(self.path+'/img/led-green.gif')
        self.fix.put(self.sts_altitude_Y_init, 705, 15)
        self.sts_altitude_Y_init.show()

        # altitude Y : sts end
        self.sts_altitude_Y_end = gtk.Image()
        self.sts_altitude_Y_end.set_from_file(self.path+'/img/led-green.gif')
        self.fix.put(self.sts_altitude_Y_end, 705, 490)
        self.sts_altitude_Y_end.show()

        ### Layer IMG ###
        # ground: cur
        self.img_ground_cur = gtk.Image()
        self.img_ground_cur.set_from_file(self.path+'/img/gl_full_s.png')
        self.fix.put(self.img_ground_cur, 100, 500)
        self.img_ground_cur.show()
        # ground: cmd
        self.img_ground_cmd = gtk.Image()
        self.img_ground_cmd.set_from_file(self.path+'/img/al_empty_s.png')
        self.fix.put(self.img_ground_cmd, 100, 500)
        self.img_ground_cmd.show()
        
        # altitude: cur
        self.img_altitude_cur = gtk.Image()
        self.img_altitude_cur.set_from_file(self.path+'/img/al_full_s.png')
        self.fix.put(self.img_altitude_cur, 100, 450)
        self.img_altitude_cur.show()
        # altitude: cmd
        self.img_altitude_cmd = gtk.Image()
        self.img_altitude_cmd.set_from_file(self.path+'/img/al_empty_s.png')
        self.fix.put(self.img_altitude_cmd, 100, 450)
        self.img_altitude_cmd.show()

        ############ labels       ##########
        self.label1 = gtk.Label()
        self.label1.modify_font(pango.FontDescription("sans 8"))
        self.label1.set_text("Ground Layer")
        self.label1.show()
        self.fix.put(self.label1, 350, 680)

        self.label2 = gtk.Label()
        self.label2.modify_font(pango.FontDescription("sans 8"))
        self.label2.set_text("Altitude Layer X")
        self.label2.show()
        self.fix.put(self.label2, 350, 600)

        self.label3 = gtk.Label()
        self.label3.modify_font(pango.FontDescription("sans 8"))
        self.label3.set_angle(90)
        self.label3.set_text("Altitude Layer Y")
        self.label3.show()
        self.fix.put(self.label3, 690, 200)

        self.label4 = gtk.Label()
        self.label4.modify_font(pango.FontDescription("sans 8"))
        self.label4.set_text("Y: INIT POSITION")
        self.label4.show()
        self.fix.put(self.label4, 570, 470)
        
        self.label5 = gtk.Label()
        self.label5.modify_font(pango.FontDescription("sans 8"))
        self.label5.set_text("Y: END POSITION")
        self.label5.show()
        self.fix.put(self.label5, 570, 50)

        self.label6 = gtk.Label()
        self.label6.modify_font(pango.FontDescription("sans 8"))
        self.label6.set_text("X: INIT POSITION")
        self.label6.show()
        self.fix.put(self.label6, 5, 540)

        self.label7 = gtk.Label()
        self.label7.modify_font(pango.FontDescription("sans 8"))
        self.label7.set_text("X: END POSITION")
        self.label7.show()
        self.fix.put(self.label7, 570, 540)

        #ground x
        self.label8 = gtk.Label()
        self.label8.modify_font(pango.FontDescription("sans 8"))
        self.label8.set_text("position")
        self.label8.show()
        self.fix.put(self.label8, 75, 700)
        #
        self.label9 = gtk.Label()
        self.label9.modify_font(pango.FontDescription("sans 8"))
        self.label9.set_text("velocity")
        self.label9.show()
        self.fix.put(self.label9, 75, 715)
        #altitude x
        self.label10 = gtk.Label()
        self.label10.modify_font(pango.FontDescription("sans 8"))
        self.label10.set_text("position")
        self.label10.show()
        self.fix.put(self.label10, 75, 620)
        #
        self.label11 = gtk.Label()
        self.label11.modify_font(pango.FontDescription("sans 8"))
        self.label11.set_text("velocity")
        self.label11.show()
        self.fix.put(self.label11, 75, 635)

        #altitude y
        self.label12 = gtk.Label()
        self.label12.modify_font(pango.FontDescription("sans 8"))
        self.label12.set_angle(90)
        self.label12.set_text("position")
        self.label12.show()
        self.fix.put(self.label12, 705, 510)
        #
        self.label13 = gtk.Label()
        self.label13.modify_font(pango.FontDescription("sans 8"))
        self.label13.set_angle(90)
        self.label13.set_text("velocity")
        self.label13.show()
        self.fix.put(self.label13, 725, 510)

        # POSITION BAR 
        ########################
        # ground_scale (pos)
        #
        layer = Layer('ground_layer')
        adjustment = gtk.Adjustment(value=float(layer.cur_pos), lower=layer.vr_init, upper=layer.vr_end+1, step_incr=0.1, page_incr=1.0, page_size=1.0)
        self.ground_scale_pos = gtk.HScale(adjustment)
        self.ground_scale_pos.set_digits(0)
        self.ground_scale_pos.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.ground_scale_pos.connect("value-changed", self.ground_scale_pos_moved)
        self.ground_scale_pos.set_size_request(500, 30)
        self.ground_scale_pos.show()
        self.fix.put(self.ground_scale_pos, 150, 680)
        ########################
        # ground_scale (vel)
        #
        adjustment = gtk.Adjustment(value=0.0, lower=0.0, upper=101.0, step_incr=0.1, page_incr=1.0, page_size=1.0)
        self.ground_scale_vel = gtk.HScale(adjustment)
        self.ground_scale_vel.set_digits(0)
        self.ground_scale_vel.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.ground_scale_vel.connect("value-changed", self.ground_scale_vel_moved)
        self.ground_scale_vel.set_size_request(500, 30)
        self.ground_scale_vel.show()
        self.fix.put(self.ground_scale_vel, 150, 700)


        ########################
        # altitude_scale X (pos)
        #
        layer = Layer('horizontal_altitude_layer')
        adjustment = gtk.Adjustment(value=float(layer.cur_pos), lower=layer.vr_init, upper=layer.vr_end+1, step_incr=0.1, page_incr=1.0, page_size=1.0)
        self.altitude_scale_pos_X = gtk.HScale(adjustment)
        self.altitude_scale_pos_X.set_digits(0)
        self.altitude_scale_pos_X.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.altitude_scale_pos_X.connect("value-changed", self.altitude_scale_pos_X_moved)
        self.altitude_scale_pos_X.set_size_request(500, 30)
        self.altitude_scale_pos_X.show()
        self.fix.put(self.altitude_scale_pos_X, 150, 600)
        ########################
        # altitude_scale X (vel)
        #
        adjustment = gtk.Adjustment(value=0.0, lower=0.0, upper=101.0, step_incr=0.1, page_incr=1.0, page_size=1.0)
        self.altitude_scale_vel_X = gtk.HScale(adjustment)
        self.altitude_scale_vel_X.set_digits(0)
        self.altitude_scale_vel_X.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.altitude_scale_vel_X.connect("value-changed", self.altitude_scale_vel_X_moved)
        self.altitude_scale_vel_X.set_size_request(500, 30)
        self.altitude_scale_vel_X.show()
        self.fix.put(self.altitude_scale_vel_X, 150, 620)
        ########################
        # altitude_scale Y (pos)
        #
        layer = Layer('vertical_altitude_layer')
        adjustment = gtk.Adjustment(value=float(layer.cur_pos), lower=layer.vr_init, upper=layer.vr_end+1, step_incr=0.1, page_incr=1.0, page_size=1.0)
        self.altitude_scale_pos_Y = gtk.VScale(adjustment)
        self.altitude_scale_pos_Y.set_digits(0)
        #self.altitude_scale_pos_Y.set_value_pos(gtk.POS_BOTTOM) 
        self.altitude_scale_pos_Y.set_inverted(True)
        self.altitude_scale_pos_Y.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.altitude_scale_pos_Y.connect("value-changed", self.altitude_scale_pos_Y_moved)
        self.altitude_scale_pos_Y.set_size_request(30, 450)
        self.altitude_scale_pos_Y.show()
        self.fix.put(self.altitude_scale_pos_Y, 700, 40)
        ########################
        # altitude_scale Y (vel)
        #
        adjustment = gtk.Adjustment(value=0.0, lower=0.0, upper=101.0, step_incr=0.1, page_incr=1.0, page_size=1.0)
        self.altitude_scale_vel_Y = gtk.VScale(adjustment)
        self.altitude_scale_vel_Y.set_digits(0)
        #self.altitude_scale_vel_Y.set_value_pos(gtk.POS_BOTTOM) 
        self.altitude_scale_vel_Y.set_inverted(True)
        self.altitude_scale_vel_Y.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.altitude_scale_vel_Y.connect("value-changed", self.altitude_scale_vel_Y_moved)
        self.altitude_scale_vel_Y.set_size_request(30, 450)
        self.altitude_scale_vel_Y.show()
        self.fix.put(self.altitude_scale_vel_Y, 720, 40)
        # Apply button:
        self.button_ok = gtk.Button("Execute Now")
        self.button_ok.show()
        self.button_ok.connect("clicked", self.execute_now)
        self.fix.put(self.button_ok, 650, 750)

        # EMERGENCY Button:
        self.button_emergency = gtk.Button("EMERGENCY")
        self.button_emergency.show()
        self.button_emergency.connect("clicked", self.abort)
        self.fix.put(self.button_emergency, 100, 750)

        ##Creating controller
        self.controller = Controller()
        
        ## cmd pos/vel
        self.ground_pos = self.controller.get_motor_cur_pos('ground_layer')
        self.alt_x_pos =  self.controller.get_motor_cur_pos('horizontal_altitude_layer')
        self.alt_y_pos =  self.controller.get_motor_cur_pos('vertical_altitude_layer')
        print "server->ground_pos %.0f" % self.ground_pos
        print "server->alt_x_pos  %.0f" % self.alt_x_pos
        print "server->alt_y_pos  %.0f" % self.alt_y_pos
        print "------------"
        self.ground_vel = 0.0
        self.alt_x_vel = 0.0
        self.alt_y_vel = 0.0
        # moving according
        self.fix.move(self.img_ground_cur, 100+int(self.ground_pos*(3/200.)), 500)
        self.fix.move(self.img_ground_cmd, 100+int(self.ground_pos*(3/200.)), 500)
        self.fix.move(self.img_altitude_cur, 100+int(self.alt_x_pos*(4/200.)), 450 - int(self.alt_y_pos*(4/200.)))
        self.fix.move(self.img_altitude_cmd, 100+int(self.alt_x_pos*(4/200.)), 450 - int(self.alt_y_pos*(4/200.)))
        self.fix.move(self.img_altitude_cur, 100+int(self.alt_x_pos*(4/200.)), 450 - int(self.alt_y_pos*(4/200.)))
        self.fix.move(self.img_altitude_cmd, 100+int(self.alt_x_pos*(4/200.)), 450 - int(self.alt_y_pos*(4/200.)))
Exemple #7
0
from BeagleDarc.Controller import Controller
import ConfigParser


bbbc = Controller()
for s in range(1,54+1):
    try:
        print "s->%d on" % s
        bbbc.star_on(s)
        print "s->%d off" % s
        bbbc.star_off(s)
    except ConfigParser.NoSectionError:
        pass
class Calibration:
    def __init__(self,cameraName):
        '''
        INPUT
        cameraName       [string]
        '''
        #Darc Controller instance
        self.c = darc.Control(cameraName)
        #Beagle Controller instance
        self.bbbc = Controller()
        #Darc camera instance
        self.Cam = Camera(cameraName)

        #Parameters
        self.niter = int(1)
        self.nsubaps = int(self.Cam.nsubaps)                             # number of active subaps(208*2)
        self.nsubaps *= 2
        self.nstars = self.Cam.nstars                                    # number of stars
        self.maxexptime = float(self.Cam.maxexptime)                     # maximum exptime time. when exptime time is set outside
                                                                    # the range [0:4095] it is taken as the modulus of tExptime/4095
        self.sat = float(self.Cam.saturation)                          # self.Cam.name saturation value
        self.majorpattern = None
        self.minorpattern = None


    def Set_useBrightest(self):
        '''
        #1- Setting useBrightest, loaded from the config. file.
        '''
        
        #self.c.Set('useBrightest',2*float(self.Cam.usebrightest))
        self.c.Set('useBrightest',0)
        
    def find_useBrightest(self):
        self.bgImage_exptime_calibration(1)
        self.subap_calibration(1)
        hardniter = 100
        nBrightest = 100                                    # range of values
                                                            # to test
        noise = numpy.zeros(nBrightest)
        name = self.Cam.name
        frames = numpy.zeros([hardniter,self.nsubaps])
        self.bbbc.star_on(1)
        for i in range(0,nBrightest):
            print '\nRecording with useBrightest:%3.0f ' %i
            self.c.Set('useBrightest',-i)
            cent = self.c.GetStreamBlock(name+'rtcCentBuf',hardniter)   # hardniter frames - as a dict
            cent = cent[cent.keys()[0]]
            for j in range(0,hardniter):
                frames[j,:] = cent[j][0]
            centx2 = numpy.square(frames[:,::2])
            centy2 = numpy.square(frames[:,1::2])
            noise[i] = ((centx2+centy2).sum(0)/float(hardniter)).sum(0)/float(self.nsubaps)       #

        print noise.argmin(0)
        self.c.Set('useBrightest',-float(noise.argmin(0)))
        self.Cam.usebrightest = -int(noise.argmin(0))
        pylab.plot(noise)
        pylab.show()
        
        self.bbbc.star_off(1)
        #FITS.Write(noise.astype(numpy.float32),'noise_vs_useBrightest.fits')

    def find_slope_niter():
        stream = 'rtcCentBuf'
        threshold = 1.0
        for star_id in range(1,1+nstars):
            star = Star(star_id)
            ok = star.setup(self.Cam)
            if(ok):
                slope_niter = find_niter(stream,threshold)
                if(slope_niter[0] != -1):
                    star.slope_iter = slope_niter[0]
                    FITS.Write(slope_niter[1],self.Cam.rawdata_path + self.Cam.name+'_slopes_noscreen_led_%d.fits'%(star_id),writeMode='a')
                else:
                    print 'Relax threshold'
                             
    def find_bg_niter():
        stream = 'rtcPxlBuf'
        threshold = 10
        c.Set('exptime',self.Cam.maxexptime)
        bg_niter = find_niter(stream,threshold)
        if(bg_iter[0] != -1):
            self.Cam.bg_niter = bg_niter[0]
            FITS.Write(bg_niter[1],self.Cam.rawdata_path + self.Cam.name+'_bgImage_exptime_%d.fits'%(int(self.Cam.maxexptime)),writeMode='a')
        else:
            print 'Relax threshold'
        

    def find_niter(self,stream, threshold):
        '''
        Finds and store (with Norman's help) a reasonable number of
        iterations to use when grabbing slopes or backgrounds. 
        The result is as small as possible given a wanted variance 
        under 1 pxl for slopes.

        INPUT
        stream[str]            Name of the darc stream for which you
                               want to find the correct number of iterations
        
        threshold[float]       Threshold under which you want the noise
                               of your system to be (variance).
        '''
        harniter = 10000
        subniter = 200
        threshold = float(threshold)
        slopes = numpy.zeros([hardniter,nsubaps])
        runningnoise = numpy.zeros(subniter)
        found = False
        index_found = 0
        
        print 'Stream Block Acquisition'
        cent = self.c.GetStreamBlock(name+stream,hardniter)   # hardniter frames - as a dict
        print 'Extracting data'
        cent = cent[cent.keys()[0]]
        for j in range(0,hardniter):
            slopes[j,:] = cent[j][0]
        
        print 'Reducing data'
        for n in numpy.arange(1,subniter+1):
            runningnoise[n-1] = running_var(slopes,0,n)
            if(runningnoise<=threshold and not(found)):
                found = True
                index_found = n
            
        if(found):
            return [index_found, slopes]
        else:
            return -1
            print 'Number of iterations not found'

    def running_var(self,data,axis,n):
        '''
        Shuffles data and calculates the mean along the specified axis.
        The mean is calculated for sets of n samples. The variance is 
        calculated upon the resulting set of mean numbers. If data is
        2-dimensional the output is the maximum resulting value.
       
        INPUT
        data[numpy array]            Array of up to 2 dimensions
        axis[int]
        n[int]        

        OUTPUT
        var[numpy float]
        '''
        # First we shuffle in the axis direction
        if(axis==1):
            data = numpy.transpose(data)
       
        shape = numpy.shape(data)
        if(numpy.shape(shape)[0]==1):
            data = data.reshape((numpy.shape(data)[0],1))
            
        elif(numpy.shape(shape)[0]>2):
            raise DimError('data has more than 2 dimensions')

        large = int(numpy.shape(data)[0]/n)
        data = data[0:large,:]
        shape = numpy.shape(data)
        means = numpy.zeros((large,shape[1]))
            
        for i in numpy.arange(0,shape[1]):
            numpy.random.shuffle(data[:,i])
            for j in numpy.arange(0,large):
                means[j,i] = numpy.mean(data[j*n:(j+1)*n,i])
        return numpy.amax(numpy.var(means,0))

    def bgImage_exptime_calibration(self,star_id):
        '''
        Determines, sets and save the bgImage for star_id. exptime is
        saved on the files name.
        INPUT
        star_id[int]
        '''
        #2-3 bgImage & exptime iteration
        star = Star(star_id)
        star.setup(self.Cam)
        exptime = numpy.round(self.Cam.initexptime)
        self.c.Set('bgImage',None)
        self.c.Set(self.Cam.exptime,int(exptime))
        bgImage = self.grab('rtcPxlBuf',self.niter)
        self.c.Set('bgImage',bgImage)
        self.bbbc.star_on(star_id)
        auxImage = self.grab('rtcCalPxlBuf',self.niter)
        self.bbbc.star_off(star_id)
        auxImageMax = auxImage.max()
        print 'auxImageMax: ', auxImageMax
        relativemax = 0.7
        threshold = 0.05

        while(numpy.absolute(auxImageMax/self.sat-relativemax)>threshold):
            # The while condition is set so that the maximum value found in the image
            # is around 60% of the saturation value
            print "exptime: ",
            print exptime
            print 'auxImageMax: ',
            print str(100*auxImageMax/self.sat)+'%'
            exptime = float(exptime)*(self.sat*float(relativemax))/auxImageMax
            if(exptime>=self.maxexptime):
                # Protection
                exptime = self.maxexptime
                auxImageMax = self.sat*relativemax
                self.c.Set(self.Cam.exptime,int(exptime))
            elif(exptime<1.0):
                exptime = 1.0
                auxImageMax = self.sat*relativemax
                self.c.Set(self.Cam.exptime,int(exptime))
            else:
                self.c.Set('bgImage',None)
                self.c.Set(self.Cam.exptime,int(exptime))
                bgImage = self.grab('rtcPxlBuf',self.niter)
                self.c.Set('bgImage',bgImage)
                self.bbbc.star_on(star_id)
                auxImage = self.grab('rtcCalPxlBuf',self.niter)
                self.bbbc.star_off(star_id)
                auxImageMax = numpy.amax(auxImage)
        
        print "Final exptime: ",
        print exptime
        print 'Final auxImageMax: ',
        print str(100*auxImageMax/self.sat)+'%'
        self.c.Set('bgImage',None)
        bgImage = self.grab('rtcPxlBuf',self.Cam.bg_iter)
        self.c.Set('bgImage',bgImage)
        self.bbbc.flush_all_leds()
        self.bbbc.star_on(star_id)
        auxImage = self.grab('rtcCalPxlBuf',self.niter)
        self.bbbc.star_off(star_id)
        self.c.Set('bgImage',bgImage)
        
        #Saving values found and removing previous values
        files = os.listdir(self.Cam.bg_path)
        files = [s for s in files if 'led_%d_'%(star_id) in s]
        if(files!=[]):
            for file_name in files:
                os.remove(self.Cam.bg_path + file_name)
        FITS.Write(bgImage,self.Cam.bg_path + self.Cam.name+'_bg_led_%d_exptime_%d.fits'%(star_id,int(exptime)),writeMode='w')
        FITS.Write(auxImage.reshape((self.Cam.pxly,self.Cam.pxlx)),self.Cam.bg_path + self.Cam.name+'_aux_led_%d_exptime_%d.fits'%(star_id,int(exptime)),writeMode='w')

    def pupil_location(self,star_id):
        #Parameters
        self.c.Set('bgImage',None)
        allsubaps = self.Cam.allsubaps                    # Active+Inactive subaps
        side = int(numpy.sqrt(allsubaps))
        nstars = self.Cam.nstars
        subapLocation = numpy.zeros((allsubaps,6))             # Centred on (0,0)
        subapLocation[:,2] = subapLocation[:,2] + 1
        subapLocation[:,5] = subapLocation[:,5] + 1

        Xwidth = self.Cam.xwidth
        Ywidth = self.Cam.ywidth
        Xgap = self.Cam.xgap
        Ygap = self.Cam.ygap 

        # Checking for parity
        xRow = numpy.array([])
        if(side%2):
            xRow = numpy.arange(-numpy.ceil(float(side)/2),round(float(side)/2))*Xgap -round(Xwidth/2)
        else:
            xRow = numpy.arange(-float(side)/2,float(side)/2)*Xgap + round(Xgap/2) -round(Xwidth/2)

        yRow = numpy.array([])
        if(side%2):
            yRow = numpy.arange(-numpy.ceil(float(side)/2),round(float(side)/2))*Ygap -round(Ywidth/2)
        else:
            yRow = numpy.arange(-float(side)/2,float(side)/2)*Ygap + round(Ygap/2) -round(Ywidth/2)

        for row in range(1,int(side+1)):
            subapLocation[side*(row-1):side*(row),0] = yRow[row-1]
            subapLocation[side*(row-1):side*(row),1] = subapLocation[side*(row-1):side*(row),0] + Ywidth
            subapLocation[side*(row-1):side*(row),3] = xRow
            subapLocation[side*(row-1):side*(row),4] = subapLocation[side*(row-1):side*(row),3] + Xwidth

        if(self.majorpattern==None):
            self.majorpattern = numpy.zeros((-subapLocation[0,0]+subapLocation[-1,1]+1,-subapLocation[0,3]+subapLocation[-1,4]+1))
            self.minorpattern = numpy.zeros((Ywidth+1,Xwidth+1))
            centx = float(Xwidth+1)/2 - 0.5
            centy = float(Ywidth+1)/2 - 0.5
            fwhm = self.Cam.fwhm
            subapLocAux = subapLocation
            Aux = numpy.zeros((allsubaps,6))
            Aux[:,0:2] = subapLocAux[:,0:2] - subapLocation[0,0]
            Aux[:,3:5] = subapLocAux[:,3:5] - subapLocation[0,3]
            subapflag = FITS.Read(self.Cam.subapflag)[1]
            subapflag = subapflag.ravel()
            
            for y in range(0,Ywidth):
                for x in range(0,Xwidth):
                    self.minorpattern[y,x] = numpy.exp(-(pow(x-centx,2)+pow(y-centy,2))/(2*pow(fwhm/2.35482,2)))
                
            tracker = 0
            for subap in Aux:
                if(int(subapflag[tracker])):
                    self.majorpattern[subap[0]:subap[1]+1,subap[3]:subap[4]+1] += self.minorpattern
                tracker += 1

        patternshape = self.majorpattern.shape
        self.bbbc.star_on(star_id)
        s = Star(star_id)
        #image = self.grab('rtcCalPxlBuf',s.slope_iter)
        image = self.grab('rtcCalPxlBuf',1)
        image = image.reshape((self.Cam.pxly,self.Cam.pxlx))
        correlation = scipy.signal.fftconvolve(image,self.majorpattern,mode='same')
        argmx = numpy.unravel_index(correlation.argmax(),correlation.shape)
        print 'Pupil centre for star %d: '%(star_id),
        print [argmx[1],argmx[0]]
        print subapLocation[5,3]
        subapLocation[:,0:2] += argmx[0]
        subapLocation[:,3:5] += argmx[1]
        print subapLocation[5,3]


        #Saving values found and removing previous values
        files = os.listdir(self.Cam.subaplocation_path)
        files = [st for st in files if 'led_%d.fits'%(star_id) in st]
        if(files!=[]):
            for file_name in files:
                os.remove(self.Cam.subaplocation_path + file_name)
        FITS.Write(subapLocation,self.Cam.subaplocation_path + self.Cam.name+'_subapLocation_led_%d.fits'%(star_id),writeMode='w')

        FITS.Write(image,self.Cam.subaplocation_path + 'image_%d.fits'%(star_id),writeMode='w')
        FITS.Write(correlation,self.Cam.subaplocation_path + 'correlation_%d.fits'%(star_id),writeMode='w')
        FITS.Write(self.majorpattern,self.Cam.subaplocation_path + 'major.fits',writeMode='w')
        FITS.Write(self.minorpattern,self.Cam.subaplocation_path + 'minor.fits',writeMode='w')

        self.bbbc.star_off(star_id)

        subapflag = FITS.Read(self.Cam.subapflag)[1]
        subapflag = subapflag.ravel()
        v = subapflag.argmax()
        print '1st subap centre for star %d: '%(star_id),
        print [v,(subapLocation[v,3]+subapLocation[v,4])/2,(subapLocation[v,0]+subapLocation[v,1])/2]
        
        #return subapLocation
    
    def subap_calibration(self,star_id):
        '''
        Calibrates the subaps location for star_id
        using an existing subap location. Finds reference
        centroids.
        INPUT
        star_id[int]
        '''
        #4- Subaps
        self.bbbc.star_on(star_id)
        s = Star(star_id)
        if(s.valid):
            subapLocation = FITS.Read(self.Cam.subaplocation_path + self.Cam.name+'_subapLocation_led_%d.fits'%(star_id))[1]
            self.c.Set('subapLocation',subapLocation.astype(numpy.float32))
            self.c.Set("refCentroids",None)
            cent = self.grab('rtcCentBuf',s.slope_iter)
            subapLocation[:,3:5] += round(cent[::2].mean())
            subapLocation[:,0:2] += round(cent[1::2].mean())
            print '\nX subap correction: ',
            print round(cent[::2].mean())
            print 'Y subap correction: ',
            print round(cent[1::2].mean())

            #Saving values found and removing previous values
            files = os.listdir(self.Cam.subaplocation_path)
            files = [st for st in files if 'led_%d.fits'%(star_id) in st]
            if(files!=[]):
                for file_name in files:
                    os.remove(self.Cam.subaplocation_path + file_name)

            FITS.Write(subapLocation.astype(numpy.float32),self.Cam.subaplocation_path + self.Cam.name+'_subapLocation_led_%d.fits'%(star_id),writeMode='a')

            #5- Ref Cent
            self.c.Set('subapLocation',subapLocation.astype(numpy.float32))
            cent = self.grab('rtcCentBuf',s.slope_iter)

            #Saving values found and removing previous values
            files = os.listdir(self.Cam.refcent_path)
            files = [st for st in files if 'led_%d.fits'%(star_id) in st]
            if(files!=[]):
                for file_name in files:
                    os.remove(self.Cam.refcent_path + file_name)

            FITS.Write(cent.astype(numpy.float32),self.Cam.refcent_path+self.Cam.name+'_RefCent_led_%d.fits'%(star_id),writeMode='a')
            self.c.Set('refCentroids',cent.astype(numpy.float32))
        else:
            print 'No subaps for led_%d'%(star_id)
        self.bbbc.star_off(star_id)

    def routine_calibration(self,star_list):
        '''
        Calibrates useBrightest, backgrounds and exptime times
        for given stars
        '''
        #Main loop. Calibrates for each star
        self.bbbc.set_position('horizontal_altitude_layer',-10000,200)
        #First we flush
        print 'Flushing!'
        self.bbbc.flush_all_leds()
        print 'Done flushing.\nBg acquisition...'
        self.Set_useBrightest()
        for star_id in star_list:
            estrella = Star(star_id)
            if(estrella.valid):
                print '\nCalibrating star:%3.0f ' %star_id
                self.bgImage_exptime_calibration(star_id)

    def first_calibration(self,star_list):
        '''
        Calibrates useBrightest, backgrounds, exptime times,
        subap locations and reference centroids for given stars
        '''
        #Main loop. Calibrates for each star
        #First we flush
        self.bbbc.flush_all_leds()
        self.Set_useBrightest()
        for star_id in star_list:
            estrella = Star(star_id)
            if(estrella.valid):
                print '\nCalibrating star:%3.0f ' %star_id
                self.pupil_location(star_id)
                self.subap_calibration(star_id)
                self.bgImage_exptime_calibration(star_id)
        raw_input('First calibration concluded.\nSet phase screen and press enter to continue')


    def grab(self,stream,niter):
        taken = pp.unpack(self.c.GetStreamBlock(self.Cam.name+stream,niter)).sum(0)/float(niter)
        return taken