idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
24,600 | def handle_lut ( self , pkt ) : self . logger . debug ( "handle lut" ) if pkt . subunit & COMMAND : data_type = str ( pkt . nbytes / 2 ) + 'h' #size = struct.calcsize(data_type) line = pkt . datain . read ( pkt . nbytes ) n = len ( line ) if ( n < pkt . nbytes ) : return try : x = struct . unpack ( data_type , line ) except Exception as e : self . logger . error ( "Error unpacking struct: %s" % ( str ( e ) ) ) return if len ( x ) < 14 : # pad it with zeroes y = [ ] for i in range ( 14 ) : try : y . append ( x [ i ] ) except Exception : y . append ( 0 ) x = y del ( y ) if len ( x ) == 14 : z = int ( x [ 0 ] ) # frames start from 1, we start from 0 self . frame = self . decode_frameno ( z ) - 1 if ( self . frame > MAX_FRAMES ) : self . logger . error ( "attempt to select non existing frame." ) return # init the framebuffer #self.server.controller.init_frame(self.frame) try : self . server . controller . get_frame ( self . frame ) except KeyError : self . server . controller . init_frame ( self . frame ) return self . logger . error ( "unable to select a frame." ) return self . logger . error ( "what shall I do?" ) | This part of the protocol is used by IRAF to set the frame number . | 352 | 16 |
24,601 | def handle_imcursor ( self , pkt ) : self . logger . debug ( "handle imcursor" ) if pkt . tid & IIS_READ : if pkt . tid & IMC_SAMPLE : self . logger . debug ( "SAMPLE" ) # return the cursor position wcsflag = int ( pkt . z ) #wcsflag = 0 res = self . server . controller . get_keystroke ( ) self . return_cursor ( pkt . dataout , res . x , res . y , res . frame , wcsflag , '0' , '' ) else : self . logger . debug ( "OTHER" ) res = self . server . controller . get_keystroke ( ) self . logger . debug ( "FRAME=%d X,Y=%f,%f" % ( res . frame , res . x , res . y ) ) ## sx = self.x self . x = res . x self . y = res . y self . frame = res . frame ## sy = self.y ## frame = self.frame #wcsflag = 1 wcsflag = 0 #self.return_cursor(pkt.dataout, sx, sy, frame, 1, key, '') self . return_cursor ( pkt . dataout , res . x , res . y , res . frame , wcsflag , res . key , '' ) else : self . logger . debug ( "READ" ) # read the cursor position in logical coordinates sx = int ( pkt . x ) sy = int ( pkt . y ) wx = float ( pkt . x ) wy = float ( pkt . y ) wcs = int ( pkt . z ) if wcs : # decode the WCS info for the current frame try : fb = self . server . controller . get_frame ( self . frame ) except KeyError : # the selected frame does not exist, create it fb = self . server . controller . init_frame ( self . frame ) fb . ct = self . wcs_update ( fb . wcs ) if fb . ct . valid : if abs ( fb . ct . a ) > 0.001 : sx = int ( ( wx - fb . ct . tx ) / fb . ct . a ) if abs ( fb . ct . d ) > 0.001 : sy = int ( ( wy - fb . ct . ty ) / fb . ct . d ) self . server . controller . set_cursor ( sx , sy ) | This part of the protocol is used by IRAF to read the cursor position and keystrokes from the display client . | 564 | 24 |
24,602 | def handle ( self ) : self . logger = self . server . logger # create a packet structure packet = iis ( ) packet . datain = self . rfile packet . dataout = self . wfile # decode the header size = struct . calcsize ( '8h' ) line = packet . datain . read ( size ) n = len ( line ) if n < size : return while n > 0 : try : bytes = struct . unpack ( '8h' , line ) except Exception : self . logger . error ( 'error unpacking the data.' ) for exctn in sys . exc_info ( ) : print ( exctn ) # TODO: verify checksum # decode the packet fields subunit = bytes [ 2 ] subunit077 = subunit & 0o77 tid = bytes [ 0 ] x = bytes [ 4 ] & 0o177777 y = bytes [ 5 ] & 0o177777 z = bytes [ 6 ] & 0o177777 t = bytes [ 7 ] & 0o17777 ndatabytes = - bytes [ 1 ] # are the bytes packed? if ( not ( tid & PACKED ) ) : ndatabytes *= 2 # populate the packet structure packet . subunit = subunit packet . subunit077 = subunit077 packet . tid = tid packet . x = x packet . y = y packet . z = z packet . t = t packet . nbytes = ndatabytes # decide what to do, depending on the # value of subunit self . logger . debug ( "PACKET IS %o" % packet . subunit ) if packet . subunit077 == FEEDBACK : self . handle_feedback ( packet ) elif packet . subunit077 == LUT : self . handle_lut ( packet ) # read the next packet line = packet . datain . read ( size ) n = len ( line ) continue elif packet . subunit077 == MEMORY : self . handle_memory ( packet ) if self . needs_update : #self.display_image() pass # read the next packet line = packet . datain . read ( size ) n = len ( line ) continue elif packet . subunit077 == WCS : self . handle_wcs ( packet ) line = packet . datain . read ( size ) n = len ( line ) continue elif packet . subunit077 == IMCURSOR : self . handle_imcursor ( packet ) line = packet . datain . read ( size ) n = len ( line ) continue else : self . logger . debug ( '?NO OP (0%o)' % ( packet . subunit077 ) ) if not ( packet . tid & IIS_READ ) : # OK, discard the rest of the data nbytes = packet . nbytes while nbytes > 0 : # for (nbytes = ndatabytes; nbytes > 0; nbytes -= n): if nbytes < SZ_FIFOBUF : n = nbytes else : n = SZ_FIFOBUF m = self . rfile . read ( n ) if m <= 0 : break nbytes -= n # read the next packet line = packet . datain . read ( size ) n = len ( line ) if n < size : return # <--- end of the while (n) loop if self . needs_update : self . display_image ( ) self . needs_update = False | This is where the action starts . | 739 | 7 |
24,603 | def display_image ( self , reset = 1 ) : try : fb = self . server . controller . get_frame ( self . frame ) except KeyError : # the selected frame does not exist, create it fb = self . server . controller . init_frame ( self . frame ) if not fb . height : width = fb . width height = int ( len ( fb . buffer ) / width ) fb . height = height # display the image if ( len ( fb . buffer ) > 0 ) and ( height > 0 ) : self . server . controller . display ( self . frame , width , height , True ) else : self . server . controller . display ( self . frame , fb . width , fb . height , False ) | Utility routine used to display an updated frame from a framebuffer . | 162 | 14 |
24,604 | def _highlight_path ( self , hl_path , tf ) : fc = self . settings . get ( 'row_font_color' , 'green' ) try : self . treeview . highlight_path ( hl_path , tf , font_color = fc ) except Exception as e : self . logger . info ( 'Error changing highlight on treeview path ' '({0}): {1}' . format ( hl_path , str ( e ) ) ) | Highlight or unhighlight a single entry . | 106 | 10 |
24,605 | def update_highlights ( self , old_highlight_set , new_highlight_set ) : if not self . gui_up : return un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set # unhighlight entries that should NOT be highlighted any more for key in un_hilite_set : self . _highlight_path ( key , False ) # highlight new entries that should be for key in re_hilite_set : self . _highlight_path ( key , True ) | Unhighlight the entries represented by old_highlight_set and highlight the ones represented by new_highlight_set . | 139 | 26 |
24,606 | def show_selection ( self , star ) : try : # NOTE: this works around a quirk of Qt widget set where # selecting programatically in the table triggers the widget # selection callback (see select_star_cb() in Catalogs.py for Qt) self . _select_flag = True self . mark_selection ( star ) finally : self . _select_flag = False | This method is called when the user clicks on a plotted star in the fitsviewer . | 81 | 18 |
24,607 | def select_star_cb ( self , widget , res_dict ) : keys = list ( res_dict . keys ( ) ) if len ( keys ) == 0 : self . selected = [ ] self . replot_stars ( ) else : idx = int ( keys [ 0 ] ) star = self . starlist [ idx ] if not self . _select_flag : self . mark_selection ( star , fromtable = True ) return True | This method is called when the user selects a star from the table . | 96 | 14 |
24,608 | def _calc_order ( self , order ) : if order is not None and order != '' : self . order = order . upper ( ) else : shape = self . shape if len ( shape ) <= 2 : self . order = 'M' else : depth = shape [ - 1 ] # TODO: need something better here than a guess! if depth == 1 : self . order = 'M' elif depth == 2 : self . order = 'AM' elif depth == 3 : self . order = 'RGB' elif depth == 4 : self . order = 'RGBA' | Called to set the order of a multi - channel image . The order should be determined by the loader but this will make a best guess if passed order is None . | 126 | 34 |
24,609 | def cutout_data ( self , x1 , y1 , x2 , y2 , xstep = 1 , ystep = 1 , astype = None ) : view = np . s_ [ y1 : y2 : ystep , x1 : x2 : xstep ] data = self . _slice ( view ) if astype : data = data . astype ( astype , copy = False ) return data | cut out data area based on coords . | 90 | 9 |
24,610 | def get_shape_mask ( self , shape_obj ) : wd , ht = self . get_size ( ) yi = np . mgrid [ : ht ] . reshape ( - 1 , 1 ) xi = np . mgrid [ : wd ] . reshape ( 1 , - 1 ) pts = np . asarray ( ( xi , yi ) ) . T contains = shape_obj . contains_pts ( pts ) return contains | Return full mask where True marks pixels within the given shape . | 101 | 12 |
24,611 | def get_shape_view ( self , shape_obj , avoid_oob = True ) : x1 , y1 , x2 , y2 = [ int ( np . round ( n ) ) for n in shape_obj . get_llur ( ) ] if avoid_oob : # avoid out of bounds indexes wd , ht = self . get_size ( ) x1 , x2 = max ( 0 , x1 ) , min ( x2 , wd - 1 ) y1 , y2 = max ( 0 , y1 ) , min ( y2 , ht - 1 ) # calculate pixel containment mask in bbox yi = np . mgrid [ y1 : y2 + 1 ] . reshape ( - 1 , 1 ) xi = np . mgrid [ x1 : x2 + 1 ] . reshape ( 1 , - 1 ) pts = np . asarray ( ( xi , yi ) ) . T contains = shape_obj . contains_pts ( pts ) view = np . s_ [ y1 : y2 + 1 , x1 : x2 + 1 ] return ( view , contains ) | Calculate a bounding box in the data enclosing shape_obj and return a view that accesses it and a mask that is True only for pixels enclosed in the region . | 247 | 37 |
24,612 | def cutout_shape ( self , shape_obj ) : view , mask = self . get_shape_view ( shape_obj ) # cutout our enclosing (possibly shortened) bbox data = self . _slice ( view ) # mask non-containing members mdata = np . ma . array ( data , mask = np . logical_not ( mask ) ) return mdata | Cut out and return a portion of the data corresponding to shape_obj . A masked numpy array is returned where the pixels not enclosed in the shape are masked out . | 81 | 34 |
24,613 | def remove_callback ( self , name , fn , * args , * * kwargs ) : try : tup = ( fn , args , kwargs ) if tup in self . cb [ name ] : self . cb [ name ] . remove ( tup ) except KeyError : raise CallbackError ( "No callback category of '%s'" % ( name ) ) | Remove a specific callback that was added . | 83 | 8 |
24,614 | def cmap2pixmap ( cmap , steps = 50 ) : import numpy as np inds = np . linspace ( 0 , 1 , steps ) n = len ( cmap . clst ) - 1 tups = [ cmap . clst [ int ( x * n ) ] for x in inds ] rgbas = [ QColor ( int ( r * 255 ) , int ( g * 255 ) , int ( b * 255 ) , 255 ) . rgba ( ) for r , g , b in tups ] im = QImage ( steps , 1 , QImage . Format_Indexed8 ) im . setColorTable ( rgbas ) for i in range ( steps ) : im . setPixel ( i , 0 , i ) im = im . scaled ( 128 , 32 ) pm = QPixmap . fromImage ( im ) return pm | Convert a Ginga colormap into a QPixmap | 186 | 14 |
24,615 | def start ( self , duration = None ) : if duration is None : duration = self . duration self . set ( duration ) | Start the timer . If duration is not None it should specify the time to expiration in seconds . | 26 | 19 |
24,616 | def _snap_cb ( self , w ) : # Clear the snap image viewer self . scrnimage . clear ( ) self . scrnimage . redraw_now ( whence = 0 ) self . fv . update_pending ( ) format = self . tosave_type if self . _screen_size : # snap image using actual viewer self . fv . error_wrap ( self . fitsimage . save_rgb_image_as_file , self . tmpname , format = format ) else : # we will be using shot generator, not actual viewer. # check that shot generator size matches UI params self . check_and_adjust_dimensions ( ) # copy background color of viewer to shot generator bg = self . fitsimage . get_bg ( ) self . shot_generator . set_bg ( * bg ) # add the main canvas from channel viewer to shot generator c1 = self . fitsimage . get_canvas ( ) c2 = self . shot_generator . get_canvas ( ) c2 . delete_all_objects ( redraw = False ) c2 . add ( c1 , redraw = False ) # hack to fix a few problem graphics self . shot_generator . _imgobj = self . fitsimage . _imgobj # scale of the shot generator should be the scale of channel # viewer multiplied by the ratio of window sizes scale_x , scale_y = self . fitsimage . get_scale_xy ( ) c1_wd , c1_ht = self . fitsimage . get_window_size ( ) c2_wd , c2_ht = self . shot_generator . get_window_size ( ) scale_wd = float ( c2_wd ) / float ( c1_wd ) scale_ht = float ( c2_ht ) / float ( c1_ht ) scale = max ( scale_wd , scale_ht ) scale_x *= scale scale_y *= scale self . shot_generator . scale_to ( scale_x , scale_y ) self . fitsimage . copy_attributes ( self . shot_generator , self . transfer_attrs ) # snap image self . fv . error_wrap ( self . shot_generator . save_rgb_image_as_file , self . tmpname , format = format ) c2 . delete_all_objects ( redraw = False ) self . shot_generator . _imgobj = None self . saved_type = format img = RGBImage ( logger = self . logger ) img . load_file ( self . tmpname ) # load the snapped image into the screenshot viewer self . scrnimage . set_image ( img ) | This function is called when the user clicks the Snap button . | 583 | 12 |
24,617 | def _save_cb ( self , w ) : format = self . saved_type if format is None : return self . fv . show_error ( "Please save an image first." ) # create filename filename = self . w . name . get_text ( ) . strip ( ) if len ( filename ) == 0 : return self . fv . show_error ( "Please set a name for saving the file" ) self . save_name = filename if not filename . lower ( ) . endswith ( '.' + format ) : filename = filename + '.' + format # join to path path = self . w . folder . get_text ( ) . strip ( ) if path == '' : path = filename else : self . save_path = path path = os . path . join ( path , filename ) # copy last saved file self . fv . error_wrap ( shutil . copyfile , self . tmpname , path ) | This function is called when the user clicks the Save button . We save the last taken shot to the folder and name specified . | 200 | 25 |
24,618 | def _lock_aspect_cb ( self , w , tf ) : self . _lock_aspect = tf self . w . aspect . set_enabled ( tf ) if self . _lock_aspect : self . _set_aspect_cb ( ) else : wd , ht = self . get_wdht ( ) _as = self . calc_aspect_str ( wd , ht ) self . w . aspect . set_text ( _as ) | This function is called when the user clicks the Lock aspect checkbox . tf is True if checked False otherwise . | 104 | 22 |
24,619 | def _screen_size_cb ( self , w , tf ) : self . _screen_size = tf self . w . width . set_enabled ( not tf ) self . w . height . set_enabled ( not tf ) self . w . lock_aspect . set_enabled ( not tf ) if self . _screen_size : wd , ht = self . fitsimage . get_window_size ( ) self . _configure_cb ( self . fitsimage , wd , ht ) | This function is called when the user clicks the Screen size checkbox . tf is True if checked False otherwise . | 110 | 22 |
24,620 | def load_asdf ( asdf_obj , data_key = 'sci' , wcs_key = 'wcs' , header_key = 'meta' ) : asdf_keys = asdf_obj . keys ( ) if wcs_key in asdf_keys : wcs = asdf_obj [ wcs_key ] else : wcs = None if header_key in asdf_keys : ahdr = asdf_obj [ header_key ] else : ahdr = { } # TODO: What about non-image ASDF data, such as table? if data_key in asdf_keys : data = np . asarray ( asdf_obj [ data_key ] ) else : data = None return data , wcs , ahdr | Load from an ASDF object . | 166 | 7 |
24,621 | def _match_cmap ( self , fitsimage , colorbar ) : rgbmap = fitsimage . get_rgbmap ( ) loval , hival = fitsimage . get_cut_levels ( ) colorbar . set_range ( loval , hival ) # If we are sharing a ColorBar for all channels, then store # to change the ColorBar's rgbmap to match our colorbar . set_rgbmap ( rgbmap ) | Help method to change the ColorBar to match the cut levels or colormap used in a ginga ImageView . | 96 | 25 |
24,622 | def rgbmap_cb ( self , rgbmap , channel ) : if not self . gui_up : return fitsimage = channel . fitsimage if fitsimage != self . fv . getfocus_fitsimage ( ) : return False self . change_cbar ( self . fv , channel ) | This method is called when the RGBMap is changed . We update the ColorBar to match . | 63 | 19 |
24,623 | def show_mode_indicator ( viewer , tf , corner = 'ur' ) : tag = '_$mode_indicator' canvas = viewer . get_private_canvas ( ) try : indic = canvas . get_object_by_tag ( tag ) if not tf : canvas . delete_object_by_tag ( tag ) else : indic . corner = corner except KeyError : if tf : # force a redraw if the mode changes bm = viewer . get_bindmap ( ) bm . add_callback ( 'mode-set' , lambda * args : viewer . redraw ( whence = 3 ) ) Indicator = canvas . get_draw_class ( 'modeindicator' ) canvas . add ( Indicator ( corner = corner ) , tag = tag , redraw = False ) canvas . update_canvas ( whence = 3 ) | Show a keyboard mode indicator in one of the corners . | 183 | 11 |
24,624 | def show_color_bar ( viewer , tf , side = 'bottom' ) : tag = '_$color_bar' canvas = viewer . get_private_canvas ( ) try : cbar = canvas . get_object_by_tag ( tag ) if not tf : canvas . delete_object_by_tag ( tag ) else : cbar . side = side except KeyError : if tf : Cbar = canvas . get_draw_class ( 'colorbar' ) canvas . add ( Cbar ( side = side ) , tag = tag , redraw = False ) canvas . update_canvas ( whence = 3 ) | Show a color bar in the window . | 135 | 8 |
24,625 | def show_focus_indicator ( viewer , tf , color = 'white' ) : tag = '_$focus_indicator' canvas = viewer . get_private_canvas ( ) try : fcsi = canvas . get_object_by_tag ( tag ) if not tf : canvas . delete_object_by_tag ( tag ) else : fcsi . color = color except KeyError : if tf : Fcsi = canvas . get_draw_class ( 'focusindicator' ) fcsi = Fcsi ( color = color ) canvas . add ( fcsi , tag = tag , redraw = False ) viewer . add_callback ( 'focus' , fcsi . focus_cb ) canvas . update_canvas ( whence = 3 ) | Show a focus indicator in the window . | 167 | 8 |
24,626 | def add_zoom_buttons ( viewer , canvas = None , color = 'black' ) : def zoom ( box , canvas , event , pt , viewer , n ) : zl = viewer . get_zoom ( ) zl += n if zl == 0.0 : zl += n viewer . zoom_to ( zl + n ) def add_buttons ( viewer , canvas , tag ) : objs = [ ] wd , ht = viewer . get_window_size ( ) SquareBox = canvas . get_draw_class ( 'squarebox' ) Text = canvas . get_draw_class ( 'text' ) Compound = canvas . get_draw_class ( 'compoundobject' ) x1 , y1 = wd - 20 , ht // 2 + 20 zoomin = SquareBox ( x1 , y1 , 15 , color = 'yellow' , fill = True , fillcolor = 'gray' , fillalpha = 0.5 , coord = 'window' ) zoomin . editable = False zoomin . pickable = True zoomin . add_callback ( 'pick-down' , zoom , viewer , 1 ) objs . append ( zoomin ) x2 , y2 = wd - 20 , ht // 2 - 20 zoomout = SquareBox ( x2 , y2 , 15 , color = 'yellow' , fill = True , fillcolor = 'gray' , fillalpha = 0.5 , coord = 'window' ) zoomout . editable = False zoomout . pickable = True zoomout . add_callback ( 'pick-down' , zoom , viewer , - 1 ) objs . append ( zoomout ) objs . append ( Text ( x1 - 4 , y1 + 6 , text = '+' , fontsize = 18 , color = color , coord = 'window' ) ) objs . append ( Text ( x2 - 4 , y2 + 6 , text = '--' , fontsize = 18 , color = color , coord = 'window' ) ) obj = Compound ( * objs ) obj . opaque = False canvas . add ( obj , tag = tag ) def zoom_resize ( viewer , width , height , canvas , tag ) : try : canvas . get_object_by_tag ( tag ) except KeyError : return False canvas . delete_object_by_tag ( tag ) add_buttons ( viewer , canvas , tag ) tag = '_$zoom_buttons' if canvas is None : canvas = viewer . get_private_canvas ( ) canvas . ui_set_active ( True ) canvas . register_for_cursor_drawing ( viewer ) canvas . set_draw_mode ( 'pick' ) viewer . add_callback ( 'configure' , zoom_resize , canvas , tag ) add_buttons ( viewer , canvas , tag ) | Add zoom buttons to a canvas . | 619 | 7 |
24,627 | def expose_event ( self , widget , event ) : x , y , width , height = event . area self . logger . debug ( "surface is %s" % self . surface ) if self . surface is not None : win = widget . get_window ( ) cr = win . cairo_create ( ) # set clip area for exposed region cr . rectangle ( x , y , width , height ) cr . clip ( ) # Paint from off-screen surface cr . set_source_surface ( self . surface , 0 , 0 ) cr . set_operator ( cairo . OPERATOR_SOURCE ) cr . paint ( ) return False | When an area of the window is exposed we just copy out of the server - side off - screen surface to that area . | 135 | 25 |
24,628 | def size_request ( self , widget , requisition ) : requisition . width , requisition . height = self . get_desired_size ( ) return True | Callback function to request our desired size . | 35 | 8 |
24,629 | def get_plugin_spec ( self , name ) : l_name = name . lower ( ) for spec in self . plugins : name = spec . get ( 'name' , spec . get ( 'klass' , spec . module ) ) if name . lower ( ) == l_name : return spec raise KeyError ( name ) | Get the specification attributes for plugin with name name . | 71 | 10 |
24,630 | def help_text ( self , name , text , text_kind = 'plain' , trim_pfx = 0 ) : if trim_pfx > 0 : # caller wants to trim some space off the front # of each line text = toolbox . trim_prefix ( text , trim_pfx ) if text_kind == 'rst' : # try to convert RST to HTML using docutils try : overrides = { 'input_encoding' : 'ascii' , 'output_encoding' : 'utf-8' } text_html = publish_string ( text , writer_name = 'html' , settings_overrides = overrides ) # docutils produces 'bytes' output, but webkit needs # a utf-8 string text = text_html . decode ( 'utf-8' ) text_kind = 'html' except Exception as e : self . logger . error ( "Error converting help text to HTML: %s" % ( str ( e ) ) ) # revert to showing RST as plain text else : raise ValueError ( "I don't know how to display text of kind '%s'" % ( text_kind ) ) if text_kind == 'html' : self . help ( text = text , text_kind = 'html' ) else : self . show_help_text ( name , text ) | Provide help text for the user . | 292 | 8 |
24,631 | def load_file ( self , filepath , chname = None , wait = True , create_channel = True , display_image = True , image_loader = None ) : if not chname : channel = self . get_current_channel ( ) else : if not self . has_channel ( chname ) and create_channel : self . gui_call ( self . add_channel , chname ) channel = self . get_channel ( chname ) chname = channel . name if image_loader is None : image_loader = self . load_image cache_dir = self . settings . get ( 'download_folder' , self . tmpdir ) info = iohelper . get_fileinfo ( filepath , cache_dir = cache_dir ) # check that file is locally accessible if not info . ondisk : errmsg = "File must be locally loadable: %s" % ( filepath ) self . gui_do ( self . show_error , errmsg ) return filepath = info . filepath kwargs = { } idx = None if info . numhdu is not None : kwargs [ 'idx' ] = info . numhdu try : image = image_loader ( filepath , * * kwargs ) except Exception as e : errmsg = "Failed to load '%s': %s" % ( filepath , str ( e ) ) self . gui_do ( self . show_error , errmsg ) return future = Future . Future ( ) future . freeze ( image_loader , filepath , * * kwargs ) # Save a future for this image to reload it later if we # have to remove it from memory image . set ( loader = image_loader , image_future = future ) if image . get ( 'path' , None ) is None : image . set ( path = filepath ) # Assign a name to the image if the loader did not. name = image . get ( 'name' , None ) if name is None : name = iohelper . name_image_from_path ( filepath , idx = idx ) image . set ( name = name ) if display_image : # Display image. If the wait parameter is False then don't wait # for the image to load into the viewer if wait : self . gui_call ( self . add_image , name , image , chname = chname ) else : self . gui_do ( self . add_image , name , image , chname = chname ) else : self . gui_do ( self . bulk_add_image , name , image , chname ) # Return the image return image | Load a file and display it . | 568 | 7 |
24,632 | def add_download ( self , info , future ) : if self . gpmon . has_plugin ( 'Downloads' ) : obj = self . gpmon . get_plugin ( 'Downloads' ) self . gui_do ( obj . add_download , info , future ) else : self . show_error ( "Please activate the 'Downloads' plugin to" " enable download functionality" ) | Hand off a download to the Downloads plugin if it is present . | 85 | 13 |
24,633 | def open_file_cont ( self , pathspec , loader_cont_fn ) : info = iohelper . get_fileinfo ( pathspec ) filepath = info . filepath if not os . path . exists ( filepath ) : errmsg = "File does not appear to exist: '%s'" % ( filepath ) self . gui_do ( self . show_error , errmsg ) return try : typ , subtyp = iohelper . guess_filetype ( filepath ) except Exception as e : self . logger . warning ( "error determining file type: %s; " "assuming 'image/fits'" % ( str ( e ) ) ) # Can't determine file type: assume and attempt FITS typ , subtyp = 'image' , 'fits' mimetype = "%s/%s" % ( typ , subtyp ) try : opener_class = loader . get_opener ( mimetype ) except KeyError : # TODO: here pop up a dialog asking which loader to use errmsg = "No registered opener for: '%s'" % ( mimetype ) self . gui_do ( self . show_error , errmsg ) return # kwd args to pass to opener kwargs = dict ( ) inherit_prihdr = self . settings . get ( 'inherit_primary_header' , False ) kwargs [ 'inherit_primary_header' ] = inherit_prihdr # open the file and load the items named by the index opener = opener_class ( self . logger ) try : with opener . open_file ( filepath ) as io_f : io_f . load_idx_cont ( info . idx , loader_cont_fn , * * kwargs ) except Exception as e : errmsg = "Error opening '%s': %s" % ( filepath , str ( e ) ) try : ( type , value , tb ) = sys . exc_info ( ) tb_str = "\n" . join ( traceback . format_tb ( tb ) ) except Exception as e : tb_str = "Traceback information unavailable." self . gui_do ( self . show_error , errmsg + '\n' + tb_str ) | Open a file and do some action on it . | 491 | 10 |
24,634 | def open_uris ( self , uris , chname = None , bulk_add = False ) : if len ( uris ) == 0 : return if chname is None : channel = self . get_channel_info ( ) if channel is None : # No active channel to load these into return chname = channel . name channel = self . get_channel_on_demand ( chname ) def show_dataobj_bulk ( data_obj ) : self . gui_do ( channel . add_image , data_obj , bulk_add = True ) def load_file_bulk ( filepath ) : self . nongui_do ( self . open_file_cont , filepath , show_dataobj_bulk ) def show_dataobj ( data_obj ) : self . gui_do ( channel . add_image , data_obj , bulk_add = False ) def load_file ( filepath ) : self . nongui_do ( self . open_file_cont , filepath , show_dataobj ) # determine whether first file is loaded as a bulk load if bulk_add : self . open_uri_cont ( uris [ 0 ] , load_file_bulk ) else : self . open_uri_cont ( uris [ 0 ] , load_file ) self . update_pending ( ) for uri in uris [ 1 : ] : # rest of files are all loaded using bulk load self . open_uri_cont ( uri , load_file_bulk ) self . update_pending ( ) | Open a set of URIs . | 338 | 7 |
24,635 | def zoom_in ( self ) : viewer = self . getfocus_viewer ( ) if hasattr ( viewer , 'zoom_in' ) : viewer . zoom_in ( ) return True | Zoom the view in one zoom step . | 42 | 9 |
24,636 | def zoom_out ( self ) : viewer = self . getfocus_viewer ( ) if hasattr ( viewer , 'zoom_out' ) : viewer . zoom_out ( ) return True | Zoom the view out one zoom step . | 42 | 9 |
24,637 | def zoom_fit ( self ) : viewer = self . getfocus_viewer ( ) if hasattr ( viewer , 'zoom_fit' ) : viewer . zoom_fit ( ) return True | Zoom the view to fit the image entirely in the window . | 42 | 13 |
24,638 | def prev_img_ws ( self , ws , loop = True ) : channel = self . get_active_channel_ws ( ws ) if channel is None : return channel . prev_image ( ) return True | Go to the previous image in the focused channel in the workspace . | 47 | 13 |
24,639 | def next_img_ws ( self , ws , loop = True ) : channel = self . get_active_channel_ws ( ws ) if channel is None : return channel . next_image ( ) return True | Go to the next image in the focused channel in the workspace . | 47 | 13 |
24,640 | def prev_img ( self , loop = True ) : channel = self . get_current_channel ( ) if channel is None : self . show_error ( "Please create a channel." , raisetab = True ) return channel . prev_image ( ) return True | Go to the previous image in the channel . | 58 | 9 |
24,641 | def next_img ( self , loop = True ) : channel = self . get_current_channel ( ) if channel is None : self . show_error ( "Please create a channel." , raisetab = True ) return channel . next_image ( ) return True | Go to the next image in the channel . | 58 | 9 |
24,642 | def close_plugins ( self , channel ) : opmon = channel . opmon for key in opmon . get_active ( ) : obj = opmon . get_plugin ( key ) try : self . gui_call ( obj . close ) except Exception as e : self . logger . error ( "Failed to continue operation: %s" % ( str ( e ) ) ) | Close all plugins associated with the channel . | 81 | 8 |
24,643 | def add_channel ( self , chname , workspace = None , num_images = None , settings = None , settings_template = None , settings_share = None , share_keylist = None ) : with self . lock : if self . has_channel ( chname ) : return self . get_channel ( chname ) if chname in self . ds . get_tabnames ( None ) : raise ValueError ( "Tab name already in use: '%s'" % ( chname ) ) name = chname if settings is None : settings = self . prefs . create_category ( 'channel_' + name ) try : settings . load ( onError = 'raise' ) except Exception as e : self . logger . warning ( "no saved preferences found for channel " "'%s': %s" % ( name , str ( e ) ) ) # copy template settings to new channel if settings_template is not None : osettings = settings_template osettings . copy_settings ( settings ) else : try : # use channel_Image as a template if one was not # provided osettings = self . prefs . get_settings ( 'channel_Image' ) self . logger . debug ( "Copying settings from 'Image' to " "'%s'" % ( name ) ) osettings . copy_settings ( settings ) except KeyError : pass if ( share_keylist is not None ) and ( settings_share is not None ) : # caller wants us to share settings with another viewer settings_share . share_settings ( settings , keylist = share_keylist ) # Make sure these preferences are at least defined if num_images is None : num_images = settings . get ( 'numImages' , self . settings . get ( 'numImages' , 1 ) ) settings . set_defaults ( switchnew = True , numImages = num_images , raisenew = True , genthumb = True , focus_indicator = False , preload_images = False , sort_order = 'loadtime' ) self . logger . debug ( "Adding channel '%s'" % ( chname ) ) channel = Channel ( chname , self , datasrc = None , settings = settings ) bnch = self . add_viewer ( chname , settings , workspace = workspace ) # for debugging bnch . image_viewer . set_name ( 'channel:%s' % ( chname ) ) opmon = self . get_plugin_manager ( self . logger , self , self . ds , self . mm ) channel . widget = bnch . widget channel . container = bnch . container channel . workspace = bnch . workspace channel . connect_viewer ( bnch . image_viewer ) channel . viewer = bnch . image_viewer # older name, should eventually be deprecated channel . fitsimage = bnch . image_viewer channel . opmon = opmon name = chname . lower ( ) self . channel [ name ] = channel # Update the channels control self . channel_names . append ( chname ) self . channel_names . sort ( ) if len ( self . channel_names ) == 1 : self . cur_channel = channel # Prepare local plugins for this channel for spec in self . get_plugins ( ) : opname = spec . get ( 'klass' , spec . get ( 'module' ) ) if spec . get ( 'ptype' , 'global' ) == 'local' : opmon . load_plugin ( opname , spec , chinfo = channel ) self . make_gui_callback ( 'add-channel' , channel ) return channel | Create a new Ginga channel . | 783 | 7 |
24,644 | def delete_channel ( self , chname ) : name = chname . lower ( ) if len ( self . channel_names ) < 1 : self . logger . error ( 'Delete channel={0} failed. ' 'No channels left.' . format ( chname ) ) return with self . lock : channel = self . channel [ name ] # Close local plugins open on this channel self . close_plugins ( channel ) try : idx = self . channel_names . index ( chname ) except ValueError : idx = 0 # Update the channels control self . channel_names . remove ( channel . name ) self . channel_names . sort ( ) self . ds . remove_tab ( chname ) del self . channel [ name ] self . prefs . remove_settings ( 'channel_' + chname ) # pick new channel num_channels = len ( self . channel_names ) if num_channels > 0 : if idx >= num_channels : idx = num_channels - 1 self . change_channel ( self . channel_names [ idx ] ) else : self . cur_channel = None self . make_gui_callback ( 'delete-channel' , channel ) | Delete a given channel from viewer . | 258 | 7 |
24,645 | def add_menu ( self , name ) : if self . menubar is None : raise ValueError ( "No menu bar configured" ) return self . menubar . add_name ( name ) | Add a menu with name name to the global menu bar . Returns a menu widget . | 43 | 17 |
24,646 | def get_menu ( self , name ) : if self . menubar is None : raise ValueError ( "No menu bar configured" ) return self . menubar . get_menu ( name ) | Get the menu with name name from the global menu bar . Returns a menu widget . | 43 | 17 |
24,647 | def register_viewer ( self , vclass ) : self . viewer_db [ vclass . vname ] = Bunch . Bunch ( vname = vclass . vname , vclass = vclass , vtypes = vclass . vtypes ) | Register a channel viewer with the reference viewer . vclass is the class of the viewer . | 55 | 18 |
24,648 | def get_viewer_names ( self , dataobj ) : res = [ ] for bnch in self . viewer_db . values ( ) : for vtype in bnch . vtypes : if isinstance ( dataobj , vtype ) : res . append ( bnch . vname ) return res | Returns a list of viewer names that are registered that can view dataobj . | 68 | 15 |
24,649 | def make_viewer ( self , vname , channel ) : if vname not in self . viewer_db : raise ValueError ( "I don't know how to build a '%s' viewer" % ( vname ) ) stk_w = channel . widget bnch = self . viewer_db [ vname ] viewer = bnch . vclass ( logger = self . logger , settings = channel . settings ) stk_w . add_widget ( viewer . get_widget ( ) , title = vname ) # let the GUI respond to this widget addition self . update_pending ( ) # let the channel object do any necessary initialization channel . connect_viewer ( viewer ) # finally, let the viewer do any viewer-side initialization viewer . initialize_channel ( self , channel ) | Make a viewer whose type name is vname and add it to channel . | 171 | 15 |
24,650 | def collapse_pane ( self , side ) : # TODO: this is too tied to one configuration, need to figure # out how to generalize this hsplit = self . w [ 'hpnl' ] sizes = hsplit . get_sizes ( ) lsize , msize , rsize = sizes if self . _lsize is None : self . _lsize , self . _rsize = lsize , rsize self . logger . debug ( "left=%d mid=%d right=%d" % ( lsize , msize , rsize ) ) if side == 'right' : if rsize < 10 : # restore pane rsize = self . _rsize msize -= rsize else : # minimize pane self . _rsize = rsize msize += rsize rsize = 0 elif side == 'left' : if lsize < 10 : # restore pane lsize = self . _lsize msize -= lsize else : # minimize pane self . _lsize = lsize msize += lsize lsize = 0 hsplit . set_sizes ( [ lsize , msize , rsize ] ) | Toggle collapsing the left or right panes . | 246 | 10 |
24,651 | def quit ( self , * args ) : self . logger . info ( "Attempting to shut down the application..." ) if self . layout_file is not None : self . error_wrap ( self . ds . write_layout_conf , self . layout_file ) self . stop ( ) self . w . root = None while len ( self . ds . toplevels ) > 0 : w = self . ds . toplevels . pop ( ) w . delete ( ) | Quit the application . | 106 | 5 |
24,652 | def showxy ( self , viewer , data_x , data_y ) : # This is an optimization to get around slow coordinate # transformation by astropy and possibly other WCS packages, # which causes delay for other mouse tracking events, e.g. # the zoom plugin. # We only update the under cursor information every period # defined by (self.cursor_interval) sec. # # If the refresh interval has expired then update the info; # otherwise (re)set the timer until the end of the interval. cur_time = time . time ( ) elapsed = cur_time - self . _cursor_last_update if elapsed > self . cursor_interval : # cancel timer self . _cursor_task . clear ( ) self . gui_do_oneshot ( 'field-info' , self . _showxy , viewer , data_x , data_y ) else : # store needed data into the timer data area self . _cursor_task . data . setvals ( viewer = viewer , data_x = data_x , data_y = data_y ) # calculate delta until end of refresh interval period = self . cursor_interval - elapsed # set timer conditionally (only if it hasn't yet been set) self . _cursor_task . cond_set ( period ) return True | Called by the mouse - tracking callback to handle reporting of cursor position to various plugins that subscribe to the field - info callback . | 281 | 26 |
24,653 | def _cursor_timer_cb ( self , timer ) : data = timer . data self . gui_do_oneshot ( 'field-info' , self . _showxy , data . viewer , data . data_x , data . data_y ) | Callback when the cursor timer expires . | 56 | 7 |
24,654 | def _showxy ( self , viewer , data_x , data_y ) : self . _cursor_last_update = time . time ( ) try : image = viewer . get_image ( ) if ( image is None ) or not isinstance ( image , BaseImage . BaseImage ) : # No compatible image loaded for this channel return settings = viewer . get_settings ( ) info = image . info_xy ( data_x , data_y , settings ) # Are we reporting in data or FITS coordinates? off = self . settings . get ( 'pixel_coords_offset' , 0.0 ) info . x += off info . y += off except Exception as e : self . logger . warning ( "Can't get info under the cursor: %s" % ( str ( e ) ) ) return # TODO: can this be made more efficient? chname = self . get_channel_name ( viewer ) channel = self . get_channel ( chname ) self . make_callback ( 'field-info' , channel , info ) self . update_pending ( ) return True | Update the info from the last position recorded under the cursor . | 235 | 12 |
24,655 | def motion_cb ( self , viewer , button , data_x , data_y ) : self . showxy ( viewer , data_x , data_y ) return True | Motion event in the channel viewer window . Show the pointing information under the cursor . | 37 | 16 |
24,656 | def keypress ( self , viewer , event , data_x , data_y ) : keyname = event . key chname = self . get_channel_name ( viewer ) self . logger . debug ( "key press (%s) in channel %s" % ( keyname , chname ) ) # TODO: keyboard accelerators to raise tabs need to be integrated into # the desktop object if keyname == 'Z' : self . ds . raise_tab ( 'Zoom' ) ## elif keyname == 'T': ## self.ds.raise_tab('Thumbs') elif keyname == 'I' : self . ds . raise_tab ( 'Info' ) elif keyname == 'H' : self . ds . raise_tab ( 'Header' ) elif keyname == 'C' : self . ds . raise_tab ( 'Contents' ) elif keyname == 'D' : self . ds . raise_tab ( 'Dialogs' ) elif keyname == 'F' : self . build_fullscreen ( ) elif keyname == 'f' : self . toggle_fullscreen ( ) elif keyname == 'm' : self . maximize ( ) elif keyname == '<' : self . collapse_pane ( 'left' ) elif keyname == '>' : self . collapse_pane ( 'right' ) elif keyname == 'n' : self . next_channel ( ) elif keyname == 'J' : self . cycle_workspace_type ( ) elif keyname == 'k' : self . add_channel_auto ( ) elif keyname == 'K' : self . remove_channel_auto ( ) elif keyname == 'f1' : self . show_channel_names ( ) ## elif keyname == 'escape': ## self.reset_viewer() elif keyname in ( 'up' , ) : self . prev_img ( ) elif keyname in ( 'down' , ) : self . next_img ( ) elif keyname in ( 'left' , ) : self . prev_channel ( ) elif keyname in ( 'right' , ) : self . next_channel ( ) return True | Key press event in a channel window . | 488 | 8 |
24,657 | def show_channel_names ( self ) : for name in self . get_channel_names ( ) : channel = self . get_channel ( name ) channel . fitsimage . onscreen_message ( name , delay = 2.5 ) | Show each channel s name in its image viewer . Useful in grid or stack workspace type to identify which window is which . | 51 | 24 |
24,658 | def _short_color_list ( self ) : return [ c for c in colors . get_colors ( ) if not re . search ( r'\d' , c ) ] | Color list is too long . Discard variations with numbers . | 40 | 12 |
24,659 | def _get_markobj ( self , x , y , marktype , marksize , markcolor , markwidth ) : if marktype == 'circle' : obj = self . dc . Circle ( x = x , y = y , radius = marksize , color = markcolor , linewidth = markwidth ) elif marktype in ( 'cross' , 'plus' ) : obj = self . dc . Point ( x = x , y = y , radius = marksize , color = markcolor , linewidth = markwidth , style = marktype ) elif marktype == 'box' : obj = self . dc . Box ( x = x , y = y , xradius = marksize , yradius = marksize , color = markcolor , linewidth = markwidth ) else : # point, marksize obj = self . dc . Box ( x = x , y = y , xradius = 1 , yradius = 1 , color = markcolor , linewidth = markwidth , fill = True , fillcolor = markcolor ) return obj | Generate canvas object for given mark parameters . | 226 | 9 |
24,660 | def clear_marking ( self ) : if self . marktag : try : self . canvas . delete_object_by_tag ( self . marktag , redraw = False ) except Exception : pass if self . markhltag : try : self . canvas . delete_object_by_tag ( self . markhltag , redraw = False ) except Exception : pass self . treeview . clear ( ) # Clear table too self . w . nshown . set_text ( '0' ) self . fitsimage . redraw ( ) | Clear marking from image . This does not clear loaded coordinates from memory . | 117 | 14 |
24,661 | def load_file ( self , filename ) : if not os . path . isfile ( filename ) : return self . logger . info ( 'Loading coordinates from {0}' . format ( filename ) ) if filename . endswith ( '.fits' ) : fmt = 'fits' else : # Assume ASCII fmt = 'ascii' try : tab = Table . read ( filename , format = fmt ) except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ , str ( e ) ) ) return if self . use_radec : colname0 = self . settings . get ( 'ra_colname' , 'ra' ) colname1 = self . settings . get ( 'dec_colname' , 'dec' ) else : colname0 = self . settings . get ( 'x_colname' , 'x' ) colname1 = self . settings . get ( 'y_colname' , 'y' ) try : col_0 = tab [ colname0 ] col_1 = tab [ colname1 ] except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ , str ( e ) ) ) return nrows = len ( col_0 ) dummy_col = [ None ] * nrows try : oldrows = int ( self . w . ntotal . get_text ( ) ) except ValueError : oldrows = 0 self . w . ntotal . set_text ( str ( oldrows + nrows ) ) if self . use_radec : ra = self . _convert_radec ( col_0 ) dec = self . _convert_radec ( col_1 ) x = y = dummy_col else : ra = dec = dummy_col # X and Y always 0-indexed internally x = col_0 . data - self . pixelstart y = col_1 . data - self . pixelstart args = [ ra , dec , x , y ] # Load extra columns for colname in self . extra_columns : try : col = tab [ colname ] . data except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ , str ( e ) ) ) col = dummy_col args . append ( col ) # Use list to preserve order. Does not handle duplicates. key = ( self . marktype , self . marksize , self . markcolor ) self . coords_dict [ key ] += list ( zip ( * args ) ) self . redo ( ) | Load coordinates file . | 577 | 4 |
24,662 | def _convert_radec ( self , val ) : try : ans = val . to ( 'deg' ) except Exception as e : self . logger . error ( 'Cannot convert, assume already in degrees' ) ans = val . data else : ans = ans . value return ans | Convert RA or DEC table column to degrees and extract data . Assume already in degrees if cannot convert . | 61 | 22 |
24,663 | def hl_table2canvas ( self , w , res_dict ) : objlist = [ ] width = self . markwidth + self . _dwidth # Remove existing highlight if self . markhltag : try : self . canvas . delete_object_by_tag ( self . markhltag , redraw = False ) except Exception : pass # Display highlighted entries only in second table self . treeviewsel . set_tree ( res_dict ) for kstr , sub_dict in res_dict . items ( ) : s = kstr . split ( ',' ) marktype = s [ 0 ] marksize = float ( s [ 1 ] ) markcolor = s [ 2 ] for bnch in sub_dict . values ( ) : obj = self . _get_markobj ( bnch . X - self . pixelstart , bnch . Y - self . pixelstart , marktype , marksize , markcolor , width ) objlist . append ( obj ) nsel = len ( objlist ) self . w . nselected . set_text ( str ( nsel ) ) # Draw on canvas if nsel > 0 : self . markhltag = self . canvas . add ( self . dc . CompoundObject ( * objlist ) ) self . fitsimage . redraw ( ) | Highlight marking on canvas when user click on table . | 282 | 11 |
24,664 | def hl_canvas2table_box ( self , canvas , tag ) : self . treeview . clear_selection ( ) # Remove existing box cobj = canvas . get_object_by_tag ( tag ) if cobj . kind != 'rectangle' : return canvas . delete_object_by_tag ( tag , redraw = False ) # Remove existing highlight if self . markhltag : try : canvas . delete_object_by_tag ( self . markhltag , redraw = True ) except Exception : pass # Nothing to do if no markings are displayed try : obj = canvas . get_object_by_tag ( self . marktag ) except Exception : return if obj . kind != 'compound' : return # Nothing to do if table has no data if ( len ( self . _xarr ) == 0 or len ( self . _yarr ) == 0 or len ( self . _treepaths ) == 0 ) : return # Find markings inside box mask = cobj . contains_arr ( self . _xarr , self . _yarr ) for hlpath in self . _treepaths [ mask ] : self . _highlight_path ( hlpath ) | Highlight all markings inside user drawn box on table . | 259 | 11 |
24,665 | def hl_canvas2table ( self , canvas , button , data_x , data_y ) : self . treeview . clear_selection ( ) # Remove existing highlight if self . markhltag : try : canvas . delete_object_by_tag ( self . markhltag , redraw = True ) except Exception : pass # Nothing to do if no markings are displayed try : obj = canvas . get_object_by_tag ( self . marktag ) except Exception : return if obj . kind != 'compound' : return # Nothing to do if table has no data if ( len ( self . _xarr ) == 0 or len ( self . _yarr ) == 0 or len ( self . _treepaths ) == 0 ) : return sr = 10 # self.settings.get('searchradius', 10) dx = data_x - self . _xarr dy = data_y - self . _yarr dr = np . sqrt ( dx * dx + dy * dy ) mask = dr <= sr for hlpath in self . _treepaths [ mask ] : self . _highlight_path ( hlpath ) | Highlight marking on table when user click on canvas . | 248 | 11 |
24,666 | def _highlight_path ( self , hlpath ) : self . logger . debug ( 'Highlighting {0}' . format ( hlpath ) ) self . treeview . select_path ( hlpath ) # TODO: Does not work in Qt. This is known issue in Ginga. self . treeview . scroll_to_path ( hlpath ) | Highlight an entry in the table and associated marking . | 81 | 11 |
24,667 | def set_marktype_cb ( self , w , index ) : self . marktype = self . _mark_options [ index ] # Mark size is not used for point if self . marktype != 'point' : self . w . mark_size . set_enabled ( True ) else : self . w . mark_size . set_enabled ( False ) | Set type of marking . | 77 | 5 |
24,668 | def set_markwidth ( self ) : try : sz = int ( self . w . mark_width . get_text ( ) ) except ValueError : self . logger . error ( 'Cannot set mark width' ) self . w . mark_width . set_text ( str ( self . markwidth ) ) else : self . markwidth = sz | Set width of marking . | 77 | 5 |
24,669 | def redo ( self , channel , image ) : self . _image = None # Skip cache checking in set_header() info = channel . extdata . _header_info self . set_header ( info , image ) | This is called when image changes . | 47 | 7 |
24,670 | def blank ( self , channel ) : self . _image = None info = channel . extdata . _header_info info . table . clear ( ) | This is called when image is cleared . | 32 | 8 |
24,671 | def clock_resized_cb ( self , viewer , width , height ) : self . logger . info ( "resized canvas to %dx%d" % ( width , height ) ) # add text objects to canvas self . canvas . delete_all_objects ( ) Text = self . canvas . get_draw_class ( 'text' ) x , y = 20 , int ( height * 0.55 ) # text object for the time self . time_txt = Text ( x , y , text = '' , color = self . color , font = self . font , fontsize = self . largesize , coord = 'window' ) self . canvas . add ( self . time_txt , tag = '_time' , redraw = False ) # for supplementary info (date, timezone, etc) self . suppl_txt = Text ( x , height - 10 , text = '' , color = self . color , font = self . font , fontsize = self . smallsize , coord = 'window' ) self . canvas . add ( self . suppl_txt , tag = '_suppl' , redraw = False ) self . canvas . update_canvas ( whence = 3 ) | This method is called when an individual clock is resized . It deletes and reconstructs the placement of the text objects in the canvas . | 254 | 28 |
24,672 | def update_clock ( self , dt ) : dt = dt . astimezone ( self . tzinfo ) fmt = "%H:%M" if self . show_seconds : fmt = "%H:%M:%S" self . time_txt . text = dt . strftime ( fmt ) suppl_text = "{0} {1}" . format ( dt . strftime ( "%Y-%m-%d" ) , self . timezone ) self . suppl_txt . text = suppl_text self . viewer . redraw ( whence = 3 ) | This method is called by the ClockApp whenever the timer fires to update the clock . dt is a timezone - aware datetime object . | 126 | 29 |
24,673 | def add_clock ( self , timezone , color = 'lightgreen' , show_seconds = None ) : if show_seconds is None : show_seconds = self . options . show_seconds clock = Clock ( self . app , self . logger , timezone , color = color , font = self . options . font , show_seconds = show_seconds ) clock . widget . cfg_expand ( 0x7 , 0x7 ) num_clocks = len ( self . clocks ) cols = self . settings . get ( 'columns' ) row = num_clocks // cols col = num_clocks % cols self . clocks [ timezone ] = clock self . grid . add_widget ( clock . widget , row , col , stretch = 1 ) | Add a clock to the grid . timezone is a string representing a valid timezone . | 167 | 18 |
24,674 | def timer_cb ( self , timer ) : dt_now = datetime . utcnow ( ) . replace ( tzinfo = pytz . utc ) self . logger . debug ( "timer fired. utc time is '%s'" % ( str ( dt_now ) ) ) for clock in self . clocks . values ( ) : clock . update_clock ( dt_now ) # update clocks approx every second timer . start ( 1.0 ) | Timer callback . Update all our clocks . | 101 | 8 |
24,675 | def set_table_cb ( self , viewer , table ) : self . clear ( ) tree_dict = OrderedDict ( ) # Extract data as astropy table a_tab = table . get_data ( ) # Fill masked values, if applicable try : a_tab = a_tab . filled ( ) except Exception : # Just use original table pass # This is to get around table widget not sorting numbers properly i_fmt = '{{0:0{0}d}}' . format ( len ( str ( len ( a_tab ) ) ) ) # Table header with units columns = [ ( 'Row' , '_DISPLAY_ROW' ) ] for c in a_tab . columns . values ( ) : col_str = '{0:^s}\n{1:^s}' . format ( c . name , str ( c . unit ) ) columns . append ( ( col_str , c . name ) ) self . widget . setup_table ( columns , 1 , '_DISPLAY_ROW' ) # Table contents for i , row in enumerate ( a_tab , 1 ) : bnch = Bunch . Bunch ( zip ( row . colnames , row . as_void ( ) ) ) i_str = i_fmt . format ( i ) bnch [ '_DISPLAY_ROW' ] = i_str tree_dict [ i_str ] = bnch self . widget . set_tree ( tree_dict ) # Resize column widths n_rows = len ( tree_dict ) if n_rows < self . settings . get ( 'max_rows_for_col_resize' , 5000 ) : self . widget . set_optimal_column_widths ( ) self . logger . debug ( 'Resized columns for {0} row(s)' . format ( n_rows ) ) tablename = table . get ( 'name' , 'NoName' ) self . logger . debug ( 'Displayed {0}' . format ( tablename ) ) | Display the given table object . | 444 | 6 |
24,676 | def build_gui ( self , container ) : vbox , sw , self . orientation = Widgets . get_oriented_box ( container ) vbox . set_border_width ( 4 ) vbox . set_spacing ( 2 ) # create the Treeview always_expand = self . settings . get ( 'always_expand' , True ) color_alternate = self . settings . get ( 'color_alternate_rows' , True ) treeview = Widgets . TreeView ( auto_expand = always_expand , sortable = True , use_alt_row_color = color_alternate ) self . treeview = treeview treeview . setup_table ( self . columns , 3 , 'MODIFIED' ) treeview . set_column_width ( 0 , self . settings . get ( 'ts_colwidth' , 250 ) ) treeview . add_callback ( 'selected' , self . show_more ) vbox . add_widget ( treeview , stretch = 1 ) fr = Widgets . Frame ( 'Selected History' ) captions = ( ( 'Channel:' , 'label' , 'chname' , 'llabel' ) , ( 'Image:' , 'label' , 'imname' , 'llabel' ) , ( 'Timestamp:' , 'label' , 'modified' , 'llabel' ) ) w , b = Widgets . build_info ( captions ) self . w . update ( b ) b . chname . set_text ( '' ) b . chname . set_tooltip ( 'Channel name' ) b . imname . set_text ( '' ) b . imname . set_tooltip ( 'Image name' ) b . modified . set_text ( '' ) b . modified . set_tooltip ( 'Timestamp (UTC)' ) captions = ( ( 'Description:-' , 'llabel' ) , ( 'descrip' , 'textarea' ) ) w2 , b = Widgets . build_info ( captions ) self . w . update ( b ) b . descrip . set_editable ( False ) b . descrip . set_wrap ( True ) b . descrip . set_text ( '' ) b . descrip . set_tooltip ( 'Displays selected history entry' ) vbox2 = Widgets . VBox ( ) vbox2 . set_border_width ( 4 ) vbox2 . add_widget ( w ) vbox2 . add_widget ( w2 ) fr . set_widget ( vbox2 , stretch = 0 ) vbox . add_widget ( fr , stretch = 0 ) container . add_widget ( vbox , stretch = 1 ) btns = Widgets . HBox ( ) btns . set_spacing ( 3 ) btn = Widgets . Button ( 'Close' ) btn . add_callback ( 'activated' , lambda w : self . close ( ) ) btns . add_widget ( btn , stretch = 0 ) btn = Widgets . Button ( "Help" ) btn . add_callback ( 'activated' , lambda w : self . help ( ) ) btns . add_widget ( btn , stretch = 0 ) btns . add_widget ( Widgets . Label ( '' ) , stretch = 1 ) container . add_widget ( btns , stretch = 0 ) self . gui_up = True | This method is called when the plugin is invoked . It builds the GUI used by the plugin into the widget layout passed as container . | 739 | 26 |
24,677 | def redo ( self , channel , image ) : chname = channel . name if image is None : # shouldn't happen, but let's play it safe return imname = image . get ( 'name' , 'none' ) iminfo = channel . get_image_info ( imname ) timestamp = iminfo . time_modified if timestamp is None : reason = iminfo . get ( 'reason_modified' , None ) if reason is not None : self . fv . show_error ( "{0} invoked 'modified' callback to ChangeHistory with a " "reason but without a timestamp. The plugin invoking the " "callback is no longer be compatible with Ginga. " "Please contact plugin developer to update the plugin " "to use self.fv.update_image_info() like Mosaic " "plugin." . format ( imname ) ) # Image somehow lost its history self . remove_image_info_cb ( self . fv , channel , iminfo ) return self . add_entry ( chname , iminfo ) | Add an entry with image modification info . | 221 | 8 |
24,678 | def remove_image_info_cb ( self , gshell , channel , iminfo ) : chname = channel . name if chname not in self . name_dict : return fileDict = self . name_dict [ chname ] name = iminfo . name if name not in fileDict : return del fileDict [ name ] self . logger . debug ( '{0} removed from ChangeHistory' . format ( name ) ) if not self . gui_up : return False self . clear_selected_history ( ) self . recreate_toc ( ) | Delete entries related to deleted image . | 120 | 7 |
24,679 | def add_image_info_cb ( self , gshell , channel , iminfo ) : timestamp = iminfo . time_modified if timestamp is None : # Not an image we are interested in tracking return self . add_entry ( channel . name , iminfo ) | Add entries related to an added image . | 56 | 8 |
24,680 | def drag_drop_cb ( self , viewer , urls ) : channel = self . fv . get_current_channel ( ) if channel is None : return self . fv . open_uris ( urls , chname = channel . name , bulk_add = True ) return True | Punt drag - drops to the ginga shell . | 63 | 12 |
24,681 | def update_highlights ( self , old_highlight_set , new_highlight_set ) : with self . thmblock : un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set # highlight new labels that should be bg = self . settings . get ( 'label_bg_color' , 'lightgreen' ) fg = self . settings . get ( 'label_font_color' , 'black' ) # unhighlight thumb labels that should NOT be highlighted any more for thumbkey in un_hilite_set : if thumbkey in self . thumb_dict : namelbl = self . thumb_dict [ thumbkey ] . get ( 'namelbl' ) namelbl . color = fg for thumbkey in re_hilite_set : if thumbkey in self . thumb_dict : namelbl = self . thumb_dict [ thumbkey ] . get ( 'namelbl' ) namelbl . color = bg if self . gui_up : self . c_view . redraw ( whence = 3 ) | Unhighlight the thumbnails represented by old_highlight_set and highlight the ones represented by new_highlight_set . | 259 | 27 |
24,682 | def have_thumbnail ( self , fitsimage , image ) : chname = self . fv . get_channel_name ( fitsimage ) # Look up our version of the thumb idx = image . get ( 'idx' , None ) path = image . get ( 'path' , None ) if path is not None : path = os . path . abspath ( path ) name = iohelper . name_image_from_path ( path , idx = idx ) else : name = 'NoName' # get image name name = image . get ( 'name' , name ) thumbkey = self . get_thumb_key ( chname , name , path ) with self . thmblock : return thumbkey in self . thumb_dict | Returns True if we already have a thumbnail version of this image cached False otherwise . | 163 | 16 |
24,683 | def auto_scroll ( self , thumbkey ) : if not self . gui_up : return # force scroll to bottom of thumbs, if checkbox is set scrollp = self . w . auto_scroll . get_state ( ) if not scrollp : return bnch = self . thumb_dict [ thumbkey ] # override X parameter because we only want to scroll vertically pan_x , pan_y = self . c_view . get_pan ( ) self . c_view . panset_xy ( pan_x , bnch . image . y ) | Scroll the window to the thumb . | 121 | 7 |
24,684 | def clear_widget ( self ) : if not self . gui_up : return canvas = self . c_view . get_canvas ( ) canvas . delete_all_objects ( ) self . c_view . redraw ( whence = 0 ) | Clears the thumbnail display widget of all thumbnails but does not remove them from the thumb_dict or thumb_list . | 53 | 25 |
24,685 | def load_nddata ( self , ndd , naxispath = None ) : self . clear_metadata ( ) # Make a header based on any NDData metadata ahdr = self . get_header ( ) ahdr . update ( ndd . meta ) self . setup_data ( ndd . data , naxispath = naxispath ) if ndd . wcs is None : # no wcs in ndd obj--let's try to make one from the header self . wcs = wcsmod . WCS ( logger = self . logger ) self . wcs . load_header ( ahdr ) else : # already have a valid wcs in the ndd object # we assume it needs an astropy compatible wcs wcsinfo = wcsmod . get_wcs_class ( 'astropy' ) self . wcs = wcsinfo . wrapper_class ( logger = self . logger ) self . wcs . load_nddata ( ndd ) | Load from an astropy . nddata . NDData object . | 206 | 14 |
24,686 | def set_naxispath ( self , naxispath ) : revnaxis = list ( naxispath ) revnaxis . reverse ( ) # construct slice view and extract it view = tuple ( revnaxis + [ slice ( None ) , slice ( None ) ] ) data = self . get_mddata ( ) [ view ] if len ( data . shape ) != 2 : raise ImageError ( "naxispath does not lead to a 2D slice: {}" . format ( naxispath ) ) self . naxispath = naxispath self . revnaxis = revnaxis self . set_data ( data ) | Choose a slice out of multidimensional data . | 135 | 10 |
24,687 | def get_keyword ( self , kwd , * args ) : try : kwds = self . get_header ( ) return kwds [ kwd ] except KeyError : # return a default if there is one if len ( args ) > 0 : return args [ 0 ] raise KeyError ( kwd ) | Get an item from the fits header if any . | 68 | 10 |
24,688 | def as_nddata ( self , nddata_class = None ) : if nddata_class is None : from astropy . nddata import NDData nddata_class = NDData # transfer header, preserving ordering ahdr = self . get_header ( ) header = OrderedDict ( ahdr . items ( ) ) data = self . get_mddata ( ) wcs = None if hasattr ( self , 'wcs' ) and self . wcs is not None : # for now, assume self.wcs wraps an astropy wcs object wcs = self . wcs . wcs ndd = nddata_class ( data , wcs = wcs , meta = header ) return ndd | Return a version of ourself as an astropy . nddata . NDData object | 157 | 18 |
24,689 | def as_hdu ( self ) : from astropy . io import fits # transfer header, preserving ordering ahdr = self . get_header ( ) header = fits . Header ( ahdr . items ( ) ) data = self . get_mddata ( ) hdu = fits . PrimaryHDU ( data = data , header = header ) return hdu | Return a version of ourself as an astropy . io . fits . PrimaryHDU object | 76 | 19 |
24,690 | def astype ( self , type_name ) : if type_name == 'nddata' : return self . as_nddata ( ) if type_name == 'hdu' : return self . as_hdu ( ) raise ValueError ( "Unrecognized conversion type '%s'" % ( type_name ) ) | Convert AstroImage object to some other kind of object . | 70 | 12 |
24,691 | def hmsToDeg ( h , m , s ) : return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec | Convert RA hours minutes seconds into an angle in degrees . | 38 | 12 |
24,692 | def hmsStrToDeg ( ra ) : hour , min , sec = ra . split ( ':' ) ra_deg = hmsToDeg ( int ( hour ) , int ( min ) , float ( sec ) ) return ra_deg | Convert a string representation of RA into a float in degrees . | 53 | 13 |
24,693 | def dmsStrToDeg ( dec ) : sign_deg , min , sec = dec . split ( ':' ) sign = sign_deg [ 0 : 1 ] if sign not in ( '+' , '-' ) : sign = '+' deg = sign_deg else : deg = sign_deg [ 1 : ] dec_deg = decTimeToDeg ( sign , int ( deg ) , int ( min ) , float ( sec ) ) return dec_deg | Convert a string representation of DEC into a float in degrees . | 101 | 13 |
24,694 | def eqToEq2000 ( ra_deg , dec_deg , eq ) : ra_rad = math . radians ( ra_deg ) dec_rad = math . radians ( dec_deg ) x = math . cos ( dec_rad ) * math . cos ( ra_rad ) y = math . cos ( dec_rad ) * math . sin ( ra_rad ) z = math . sin ( dec_rad ) p11 , p12 , p13 , p21 , p22 , p23 , p31 , p32 , p33 = trans_coeff ( eq , x , y , z ) x0 = p11 * x + p21 * y + p31 * z y0 = p12 * x + p22 * y + p32 * z z0 = p13 * x + p23 * y + p33 * z new_dec = math . asin ( z0 ) if x0 == 0.0 : new_ra = math . pi / 2.0 else : new_ra = math . atan ( y0 / x0 ) if ( ( y0 * math . cos ( new_dec ) > 0.0 and x0 * math . cos ( new_dec ) <= 0.0 ) or ( y0 * math . cos ( new_dec ) <= 0.0 and x0 * math . cos ( new_dec ) < 0.0 ) ) : new_ra += math . pi elif new_ra < 0.0 : new_ra += 2.0 * math . pi #new_ra = new_ra * 12.0 * 3600.0 / math.pi new_ra_deg = new_ra * 12.0 / math . pi * 15.0 #new_dec = new_dec * 180.0 * 3600.0 / math.pi new_dec_deg = new_dec * 180.0 / math . pi return ( new_ra_deg , new_dec_deg ) | Convert Eq to Eq 2000 . | 424 | 9 |
24,695 | def get_rotation_and_scale ( header , skew_threshold = 0.001 ) : ( ( xrot , yrot ) , ( cdelt1 , cdelt2 ) ) = get_xy_rotation_and_scale ( header ) if math . fabs ( xrot ) - math . fabs ( yrot ) > skew_threshold : raise ValueError ( "Skew detected: xrot=%.4f yrot=%.4f" % ( xrot , yrot ) ) rot = yrot lonpole = float ( header . get ( 'LONPOLE' , 180.0 ) ) if lonpole != 180.0 : rot += 180.0 - lonpole return ( rot , cdelt1 , cdelt2 ) | Calculate rotation and CDELT . | 167 | 9 |
24,696 | def get_relative_orientation ( image , ref_image ) : # Get reference image rotation and scale header = ref_image . get_header ( ) ( ( xrot_ref , yrot_ref ) , ( cdelt1_ref , cdelt2_ref ) ) = get_xy_rotation_and_scale ( header ) scale_x , scale_y = math . fabs ( cdelt1_ref ) , math . fabs ( cdelt2_ref ) # Get rotation and scale of image header = image . get_header ( ) ( ( xrot , yrot ) , ( cdelt1 , cdelt2 ) ) = get_xy_rotation_and_scale ( header ) # Determine relative scale of this image to the reference rscale_x = math . fabs ( cdelt1 ) / scale_x rscale_y = math . fabs ( cdelt2 ) / scale_y # Figure out rotation relative to our orientation rrot_dx , rrot_dy = xrot - xrot_ref , yrot - yrot_ref # flip_x = False # flip_y = False # ## # Flip X due to negative CDELT1 # ## if np.sign(cdelt1) < 0: # ## flip_x = True # ## # Flip Y due to negative CDELT2 # ## if np.sign(cdelt2) < 0: # ## flip_y = True # # Optomization for 180 rotations # if np.isclose(math.fabs(rrot_dx), 180.0): # flip_x = not flip_x # rrot_dx = 0.0 # if np.isclose(math.fabs(rrot_dy), 180.0): # flip_y = not flip_y # rrot_dy = 0.0 rrot_deg = max ( rrot_dx , rrot_dy ) res = Bunch . Bunch ( rscale_x = rscale_x , rscale_y = rscale_y , rrot_deg = rrot_deg ) return res | Computes the relative orientation and scale of an image to a reference image . | 456 | 15 |
24,697 | def deg2fmt ( ra_deg , dec_deg , format ) : rhr , rmn , rsec = degToHms ( ra_deg ) dsgn , ddeg , dmn , dsec = degToDms ( dec_deg ) if format == 'hms' : return rhr , rmn , rsec , dsgn , ddeg , dmn , dsec elif format == 'str' : #ra_txt = '%02d:%02d:%06.3f' % (rhr, rmn, rsec) ra_txt = '%d:%02d:%06.3f' % ( rhr , rmn , rsec ) if dsgn < 0 : dsgn = '-' else : dsgn = '+' #dec_txt = '%s%02d:%02d:%05.2f' % (dsgn, ddeg, dmn, dsec) dec_txt = '%s%d:%02d:%05.2f' % ( dsgn , ddeg , dmn , dsec ) return ra_txt , dec_txt | Format coordinates . | 256 | 3 |
24,698 | def deltaStarsRaDecDeg1 ( ra1_deg , dec1_deg , ra2_deg , dec2_deg ) : phi , dist = dispos ( ra1_deg , dec1_deg , ra2_deg , dec2_deg ) return arcsecToDeg ( dist * 60.0 ) | Spherical triangulation . | 70 | 6 |
24,699 | def get_starsep_RaDecDeg ( ra1_deg , dec1_deg , ra2_deg , dec2_deg ) : sep = deltaStarsRaDecDeg ( ra1_deg , dec1_deg , ra2_deg , dec2_deg ) sgn , deg , mn , sec = degToDms ( sep ) if deg != 0 : txt = '%02d:%02d:%06.3f' % ( deg , mn , sec ) else : txt = '%02d:%06.3f' % ( mn , sec ) return txt | Calculate separation . | 137 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.